目录
2.创建MyBatis配置文件SqlMapConfig.xml,
3.创建Spring配置文件applicationContext.xml
三、Spring整合MyBatis_编写数据库、实体类domain、持久层接口dao层、service层
四、Spring整合MyBatis_Spring整合Junit进行单元测试
注意:使用SqlSessionTemplate创建代理对象还是需要注册接口或者映射文件的。
1.在applicationContext.xml中创建MapperScannerConfigurer对象
一、Spring整合MyBatis_搭建环境
我们知道使用MyBatis时需要写大量创建SqlSessionFactoryBuilder、SqlSessionFactory、SqlSession等对象的代码,而Spring的作用是帮助我们创建和管理对象,所以我们可以使用Spring整合MyBatis,简化MyBatis开发。
1.创建Maven项目,引入依赖
<dependencies> <dependency> <groupId>org.mybatisgroupId> <artifactId>mybatisartifactId> <version>3.5.7version> dependency> <dependency> <groupId>mysqlgroupId> <artifactId>mysql-connector-javaartifactId> <version>8.0.26version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-contextartifactId> <version>5.3.13version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-txartifactId> <version>5.2.12.RELEASEversion> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-jdbcartifactId> <version>5.2.12.RELEASEversion> dependency> <dependency> <groupId>org.mybatisgroupId> <artifactId>mybatis-springartifactId> <version>2.0.6version> dependency> <dependency> <groupId>com.alibabagroupId> <artifactId>druidartifactId> <version>1.2.8version> dependency> <dependency> <groupId>junitgroupId> <artifactId>junitartifactId> <version>4.12version> <scope>testscope> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-testartifactId> <version>5.2.12.RELEASEversion> dependency> dependencies>
二、Spring整合MyBatis_编写配置文件
1.编写数据库配置文件db.properties
jdbc.driverClassName=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql:///student jdbc.username=root jdbc.password=1234562.创建MyBatis配置文件SqlMapConfig.xml,
数据源、扫描接口都交由Spring管理,不需要在MyBatis配置文件SqlMapConfig.xml中设置。
configuration PUBLIC "-//mybatis.org//DTD Config3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> configuration>3.创建Spring配置文件applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:comtext="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <comtext:component-scan base-package="com.itbaizhan">comtext:component-scan> <context:property-placeholder location="db.properties">context:property-placeholder> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}">property> <property name="url" value="${jdbc.url}">property> <property name="username" value="${jdbc.username}">property> <property name="password" value="${jdbc.password}">property> bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource">property> <property name="configLocation" value="classpath:SqlMapConfig.xml">property> bean> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.itbaizhan.dao">property> bean> beans>
三、Spring整合MyBatis_编写数据库、实体类domain、持久层接口dao层、service层
1.编写数据库
CREATE DATABASE `student`; USE `student`; DROP TABLE IF EXISTS `student`; CREATE TABLE `student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, `sex` varchar(10) DEFAULT NULL, `address` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; insert into `student`(`id`,`name`,`sex`,`address`) values (1,'百战程序员','男','北京'),(2,'北京尚学 堂','女','北京');2.准备实体类
public class Student { private int id; private String name; private String sex; private String address; // 省略有参、无参构造方法/getter/setter/tostring }3.编写持久层接口
@Repository public interface StudentDao { // 查询所有学生 @Select("select * from student") ListfindAll(); // 添加学生 @Insert("insert into student values (null,#{name},#{sex},#{address})") void add(Student student); }4.编写service层
@Service public class StudentService { // SqlSession对象 @Autowired private SqlSessionTemplate sqlSession; // 使用SqlSession获取代理对象 public ListfindAllStudent(){ StudentDao studentDao = sqlSession.getMapper(StudentDao.class); return studentDao.findAll(); } }
四、Spring整合MyBatis_Spring整合Junit进行单元测试
之前进行单元测试时都需要手动创建 Spring 容器ApplicationContext,接下来在测试时让Spring自动创建容器。1.引入Junit和Spring整合Junit依赖
<dependency> <groupId>junitgroupId> <artifactId>junitartifactId> <version>4.12version> <scope>testscope> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-testartifactId> <version>5.3.13version> dependency>2.编写测试类
- //Junit使用Spring的方式运行代码,即自动创建Spring容器ApplicationContext
- @RunWith(SpringJUnit4ClassRunner.class)
- //Spring容器创建时读取的配置文件或配置类
- //配置类写法@Contextfiguration(classes = 配置类.class)
- //配置文件写法@Contextfiguration(locations = classpath:配置文件.xml)
- @ContextConfiguration(locations = "classpath:applicationContext.xml")
- public class StudentServiceTest {
- @Autowired
- private StudentService studentService;
-
- @Test
- public void testFindAllStudent(){
- List
allStudent = studentService.findAllStudent(); - allStudent.forEach(System.out::println);
- }
-
- @Test
- public void testAddStudent(){
- Student student = new Student(0,"同学","男","北京");
- studentService.addStudent(student);
- }
- }
注意:使用SqlSessionTemplate创建代理对象还是需要注册接口或者映射文件的。
1.在MyBatis配置文件SqlMapConfig.xml中注册接口
configuration PUBLIC "-//mybatis.org//DTD Config3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <mappers> <mapper class="com.itbaizhan.dao.StudentDao">mapper> mappers> configuration>2.创建sqlSessionFactory时指定MyBatis配置文件
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource">property> <property name="configLocation" value="classpath:SqlMapConfig.xml">property> bean>
五、Spring整合MyBatis_自动创建代理对象
Spring提供了MapperScannerConfigurer对象,该对象可以自动扫描包创建代理对象,并将代理对象放入容器中,此时不需要使用SqlSession手动创建代理对象。1.在applicationContext.xml中创建MapperScannerConfigurer对象
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.itbaizhan.dao">property> bean>2.StudentService类直接使用代理对象即可
@Service public class StudentService { // SqlSession对象 // @Autowired // private SqlSessionTemplate sqlSession; // // 使用SqlSession获取代理对象 // public ListfindAllStudent(){ // StudentDao studentDao = sqlSession.getMapper(StudentDao.class); // return studentDao.findAll(); // } // 直接注入代理对象 @Autowired private StudentDao studentDao; public ListfindAllStudent(){ return studentDao.findAll(); } // 直接使用代理对象 public void addStudent(Student student){ studentDao.add(student); } }3.测试
//Junit使用Spring的方式运行代码,即自动创建Spring容器ApplicationContext @RunWith(SpringJUnit4ClassRunner.class) //Spring容器创建时读取的配置文件或配置类 //配置类写法@Contextfiguration(classes = 配置类.class) //配置文件写法@Contextfiguration(locations = classpath:配置文件.xml) @ContextConfiguration(locations = "classpath:applicationContext.xml") public class StudentServiceTest { @Autowired private StudentService studentService; @Test public void testFindAllStudent(){ ListallStudent = studentService.findAllStudent(); allStudent.forEach(System.out::println); } @Test public void testAddStudent(){ Student student = new Student(0,"同学","男","北京"); studentService.addStudent(student); } }