目录
一、回顾MyBatis入门
跳转到目录
也包括一些Spring需要的坐标
<dependencies>
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
<scope>provided</scope>
</dependency>
<!--日志组件-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
<scope>test</scope>
</dependency>
<!--MySQL驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
<scope>runtime</scope>
</dependency>
<!--Druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.19</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.0</version>
</dependency>
<!--Spring-->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
</dependencies>
数据库关系表设计
CREATE TABLE `t_user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`age` tinyint(4) DEFAULT NULL,
`born_date` date DEFAULT NULL,
`head_img` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
domain实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
private Date bornDate;
private String headImg;
}
实现mybatis的配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.sunny.domain"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="1111"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mappers/UserMapper.xml"/>
</mappers>
</configuration>
</configuration>
UserMapper接口编写
public interface UserMapper {
List<User> selectAll();
}
接口对应的Mapper映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--命名空间,类似包的概念: namespace:绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.sunny.ssm.mapper.UserMapper">
<resultMap id="BaseResultMap" type="User">
<result property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<result property="bornDate" column="born_date"/>
<result property="headImg" column="head_img"/>
</resultMap>
<select id="selectAll" resultMap="BaseResultMap">
SELECT id, name, age, born_date, head_img FROM t_user;
</select>
</mapper>
测试类
public class UserMapperTest {
@Test
public void test1() throws Exception{
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
SqlSession sqlSession = factory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.selectAll();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
}
二、Spring集成MyBatis
跳转到目录
官方文档: mybatis-spring
什么是 MyBatis-Spring?
- MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中。
- 在开始使用 MyBatis-Spring 之前,你需要先熟悉 Spring 和 MyBatis 这两个框架和有关它们的术语。
MyBatis-Spring 需要以下版本:
Spring整合MyBatis, 主要目的就是把MyBatis核心配置文件中的内容,交给Spring来处理; 再简单点来说, 将MyBatis的SqlSessionFactory
和Mapper
的创建交给Spring处理;
1、简单介绍
<dependencies>
<!--spring_mybatis桥梁-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.0</version>
</dependency>
</dependencies>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<!--配置sqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能通过构造器注入sqlSessionFactory,因为没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
现在,这个 bean 就可以直接注入到你的 DAO bean 中了。你需要在你的 bean 中添加一个 SqlSession 属性,就像下面这样:
public class UserMapperImpl implements UserMapper{
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
public List<User> selectAll() {
return sqlSession.getMapper(UserMapper.class).selectAll();
}
}
按下面这样,注入 SqlSessionTemplate
:
<!-- 创建mapper对象-->
<bean id="userMapperImpl" class="com.sunny.ssm.mapper.UserMapperImpl">
<property name="sqlSession" ref="sqlSession"/>
</bean>
三、整合实现一
1、创建Spring配置文件applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
2、配置数据源替换mybaits的数据源
db.properties
#连接数据库的四个基本要素
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm
jdbc.username=root
jdbc.password=1111
#druid连接池其他配置,省略
<!--DataSource: 使用Spirng的数据源替换Mybatis的配置, 可以使用c3p0,dbcp,druid,或者spring提供的jdbc-->
<!-- 加载数据库配置信息 -->
<context:property-placeholder location="classpath:db.properties" system-properties-mode="NEVER"/>
<!-- 连接池对象 -->
<bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="username" value="${jdbc.username}"/>
<property name="url" value="${jdbc.url}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
3、配置SqlSessionFactory,关联MyBatis
<!-- 配置SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 1:连接池 -->
<property name="dataSource" ref="myDataSource"/>
<!-- 2:绑定MyBatis总配置文件 -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!-- 3:配置别名扫描 -->
<property name="typeAliasesPackage" value="com.sunny.ssm"/>
<!-- 4:加载mapper文件 -->
<property name="mapperLocations" value="classpath:mappers/*Mapper.xml"/>
</bean>
4、注册sqlSessionTemplate,关联sqlSessionFactory;
<!--配置sqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能通过构造器注入sqlSessionFactory,因为没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
5、增加Mapper(Dao)接口的实现类;私有化sqlSessionTemplate
public class UserMapperImpl implements UserMapper{
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
public List<User> selectAll() {
return sqlSession.getMapper(UserMapper.class).selectAll();
}
}
6、注册bean实现
<bean id="userMapperImpl" class="com.sunny.ssm.mapper.UserMapperImpl">
<property name="sqlSession" ref="sqlSession"/>
</bean>
7、测试
@Test
public void test1() throws Exception{
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapperImpl", UserMapper.class);
for (User user : userMapper.selectAll()) {
System.out.println(user);
}
}
结果成功输出!现在我们的Mybatis配置文件的状态!发现都可以被Spring整合!
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--日志技术-->
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
</configuration>
其实我们可以通过Spirng完全将mybatis配置文件去除,这里还是保留一个配置吧!
四、整合实现二
跳转到目录
让Dao继承Support类 , 直接利用 getSqlSession()
获得 , 然后直接注入SqlSessionFactory
. 比起方式1 , 不需要管理SqlSessionTemplate , 而且对事务的支持更加友好
官方文档截图:
1、将我们上面写的UserMapperImpl修改一下
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper {
public List<User> selectAll() {
return getSqlSession().getMapper(UserMapper.class).selectAll();
}
}
2、修改bean的配置
<bean id="userMapperImpl" class="com.sunny.ssm.mapper.UserMapperImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
3、测试
@Test
public void test2() throws Exception{
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapperImpl", UserMapper.class);
for (User user : userMapper2.selectAll()) {
System.out.println(user);
}
}
五、整合实现三
跳转到目录
前两种的整合实现方式,都创建了Dao接口的实现类,通过实现类来获取mapper对象;
使用整合方式三,我们告诉Spring,让他来帮我们创建mapper的代理对象即可!
1、配置MapperFactoryBean,Spring帮我们创建 Mapper的代理对象
<!-- 创建mapper, 因为之前没有写mapper的实现类,mybatis帮我们创建的代理类 所以要告诉Spring,帮我们创建mapper的代理对象 -->
<!-- 配置MapperFactoryBean,Spring帮我们创建 Mapper的代理对象-->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="sqlSessionFactory" ref="mySqlSessionFactory"/>
<!--给哪个接口创建代理对象-->
<property name="mapperInterface" value="com.sunny.ssm.mapper.UserMapper"/>
</bean>
或者采用下面扫描的方式
<!--扫描接口包路径,生成包下所有接口的代理对象,并且放入spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.sunny.mapper"/>
</bean>
此时的applicationContext.xml文件; 其他和方式一相同
2、测试
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelectAll(){
/* // 非DI注入的方式 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserMapper mapper = context.getBean("userMapper", UserMapper.class); for (User user : mapper.selectAll()) { System.out.println(user); }*/
// DI注入方式
List<User> users = userMapper.selectAll();
for (User user : users) {
System.out.println(user);
}
}
}
此时, 通过DI注入的方式获取到mapper对象,然后进行CRUD即可!
总结 : 整合到spring中以后可以完全不要mybatis的配置文件,除了这些方式可以实现整合之外,我们还可以使用注解来实现
今天的文章Spring集成MyBatis的三种实现方式分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/27142.html