如何“優雅”的將Spring與Mybatis整合(配置文件方式)


思路:
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添加依賴:

<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
public class Student {

    private int stuNo;
    private String stuName;
    private int stuAge;
	
	//getter,setter....
}

3.Mybatis配置文件:conf.xml


4.通過mapper.xml將類、表建立映射關係

5.在Spring配置文件中配,SqlSessionFactoy和數據源

<?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
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
public interface StudentMapper {
    
    public void addStudent(Student student);
    
}
  • studentMapper.xml
<?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
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
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);
    }
}
  • IStudentService
public interface IStudentService {
    
    public void addStudent(Student student);
    
}
  • config.xml
<?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
@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批量掃描配置文件

<?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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章