Spring 整合 MyBatis
回顾MyBatis开发流程
首先回顾一下MyBatis的开发流程
- 导入 jar 包
- junit
- mybatis
- mysql
- spring相关
- aop织入
- mybatis-spring(new)
- 配置xml文件
- 创建对应数据库表的实体类
- 创建接口和方法
- 配置对应接口的xml文件,绑定方法
- 测试
整合思路
- xml编写数据源DataSource
- SqlSessionFactory
- SqlSessionTemplate
- 需要给接口加一个额外的实现类
- 将自己写的实现类注入到Spring中
- 测试使用
项目整体架构
对应数据库中的 user 表有一对应的 User pojo 类,字段名如下。
public class User {
private int id;
private String name;
private String pwd;
}
对应 pojo 类有映射接口 UserMapper
public interface UserMapper {
List<User> selectById(Map<String,Integer> map);
}
对应UserMapper类有一个 XML 映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hudu.mapper.UserMapper">
<select id="selectById" parameterType="map" resultType="user">
select * from user
<where>
<if test="uid != null">
id = #{uid}
</if>
<if test="uname != null">
and name = #{uname}
</if>
</where>
</select>
</mapper>
外部 properties 文件
#db.properties文件
#注意 mysql 8.0 之后 driver 为 com.mysql.cj.jdbc.Driver
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username=username
password=password
mybatis-config.xml 配置文件,注释掉的部分,包括 properties 引入外部文件、environment 环境配置等都是可以通过 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>
<!-- <properties resource="db.properties"/>-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<typeAliases>
<package name="com.hudu.pojo"/>
</typeAliases>
<!-- <environments default="development">-->
<!-- <environment id="development">-->
<!-- <transactionManager type="JDBC"/>-->
<!-- <dataSource type="POOLED">-->
<!-- <property name="driver" value="${driver}"/>-->
<!-- <property name="url" value="${url}"/>-->
<!-- <property name="username" value="${username}"/>-->
<!-- <property name="password" value="${password}"/>-->
<!-- </dataSource>-->
<!-- </environment>-->
<!-- </environments>-->
<!-- <mappers>-->
<!-- <mapper resource="com/hudu/mapper/UserMapper.xml"/>-->
<!-- </mappers>-->
</configuration>
三种Spring整合MyBatis的方式
- 第一种,通过 SqlSessionTemplate
UserMapperImpl 继承 UserMapper 接口,实现其中的方法。通过 Set 方法注入 SqlSessionTemplate,即SqlSession。
public class UserMapperImpl implements UserMapper {
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
public List<User> selectById(Map<String, Integer> map) {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.selectById(map);
}
}
配置spring-mybatis.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"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="szy10086"/>
</bean>
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/hudu/mapper/UserMapper.xml"/>
</bean>
<!--SqlSessionTemplate就是我们使用的SqlSession-->
<bean id="SqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<bean id="userMapper" class="com.hudu.mapper.UserMapperImpl">
<property name="sqlSession" ref="SqlSession"/>
</bean>
</beans>
测试
@Test
public void test2() {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-mapper.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
HashMap<String,Integer> map = new HashMap<String, Integer>();
map.put("uid",1);
List<User> users = userMapper.selectById(map);
for (User user : users) {
System.out.println(user);
}
}
- 第二种,主要改变在 Impl 实现类和 XML 配置文件
原先是通过 SqlSessionTemplate,这里通过继承 SqlSessionDaoSupport,里面有 getSqlSession 这个方法,可以直接获取到 SqlSession。
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
public List<User> selectById(Map<String, Integer> map) {
return getSqlSession().getMapper(UserMapper.class).selectById(map);
}
}
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
public List<User> selectById(Map<String, Integer> map) {
return getSqlSession().getMapper(UserMapper.class).selectById(map);
}
}
配置 xml 文件,可以对比上两种方法,查看他们的不同之处。
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="szy10086"/>
</bean>
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/hudu/mapper/UserMapper.xml"/>
</bean>
<bean id="userMapper" class="com.hudu.mapper.UserMapperImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
- 第三种,通过包自动扫描
这就不需要再创建 Impl 实现类了,只需要在 xml 文件中添加包扫描,底层就会自动帮你做之前的事情。
<!--配置dao按口扫描包,动态的实现了Dao接口可以注入到Spring容器中! -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--注入sqlSessionFactory-->
<property name="basePackage" value="com.hudu.mapper"/>
</bean>
测试
@Test
public void test2() {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-mapper.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
HashMap<String,Integer> map = new HashMap<String, Integer>();
map.put("uid",1);
List<User> users = userMapper.selectById(map);
for (User user : users) {
System.out.println(user);
}
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: