三、spring整合MyBatis

官网下载地址

能源节点spring材料

视频观看地址

https://www.bilibili.com/vide...

将 MyBatis 与 Spring 进行整合,次要解决的问题就是将SqlSessionFactory 对象交由 Spring来治理

只须要将 SqlSessionFactory 的对象生成器 SqlSessionFactoryBean 注册在 Spring 容器中,再将其注入给 Dao 的实现类即可实现整合

整合思路

须要有须要有Dao接口的代理对象,例如studentDao须要一个他的代理对象,应用SqlSession.getMapper(StudentDao.class),失去dao代理对象

须要有SqlSessionFactory,创立一个SqlSessionFactory对象,应用SqlSessionFactory.open()失去SqlSession对象

数据源DataSource对象,应用连接池对象替换mybatis本人的PooledDataSource

3.1 maven依赖

maven依赖

   <dependencies>    <dependency>      <groupId>junit</groupId>      <artifactId>junit</artifactId>      <version>4.11</version>      <scope>test</scope>    </dependency>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-context</artifactId>      <version>5.2.5.RELEASE</version>    </dependency>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-tx</artifactId>      <version>5.3.8</version>    </dependency>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-jdbc</artifactId>      <version>5.3.8</version>    </dependency>    <dependency>      <groupId>org.mybatis</groupId>      <artifactId>mybatis</artifactId>      <version>3.5.7</version>    </dependency>    <dependency>      <groupId>org.mybatis</groupId>      <artifactId>mybatis-spring</artifactId>      <version>2.0.6</version>    </dependency>    <dependency>      <groupId>mysql</groupId>      <artifactId>mysql-connector-java</artifactId>      <version>8.0.25</version>    </dependency>    <dependency>      <groupId>com.alibaba</groupId>      <artifactId>druid</artifactId>      <version>1.2.1</version>    </dependency>    <dependency>      <groupId>org.projectlombok</groupId>      <artifactId>lombok</artifactId>      <version>1.18.20</version>    </dependency>  </dependencies>    <build>    <resources>      <resource>        <directory>src/main/java</directory><!--所在的目录-->        <includes><!--包含目录下的.properties,.xml 文件都会扫描到-->          <include>**/*.properties</include>          <include>**/*.xml</include>        </includes>        <filtering>false</filtering>      </resource>    </resources>  </build>

3.2 实体类

定义实体类

@Data@AllArgsConstructor@NoArgsConstructorpublic class Student {    private Integer id;    private String name;    private String email;    private Integer age;}

3.3 Dao接口与mapper文件

Dao接口

public interface StudentDao {    int insertStudent(Student student);    List<Student> selectStudentList();}

mapper文件

<?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.jjh.dao.StudentDao">    <insert id="insertStudent">        insert into student values (#{id},#{name},#{email},#{age})    </insert>    <select id="selectStudentList" resultType="com.jjh.domain.entity.Student">        select * from student order by id desc    </select></mapper>

3.4 service接口与实现类

service接口

public interface StudentService {    int addStudent(Student student);    List<Student> queryAllStudents();}

service实现类

@Service("myStudentService")public class StudentServiceImpl implements StudentService {    @Autowired    private StudentDao studentDao;    @Override    public int addStudent(Student student) {        int result = studentDao.insertStudent(student);        return result;    }    @Override    public List<Student> queryAllStudents() {        List<Student> students = studentDao.selectStudentList();        return students;    }}

3.5 MyBatis主配置文件

主配置文件中不再须要数据源的配置了,因为数据源要交给 Spring 容器来治理了

这里对 mapper 映射文件的注册,应用<package/>标签,即只需给出 mapper 映射文件所在的包即可,因为 mapper 的名称与 Dao 接口名雷同,能够应用这种简略注册形式。这种形式的益处是,若有多个映射文件,这里的配置也是不必扭转的。当然,也可应用原来的<resource/>标签形式

<?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>    <!--settings:管制mybatis全局行为-->    <settings>        <!--设置mybatis输入日志-->        <setting name="logImpl" value="STDOUT_LOGGING"/>    </settings>    <!--设置别名-->    <typeAliases>        <!--实体类别名-->        <!--            package:把包上面所有类名作为别名            name:实体类的包名        -->        <package name="com.jjh.domain.entity"/>    </typeAliases>    <!-- sql mapper(sql映射文件)的地位-->    <mappers>        <!--            package:指定Dao接口包的地位,示意将包上面的sql映射文件找到            name:Dao接口的包名            应用package指定映射文件的要求:            1.sql映射的文件名与Dao接口名统一            2.sql映射文件和Dao接口在同一目录        -->        <package name="com.jjh.dao"/>    </mappers></configuration>

3.6 spring的配置文件

  • jdbc.properties文件
  • jdbc.driver=com.mysql.cj.jdbc.Driver
  • jdbc.url=jdbc:mysql://localhost:3306/mybatis01?serverTimezone=Asia/Shanghai
  • jdbc.username=root
  • jdbc.password=123456

该属性文件若要被 Spring 配置文件读取,其必须在配置文件中进行注册。应用<context>标签
<context:property-placeholder/>标签中有一个属性 location,用于指定属性文件的地位

注册 SqlSessionFactoryBean

<!--申明的是mybatis中提供的SqlSessionFactoryBean类,这个类外部创立SqlSessionFactory的    SqlSessionFactory  sqlSessionFactory = new ..    -->    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">        <!--set注入,把数据库连接池付给了dataSource属性-->        <property name="dataSource" ref="myDataSource" />        <!--mybatis主配置文件的地位           configLocation属性是Resource类型,读取配置文件           它的赋值,应用value,指定文件的门路,应用classpath:示意文件的地位        -->        <property name="configLocation" value="classpath:mybatis.xml" />    </bean>

定义 Mapper 扫描配置器 MapperScannerConfigurer

Mapper 扫描配置器 MapperScannerConfigurer会主动生成指定的根本包中 mapper 的代理对象 。该 Bean无需设置 id 属性。basePackage 应用分号或逗号设置多个包

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">        <!--指定SqlSessionFactory对象的id-->        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>        <!--指定包名, 包名是dao接口所在的包名。            MapperScannerConfigurer会扫描这个包中的所有接口,把每个接口都执行            一次getMapper()办法,失去每个接口的dao对象。            创立好的dao对象放入到spring的容器中的。dao对象的默认名称是 接口名首字母小写        -->        <property name="basePackage" value="com.jjh.dao"/>    </bean>

3.7 向service注入接口名

向 Service 注入 Mapper 代理对象时须要留神,因为通过 Mapper 扫描配置器MapperScannerConfigurer生成的 Mapper 代理对象没有名称,所以在向 Service 注入 Mapper代理时,无奈通过名称注入。但可通过接口的简略类名注入,因为生成的是这个 Dao 接口的对象。

全副配置文件

<context:component-scan base-package="com.jjh.service"/>    <!--        把数据库的配置信息,写在一个独立的文件,编译批改数据库的配置内容        spring晓得jdbc.properties文件的地位    -->    <context:property-placeholder location="classpath:jdbc.properties"/>    <!--申明数据源DataSource,作用是连贯数据库-->    <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource"          init-method="init" destroy-method="close">        <!--set注入-->        <property name="url" value="${jdbc.url}"/>        <property name="username" value="${jdbc.username}"/>        <property name="password" value="${jdbc.password}"/>        <property name="maxActive" value="20"/>    </bean>    <!--申明的是mybatis中提供的SqlSessionFactoryBean类,这个类外部创立SqlSessionFactory的    SqlSessionFactory  sqlSessionFactory = new ..    -->    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">        <!--set注入,把数据库连接池付给了dataSource属性-->        <property name="dataSource" ref="myDataSource" />        <!--mybatis主配置文件的地位           configLocation属性是Resource类型,读取配置文件           它的赋值,应用value,指定文件的门路,应用classpath:示意文件的地位        -->        <property name="configLocation" value="classpath:mybatis.xml" />    </bean>    <!--创立dao对象,应用SqlSession的getMapper(StudentDao.class)        MapperScannerConfigurer:在外部调用getMapper()生成每个dao接口的代理对象。    -->    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">        <!--指定SqlSessionFactory对象的id-->        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>        <!--指定包名, 包名是dao接口所在的包名。            MapperScannerConfigurer会扫描这个包中的所有接口,把每个接口都执行            一次getMapper()办法,失去每个接口的dao对象。            创立好的dao对象放入到spring的容器中的。dao对象的默认名称是 接口名首字母小写        -->        <property name="basePackage" value="com.jjh.dao"/>    </bean>    </beans>