Version: Next
整合Mybatis
- 导入相关jar包
- junit
- Mybatis
- Mysql数据库
- Spring
- Aop织入
- Mybatis-Spring [new]
- 编写配置文件
- 测试
环境搭建
新建Maven模块spring-10-mybatis
导包
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.46</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.2</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.2.0.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.1.9.RELEASE</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>2.0.2</version></dependency>
回忆Mybatis
编写实体类
编写核心配置文件
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><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/test?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/><property name="username" value="root"/><property name="password" value="root"/></dataSource></environment></environments><mappers><mapper resource="com/bsx/mapper/UserMapper.xml"/></mappers></configuration>
编写接口
public interface UserMapper {public List<User> queryUser();}编写Mapper.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.bsx.mapper.UserMapper"><select id="queryUser" resultType="com.bsx.pojo.User">SELECT * FROM USER;</select></mapper>解决找不到Mapper.xml文件的问题 在pom.xml中添加
<build><resources><resource><directory>src/main/resources</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>true</filtering></resource><resource><directory>src/main/java</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>true</filtering></resource></resources></build>测试
@Testpublic void testMybatis() throws IOException {InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();try {UserMapper mapper = sqlSession.getMapper(UserMapper.class);List<User> users = mapper.queryUser();for (User user : users) {System.out.println(user);}} catch (Exception e) {e.printStackTrace();} finally {sqlSession.close();}}
1. Spring整合Mybatis
1.1 Mybatis-Spring
什么是Mybatis-Spring
帮助将Mybatis代码无缝的整合到Spring中。它允许Mybatis参与到Spring的事务管理中,创建映射其Mapper和sqlSession
并注入到bean中,以及将Mybatis的异常转换为Spring的DataAccessException
。最终可以做到代码不依赖于Mybatis、Spring或Mybatis-Spring
1.1.1 导包
在环境搭建部分导过了
1.1.2 整合方式一 [重要]
Spring容器 -> 新建spring-dao.xml 注册以下东西
- sqlSessionFactory (可以实现一切mybatis核心配置文件的功能)
- 指定数据源DataSource
- 绑定Mybatis配置文件
- 绑定mapper.xml文件
- DataSource
- 使用Spring数据源替换Mybatis的配置 (还可用c3p0 druid)
DriverManagerDataSource
类 - 删除Mybatis核心配置文件中关于连接数据库的配置
- 使用Spring数据源替换Mybatis的配置 (还可用c3p0 druid)
- SqlSessionTemplate (代替SqlSession)
- 构造器注入,要求传入一个
sqlSessionFactory
- 构造器注入,要求传入一个
<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/beanshttps://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttps://www.springframework.org/schema/aop/spring-aop.xsd"><!-- DataSource 来自导入的包spring jdbc --><bean id="datasource"class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/><property name="username" value="root"/><property name="password" value="root"/></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/bsx/mapper/*.xml"/></bean></beans>- sqlSessionFactory (可以实现一切mybatis核心配置文件的功能)
Mapper实现类MapperImpl 所有操作使用sqlSessionTemplate来执行
public class UserMapperImpl implements UserMapper{private SqlSessionTemplate sqlSession;//用来让Spring注入public void setSqlSession(SqlSessionTemplate sqlSession) {this.sqlSession = sqlSession;}public List<User> queryUser() {UserMapper mapper = sqlSession.getMapper(UserMapper.class);List<User> users = mapper.queryUser();return users;}}把实现类注册到Spring容器
<!-- DataSource 来自导入的包spring jdbc --><bean id="datasource"class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/><property name="username" value="root"/><property name="password" value="root"/></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/bsx/mapper/*.xml"/></bean><!-- sqlSessionTemplate 构造器注入一个sqlSessionFactory--><bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"><constructor-arg index="0" ref="sqlSessionFactory"/></bean><!-- userMapperImpl--><bean id="userMapper" class="com.bsx.mapper.UserMapperImpl"><property name="sqlSession" ref="sqlSession"/></bean>- 新建一个
applicationContext.xml
引入上面的spring-dao.xml
<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/beanshttps://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttps://www.springframework.org/schema/aop/spring-aop.xsd"><import resource="spring-dao.xml"/></beans>
- 新建一个
测试
@Testpublic void testSpringMybatis(){ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");UserMapper userMapper = context.getBean("userMapper", UserMapper.class);List<User> users = userMapper.queryUser();for (User user : users) {System.out.println(user);}}
步骤
- 编写数据源配置
- 用sqlSessionFactoryBean 创建 sqlSessionFactory
- 创建sqlSessionTemplate
- 需要给mapper接口加实现类 [新]
- 将编写的实现类注册到Spring容器,提供set方法让spring注入
- 编写测试,直接从Spring容器拿Mapper实现类对象,调用方法
1.1.3 整合方式二
这种方式继承sqlSessionDaoSupport
类,然后直接使用它的getSqlSession
方法获得sqlSessionFactoryTemplate
对象,这种方式不需要在Spring中注册一个sqlSessionFactoryTemplate
这种方式要求在将实现类注册到Spring容器时传入一个sqlSessionFactory
对象,因为sqlSessionDaoSupport
需要它来实例化sqlSessionTemplate
mapper实现类
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {public List<User> queryUser() {return getSqlSession().getMapper(UserMapper.class).queryUser();}}注册到Spring
<bean id="userMapper2" class="com.bsx.mapper.UserMapperImpl2"><property name="sqlSessionFactory" ref="sqlSessionFactory"/></bean>测试
@Testpublic void testSpringMybatis(){ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");UserMapper userMapper = context.getBean("userMapper2", UserMapper.class);List<User> users = userMapper.queryUser();for (User user : users) {System.out.println(user);}}