• 05 Spring整合MyBatis


    目录

    一、Spring整合MyBatis_搭建环境

    1.创建Maven项目,引入依赖

    二、Spring整合MyBatis_编写配置文件

    1.编写数据库配置文件db.properties

    2.创建MyBatis配置文件SqlMapConfig.xml,

    3.创建Spring配置文件applicationContext.xml

    三、Spring整合MyBatis_编写数据库、实体类domain、持久层接口dao层、service层

    1.编写数据库

    2.准备实体类

    3.编写持久层接口

    4.编写service层

    四、Spring整合MyBatis_Spring整合Junit进行单元测试

    1.引入Junit和Spring整合Junit依赖

    2.编写测试类

    注意:使用SqlSessionTemplate创建代理对象还是需要注册接口或者映射文件的。

    五、Spring整合MyBatis_自动创建代理对象

    1.在applicationContext.xml中创建MapperScannerConfigurer对象

    2.StudentService类直接使用代理对象即可

    3.测试


    一、Spring整合MyBatis_搭建环境

     我们知道使用MyBatis时需要写大量创建SqlSessionFactoryBuilder、SqlSessionFactorySqlSession等对象的代码,而Spring的作用是帮助我们创建和管理对象,所以我们可以使用Spring整合MyBatis,简化MyBatis开发。

    1.创建Maven项目,引入依赖

    1. <dependencies>
    2. <dependency>
    3. <groupId>org.mybatisgroupId>
    4. <artifactId>mybatisartifactId>
    5. <version>3.5.7version>
    6. dependency>
    7. <dependency>
    8. <groupId>mysqlgroupId>
    9. <artifactId>mysql-connector-javaartifactId>
    10. <version>8.0.26version>
    11. dependency>
    12. <dependency>
    13. <groupId>org.springframeworkgroupId>
    14. <artifactId>spring-contextartifactId>
    15. <version>5.3.13version>
    16. dependency>
    17. <dependency>
    18. <groupId>org.springframeworkgroupId>
    19. <artifactId>spring-txartifactId>
    20. <version>5.2.12.RELEASEversion>
    21. dependency>
    22. <dependency>
    23. <groupId>org.springframeworkgroupId>
    24. <artifactId>spring-jdbcartifactId>
    25. <version>5.2.12.RELEASEversion>
    26. dependency>
    27. <dependency>
    28. <groupId>org.mybatisgroupId>
    29. <artifactId>mybatis-springartifactId>
    30. <version>2.0.6version>
    31. dependency>
    32. <dependency>
    33. <groupId>com.alibabagroupId>
    34. <artifactId>druidartifactId>
    35. <version>1.2.8version>
    36. dependency>
    37. <dependency>
    38. <groupId>junitgroupId>
    39. <artifactId>junitartifactId>
    40. <version>4.12version>
    41. <scope>testscope>
    42. dependency>
    43. <dependency>
    44. <groupId>org.springframeworkgroupId>
    45. <artifactId>spring-testartifactId>
    46. <version>5.2.12.RELEASEversion>
    47. dependency>
    48. dependencies>

    二、Spring整合MyBatis_编写配置文件

    1.编写数据库配置文件db.properties

    1. jdbc.driverClassName=com.mysql.cj.jdbc.Driver
    2. jdbc.url=jdbc:mysql:///student
    3. jdbc.username=root
    4. jdbc.password=123456

    2.创建MyBatis配置文件SqlMapConfig.xml

    数据源、扫描接口都交由Spring管理,不需要在MyBatis配置文件SqlMapConfig.xml中设置。

    1. configuration PUBLIC "-//mybatis.org//DTD Config3.0//EN"
    2. "http://mybatis.org/dtd/mybatis-3-config.dtd">
    3. <configuration>
    4. configuration>

    3.创建Spring配置文件applicationContext.xml

    1. <beans xmlns="http://www.springframework.org/schema/beans"
    2. xmlns:context="http://www.springframework.org/schema/context"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:comtext="http://www.springframework.org/schema/context"
    5. xsi:schemaLocation="http://www.springframework.org/schema/beans
    6. http://www.springframework.org/schema/beans/spring-beans.xsd
    7. http://www.springframework.org/schema/context
    8. http://www.springframework.org/schema/context/spring-context.xsd">
    9. <comtext:component-scan base-package="com.itbaizhan">comtext:component-scan>
    10. <context:property-placeholder location="db.properties">context:property-placeholder>
    11. <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    12. <property name="driverClassName" value="${jdbc.driverClassName}">property>
    13. <property name="url" value="${jdbc.url}">property>
    14. <property name="username" value="${jdbc.username}">property>
    15. <property name="password" value="${jdbc.password}">property>
    16. bean>
    17. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    18. <property name="dataSource" ref="dataSource">property>
    19. <property name="configLocation" value="classpath:SqlMapConfig.xml">property>
    20. bean>
    21. <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    22. <property name="basePackage" value="com.itbaizhan.dao">property>
    23. bean>
    24. beans>

    三、Spring整合MyBatis_编写数据库、实体类domain、持久层接口dao层、service层

    1.编写数据库

    1. CREATE DATABASE `student`;
    2. USE `student`;
    3. DROP TABLE IF EXISTS `student`;
    4. CREATE TABLE `student` (
    5.  `id` int(11) NOT NULL AUTO_INCREMENT,
    6.  `name` varchar(255) DEFAULT NULL,
    7.  `sex` varchar(10) DEFAULT NULL,
    8.  `address` varchar(255) DEFAULT NULL,
    9.  PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
    10. insert  into
    11. `student`(`id`,`name`,`sex`,`address`)
    12. values (1,'百战程序员','男','北京'),(2,'北京尚学
    13. 堂','女','北京');

    2.准备实体类

    1. public class Student {
    2.    private int id;
    3.    private String name;
    4.    private String sex;
    5.    private String address;
    6.    
    7.    // 省略有参、无参构造方法/getter/setter/tostring
    8. }

    3.编写持久层接口

    1. @Repository
    2. public interface StudentDao {
    3. // 查询所有学生
    4. @Select("select * from student")
    5. List findAll();
    6. // 添加学生
    7. @Insert("insert into student values (null,#{name},#{sex},#{address})")
    8. void add(Student student);
    9. }

    4.编写service层

    1. @Service
    2. public class StudentService {
    3.    // SqlSession对象
    4.    @Autowired
    5.    private SqlSessionTemplate sqlSession;
    6.    // 使用SqlSession获取代理对象
    7.    public List findAllStudent(){
    8.        StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
    9.        return studentDao.findAll();
    10.   }
    11. }

    四、Spring整合MyBatis_Spring整合Junit进行单元测试

    之前进行单元测试时都需要手动创建 Spring 容器ApplicationContext,接下来在测试时让Spring自动创建容器。

    1.引入Junit和Spring整合Junit依赖

    1. <dependency>
    2.    <groupId>junitgroupId>
    3.    <artifactId>junitartifactId>
    4.    <version>4.12version>
    5.    <scope>testscope>
    6. dependency>
    7. <dependency>
    8.    <groupId>org.springframeworkgroupId>
    9.    <artifactId>spring-testartifactId>
    10.    <version>5.3.13version>
    11. dependency>

    2.编写测试类

    1. //Junit使用Spring的方式运行代码,即自动创建Spring容器ApplicationContext
    2. @RunWith(SpringJUnit4ClassRunner.class)
    3. //Spring容器创建时读取的配置文件或配置类
    4. //配置类写法@Contextfiguration(classes = 配置类.class)
    5. //配置文件写法@Contextfiguration(locations = classpath:配置文件.xml)
    6. @ContextConfiguration(locations = "classpath:applicationContext.xml")
    7. public class StudentServiceTest {
    8. @Autowired
    9. private StudentService studentService;
    10. @Test
    11. public void testFindAllStudent(){
    12. List allStudent = studentService.findAllStudent();
    13. allStudent.forEach(System.out::println);
    14. }
    15. @Test
    16. public void testAddStudent(){
    17. Student student = new Student(0,"同学","男","北京");
    18. studentService.addStudent(student);
    19. }
    20. }

    注意:使用SqlSessionTemplate创建代理对象还是需要注册接口或者映射文件的。

    1.在MyBatis配置文件SqlMapConfig.xml中注册接口

    1. configuration PUBLIC "-//mybatis.org//DTD Config3.0//EN"
    2. "http://mybatis.org/dtd/mybatis-3-config.dtd">
    3. <configuration>
    4. <mappers>
    5. <mapper class="com.itbaizhan.dao.StudentDao">mapper>
    6. mappers>
    7. configuration>

    2.创建sqlSessionFactory时指定MyBatis配置文件

    1. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    2. <property name="dataSource" ref="dataSource">property>
    3. <property name="configLocation" value="classpath:SqlMapConfig.xml">property>
    4. bean>

    五、Spring整合MyBatis_自动创建代理对象

    Spring提供了MapperScannerConfigurer对象,该对象可以自动扫描包创建代理对象,并将代理对象放入容器中,此时不需要使用SqlSession手动创建代理对象。

    1.在applicationContext.xml中创建MapperScannerConfigurer对象

    1. <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    2. <property name="basePackage" value="com.itbaizhan.dao">property>
    3. bean>

    2.StudentService类直接使用代理对象即可

    1. @Service
    2. public class StudentService {
    3. // SqlSession对象
    4. // @Autowired
    5. // private SqlSessionTemplate sqlSession;
    6. //
    7. // 使用SqlSession获取代理对象
    8. // public List findAllStudent(){
    9. // StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
    10. // return studentDao.findAll();
    11. // }
    12. // 直接注入代理对象
    13. @Autowired
    14. private StudentDao studentDao;
    15. public List findAllStudent(){
    16. return studentDao.findAll();
    17. }
    18. // 直接使用代理对象
    19. public void addStudent(Student student){
    20. studentDao.add(student);
    21. }
    22. }

    3.测试

    1. //Junit使用Spring的方式运行代码,即自动创建Spring容器ApplicationContext
    2. @RunWith(SpringJUnit4ClassRunner.class)
    3. //Spring容器创建时读取的配置文件或配置类
    4. //配置类写法@Contextfiguration(classes = 配置类.class)
    5. //配置文件写法@Contextfiguration(locations = classpath:配置文件.xml)
    6. @ContextConfiguration(locations = "classpath:applicationContext.xml")
    7. public class StudentServiceTest {
    8. @Autowired
    9. private StudentService studentService;
    10. @Test
    11. public void testFindAllStudent(){
    12. List allStudent = studentService.findAllStudent();
    13. allStudent.forEach(System.out::println);
    14. }
    15. @Test
    16. public void testAddStudent(){
    17. Student student = new Student(0,"同学","男","北京");
    18. studentService.addStudent(student);
    19. }
    20. }
  • 相关阅读:
    Python使用lxml解析XML格式化数据
    django-rest-framework 基础三 认证、权限和频率
    codeforces 1635E-Cars (二分图染色+拓扑排序)
    goweb入门
    Spring Cloud 网关的配置示例
    Mac下Qt设置应用程序名称--多国语言
    Fastjson Sec
    公共4G广播音柱有哪些用处
    数字图像处理—— 实验五 基于图像分割的车牌定位识别
    uniapp 小程序AP配网
  • 原文地址:https://blog.csdn.net/m0_51697147/article/details/126100168