如何“优雅”的将Spring与Mybatis整合(xml方式)

  • @[TOC]
    思路:
    SqlSessionFactory -> SqlSession ->StudentMapper ->CRUD
    Spring整合Mybatis时,我们如果只需要SqlSessionFactory 那么其他的功能都是可以实现的,所以在整合时就是将Mybatis的SqlSessionFactory 交给Spring的Ioc容器来管理。

    项目的结构图:
    在这里插入图片描述
    整合的步骤:

    1.炸包

    mybatis-spring.jar
    spring-tx.jar
    spring-jdbc.jar
    spring-expression.jar
    spring-context-support.jar
    spring-core.jar
    spring-context.jar
    spring-beans.jar
    spring-aop.jar
    spring-web.jar
    commons-logging.jar
    commons-dbcp.jar
    mysql-connector-java.jar
    mybatis.jar
    log4j.jar
    commons-pool.jar

    当然,大家也可以用Maven添加依赖:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <spring.version>5.0.3.RELEASE</spring.version>
    <mybatis.version>3.4.4</mybatis.version>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    </properties>
    <dependencies>
    <!--单元测试-->
    <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
    </dependency>
    <!-- 第一部分:Spring 配置-->
    <!-- Spring core -->
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <!-- Spring DAO -->
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <!-- Spring mvc -->
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <!-- 数据库 -->
    <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.38</version>
    </dependency>
    <!-- 数据库连接池 -->
    <dependency>
    <groupId>com.mchange</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.5.2</version>
    </dependency>
    <!-- MyBatis -->
    <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>${mybatis.version}</version>
    </dependency>
    <!-- mybatis-spring整合包 -->
    <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.1</version>
    </dependency>
    <!-- 第四部分:日志 -->
    <!--日志-->
    <dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.1.1</version>
    </dependency>
    <dependency>
    <groupId>commons-dbcp</groupId>
    <artifactId>commons-dbcp</artifactId>
    <version>1.4</version>
    </dependency>
    <!--依赖的jar-->
    <dependency>
    <groupId>commons-pool</groupId>
    <artifactId>commons-pool</artifactId>
    <version>1.5.4</version>
    </dependency>
    </dependencies>

    2.类-表

    在这里插入图片描述

    • Student
      1
      2
      3
      4
      5
      6
      7
      8
      public class Student {

      private int stuNo;
      private String stuName;
      private int stuAge;

      //getter,setter....
      }

      3.Mybatis配置文件:conf.xml

      1
      2


      4.通过mapper.xml将类、表建立映射关系

    5.在Spring配置文件中配,SqlSessionFactoy和数据源

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    <?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:context="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">
    <!--加载配置文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--第二种-->
    <!--<bean id="config" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">-->
    <!--<property name="locations">-->
    <!--<array>-->
    <!--<value>classpath:jdbc.properties</value>-->
    <!--</array>-->
    <!--</property>-->
    <!--</bean>-->
    <!-- 配置数据库信息(替代mybatis的配置文件conf.xml)-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="${driver}"></property>
    <property name="url" value="${url}"></property>
    <property name="username" value="${username}"></property>
    <property name="password" value="${password}"></property>
    <property name="maxActive" value="${maxActive}"></property>
    <property name="maxIdle" value="${maxIdle}"></property>
    </bean>

    <!-- 在Spring中创建SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <!--引用配置好的数据源-->
    <property name="dataSource" ref="dataSource"></property>
    <!--加载mybatis的配置文件-->
    <property name="configLocation" value="classpath:config.xml"></property>
    </bean>
    </beans>
    • jdbc.properties
      1
      2
      3
      4
      5
      6
      driver=com.mysql.jdbc.Driver
      url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=true
      username=root
      password=
      maxIdle=1000
      maxActive=500

      6.使用Spring-MyBatis整合产物开发程序

      目标:

      通过spring产生mybatis最终操作需要 的动态mapper对象(StudentMapper对象)
      Spring产生动态mapper对象有3种方法:

    a.Dao层实现类 继承 SqlSessionDaoSupport类

    SqlSessionDaoSupport类提供了一个属性:SqlSession
    在这里插入图片描述

    • StudentMapper
      1
      2
      3
      4
      5
      public interface StudentMapper {

      public void addStudent(Student student);

      }
    • studentMapper.xml
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      <?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">
      <mapper namespace="com.itt.mapper.StudentMapper">

      <insert id="addStudent" parameterType="Student">
      insert into student22(stuno,stuname,stuage)
      values(#{stuNo},#{stuName},#{stuAge})
      </insert>

      </mapper>
      在这里插入图片描述
    • StudentDaoImpl
      1
      2
      3
      4
      5
      6
      7
      8
      9
      public class StudentDaoImpl extends SqlSessionDaoSupport implements StudentMapper {
      public void addStudent(Student student) {
      //从父类中获取到sqlSession对象
      SqlSession session = super.getSqlSession();
      StudentMapper studentDao = session.getMapper(StudentMapper.class);
      studentDao.addStudent(student);

      }
      }
      在这里插入图片描述
    • StudentServiceImpl
      1
      public class StudentServiceImpl implements IStudentService {
private StudentMapper studentMapper;

public void setStudentMapper(StudentMapper studentMapper) {
    this.studentMapper = studentMapper;
}

public void addStudent(Student student) {
    //调用dao
    studentMapper.addStudent(student);
}

}

1
2
3
4
5
6
7
* IStudentService
```java
public interface IStudentService {

public void addStudent(Student student);

}

  • config.xml
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    <?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.itt"/>
    </typeAliases>
    <!-- 数据库的相关信息
    交给Spring来创建
    -->

    <!-- 加载映射文件studentMapper.xml-->
    <mappers>
    <mapper resource="com/itt/mapper/StudentMapper.xml"></mapper>
    </mappers>

    </configuration>
  • AppTest
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    @Test
    public void demo1(){

    ClassPathXmlApplicationContext applicationContext =
    new ClassPathXmlApplicationContext("applicationContext.xml");
    IStudentService studentService =
    applicationContext.getBean("studentService",IStudentService.class);

    Student student = new Student();
    student.setStuAge(20);
    student.setStuNam("hk");
    student.setStuNo(100);
    studentService.addStudent(student);
    }
  • 运行成功!*
    在这里插入图片描述
  • 数据也到了库中!*
    在这里插入图片描述
  • 这样就实现了Spring-Mybatis的整合!*
    此方法的改进:
    可以将config.xml文件中的加载映射文件studentMapper.xml也交给Spring来加载,代码如下:
    在这里插入图片描述
  • 注意:*
    使用mybatis时,增删改时必须手动提交事务!
    在使用Spring时,默认自动提交事务!

    b.第二种方式,就是去掉第一种方式的dao的实现类

    Mybatis已经给我们实现了功能,我们只需要注册容器并注入接口位置与SqlSessionfactory就可以了!
    在这里插入图片描述
    这样的方式也是可以实现业务的!
    但是这有一个缺点,那就是每生成一个Mapper对象就得配置一次,太过于麻烦!

    C.批量配置实现类

    使用mybatis-spring提供的:org.mybatis.spring.mapper.MapperScannerConfigurer批量扫描配置文件
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    <?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:context="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">
    <!--加载配置文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--第二种-->
    <!--<bean id="config" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">-->
    <!--<property name="locations">-->
    <!--<array>-->
    <!--<value>classpath:jdbc.properties</value>-->
    <!--</array>-->
    <!--</property>-->
    <!--</bean>-->

    <!-- 第一种方式生成mapper对象
    <bean id="studentMapper" class="com.itt.dao.impl.StudentDaoImpl">-->
    <!--&lt;!&ndash; 将Spring配置好的SqlSessionFactory交给mapper(dao)&ndash;&gt;-->
    <!--<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>-->
    <!--</bean>-->

    <!-- 第二种方式:生成mapper对象-->
    <!--<bean id="studentMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">-->
    <!--<property name="mapperInterface" value="com.itt.mapper.StudentMapper"></property>-->
    <!--<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>-->
    <!--</bean>-->
    <!-- 第三种方式,生mapper对象(批量方式)
    批量产生对在SpringIOC中的id值默认就是接口名
    -->
    <bean id="mappers" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    <!--指定批量产生哪个包中的mapper对象-->
    <property name="basePackage" value="com.itt.mapper"/>
    </bean>

    <bean id="studentService" class="com.itt.service.impl.StudentServiceImpl">
    <property name="studentMapper" ref="studentMapper"></property>
    </bean>


    <!-- 配置数据库信息(替代mybatis的配置文件conf.xml)-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="${driver}"></property>
    <property name="url" value="${url}"></property>
    <property name="username" value="${username}"></property>
    <property name="password" value="${password}"></property>
    <!--<property name="maxActive" value="${maxActive}"></property>-->
    <!--<property name="maxIdle" value="${maxIdle}"></property>-->
    </bean>

    <!-- 在Spring中创建SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <!--引用配置好的数据源-->
    <property name="dataSource" ref="dataSource"></property>
    <!--加载mybatis的配置文件-->
    <property name="configLocation" value="classpath:config.xml"></property>
    <!-- 扫描sql配置文件:mapper需要的xml文件 -->
    <property name="mapperLocations" value="com/itt/mapper/*.xml"></property>
    </bean>
    </beans>