mybatis-spring整合——这可太详细了

1 篇文章 0 订阅

spring-mybatis整合

1.环境配置

1.1导入依赖:

sringAop
       <!--Spring 所需Jar包    -->
            <!--AOP所需依赖-->
        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.7</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>
spring核心
    <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>
springJdbc
            <!-- SpringJDBC依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>
springTx
            <!-- Spring 事务管理依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>
springTest
            <!-- spring test 依赖 ,没有它junit无法加载Spring 上下文-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>
mybatis
            <!--mybatis 核心jar-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>
整合中间件
        <!--整合中间件 mybatis写的-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>
数据库驱动
        <!--数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.27</version>
        </dependency>
数据源
        <!--数据源-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.8.1</version>
        </dependency>

日志
<!--日志-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>2.9.1</version>
        </dependency>
辅助工具
<!--辅助工具-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>
测试
<!-- 测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>
mvn配置
    <!--配置加载XML -->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

1.2 数据库配置

  • com.mysql.jdbc.Driver
    • mysql5及以下版本驱动
  • com.mysql.cj.jdbc.Driver
    • mysql6及以上版本驱动
    • url 中必须配置时区serverTimeZone=GMT%2B8
jdbc.driver= com.mysql.cj.jdbc.Driver
jdbc.url= jdbc:mysql://xxx.xxx.xxx.xxx:3306/mybatis?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
jdbc.username= root
jdbc.password= xxxxxx
jdbc.maxTotal= 30
jdbc.maxIdle= 20
jdbc.initialSize= 5

1.3 applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans
        xmlns:tx="http://www.springframework.org/schema/tx"
        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-3.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
">

<!--  读取db.yml 文件-->
    <context:property-placeholder location="db.properties"/>

<!-- 配置数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <!--最大连接数-->
        <property name="maxTotal" value="${jdbc.maxTotal}"/>
        <!--最大空闲连接数-->
        <property name="maxIdle" value="${jdbc.maxIdle}"/>
        <!--初始化连接数-->
        <property name="initialSize" value="${jdbc.initialSize}"/>
    </bean>
<!--事务管理器,依赖于数据源-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
<!-- 开启事务注解-->
    <tx:annotation-driven transaction-manager="transactionManager" />

<!-- 配置mybatis工厂bean -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--数据源-->
        <property name="dataSource" ref="dataSource"/>
        <!--配置文件路径-->
        <property name="configLocation" value="mybatis-config.xml"/>
    </bean>
</beans>

1.4 mybatis-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.wang.po"/>
    </typeAliases>

    <mappers>

    </mappers>
</configuration>

1.5 log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration status="OFF">
<!--输出目的地配置-->
    <appenders>
        <Console name="Console" target="SYSTEM_OUT">
<!-- %d{格式 yyyy-MM-dd HH:mm:ss,SSS} 时间
     %c 全限定类名
     %highlight{%d-5level} 输出打印优先级{颜色类型}
     %style{[%t]} 对线程名添加风格{bright,magenta}
     %L 行数
     %M 调用logger 的方法名
       -->
            <PatternLayout pattern="%d{HH:mm:ss} %highlight{%-5level}{ERROR=Bright RED, WARN=Bright Yellow, INFO=Bright Green, DEBUG=Bright Cyan, TRACE=Bright White} %style{[%t]}{bright,magenta} %style{%c{1.}.%M(%L)}{cyan}->>> %msg%n"/>
        </Console>
    </appenders>
    <loggers>
        <root level="DEBUG">
            <appender-ref ref="Console"/>
        </root>
    </loggers>
</configuration>

2.整合方式

2.1 传统Dao开发整合

整合的统一思想:

需要向持久层注入SqlSessionFactory,因为在Spring 种SqlSessionFactory 默认创建是单例的,所以符合SqlSessionFactory的操作特点(数据库的映射,线程安全)

而持久层的方法体内则需要创建SqlSession 对象,在每一个方法体中都需要创建,因为SqlSession 是非线程安全的,其中包含了所有的SQL信息,唯一标识SQL的就是配置的id

基于传统Dao方式开发有两种情况:

  • 继承SqlSessionDaoSupport:
    • 是一个抽象支持类,继承自DaoSupport,主要作为Dao的基类来使用,可以通过SqlSessionDaoSupport 类的getSqlSession方法来获取所需的SqlSession
  • SqlSessionTemplate
    • mybatis-spring 的核心类,负责管理Mybatis的SqlSession,调用mybatis 的SQL方法,调用SQL方法时,会保证使用的SqlSession 与当前的Spring 事务时相关的,还管理SqlSession 的生命周期,包含必要的关闭、提交和回滚操作

使用SqlSessionDaoSupport 更加的方便,但实际上底层也是通过SqlSessionTemplate 提高的SqlSession 对象

image-20211231113807102

因为SqlSessionDaoSupport 需要SqlSessionFactory对象,所以在使用的时候需要将SqlSessionFactory 对象注入其中

定义接口:
public interface CustomerDao {

    /**
     * @param id 用户id
     * @return 用户
     */
    public Customer findById(Integer id);
}

编写实现类:

继承SqlSessionDaoSupport抽象类,注入SqlSessionFactory 对象,并通过getSqlSession方法获取SqlSession

public class CustomerDaoImpl extends SqlSessionDaoSupport implements CustomerDao {
    @Override
    public Customer findById(Integer id) {
        /*
        继承SqlSessionDaoSupport 类
        使用时,Spring 会给他注入一个SqlSessionFactory 或SqlSessionTemplate 对象
        这样就能通过getSqlSession 来获取SqlSession对象
         */
        return this.getSqlSession().selectOne("findById",id);
    }
}

因为是在SqlSessionDaoSupport 类中SqlSessionFactory 对象是通过setter 方法注入的,所以可以在applicationContext.xml 中直接注入:

<!--实例化-->
    <bean id="customerDao" class="com.wang.dao.impl.CustomerDaoImpl">
        <!-- 注入中间件支持的SqlSessionDaoSupport 所需的 sqlSessionFactory      -->
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
测试:

这里需要注意的是

  1. Junit 和Spring 也是需要整合的,不能简单的通过编写test直接运行,这样并不会加载Spring 的容器,而是仅运行了一个测试类

  2. 首先需要导入Spring-test dependency

    •             <!-- spring test 依赖 ,没有它junit无法加载Spring 上下文-->
              <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>spring-test</artifactId>
                  <version>5.2.12.RELEASE</version>
              </dependency>
      
  3. 其次需要在测试类上写明启动环境以及加载的配置文件

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = { "classpath:applicationContext.xml" })
    
  4. 完整代码:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = { "classpath:applicationContext.xml" })
    @Slf4j
    public class CustomerDaoTest {
    
        @Autowired
        CustomerDao customerDao;
    
        @Test
        public void test1(){
            System.out.println(customerDao.findById(1));
        }
    }
    

2.2 Mapper接口方式开发整合

对于上面的通过SqlSession 进行开发会很繁琐,无形中增加了工作负担,所以Mybatis-spring 提供了根据Mapper 接口动态代理生成Mapper 对象的类——MapperFactoryBean,依赖于:

  • mapperInterface:用于指定接口
  • sqlSessionFactory:用于指定SqlSessionFactory 也可以指定SqlSessionTemplate ,如果同时指定只会启动SqlSessionFactory

这种方式的本质是通过程序员编写Mapper 接口,由框架通过定义创建接口的动态代理对象,这个代理对象的方法体等同于上面Dao接口的实现类方法,也就是获取SqlSession 并且通过sqlSession 根据id调用方法,如果按照以下规范去书写,可以在配置文件(mybatis-config.xml)中不引入映射文件(xxxMapper.xml),框架会直接扫描进行绑定:

  1. Mapper 接口和xml映射文件名称一致:CustomerMapper—CustomerMapper.xml

  2. mapper 和xml 必须需要在一个包内

    image-20211231143842940

  3. xml 中的namspce 和Mapper 接口的类路径一致:

    <mapper namespace="com.wang.dao.CustomerMapper">
    
  4. Mapper 接口中的方法名和xml 中的每个执行语句的id 一致

    image-20211231120836442

    image-20211231120845017

  5. Mapper 接口中的输入参数和xml中的parameterType 一致

  6. Mapper 接口中的输出参数和xml 中resultType 一致

四种Mapper 的配置方式:

image-20211231143920375

  • 面向xml文件:
    • 需要将每个xml都进行注册
  • 面向接口:
    • 需要将每个接口进行注册
  • 面向包:
    • 需要将包的每个接口都注册,且接口名要与xml名一致
  • 不注册:
    • xml必须和接口在一个包下
定义接口:
public interface CustomerMapper {

    /**
     * @param id 用户id
     * @return 用户
     */
    public Customer findById(Integer id);
}
定义xml:

xml 的namespace需要是对应接口的全限定路径:

<?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.wang.mapper.CustomerMapper">


    <select id="findById" parameterType="Integer"
            resultType="com.wang.po.Customer">
        select * from t_customer where id = #{id}
    </select>

</mapper>
注册/不注册:
    <!--mapper 注册 -->
    <mappers>

        <!--<mapper resource="com/wang/mapper/CustomerMapper.xml"/>-->
<!--        <package name="com.wang.mapper"/>-->
<!--        <mapper class="com.wang.dao.CustomerMapper"/>-->
    </mappers>
测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
@Slf4j
public class CustomerDaoTest {

    @Autowired
    CustomerMapper customerMapper;

    @Test
    public void test1(){
        System.out.println(customerMapper.findById(1));
    }
}

2.3 MapperScannerConfigurer

所有的mapper 接口不需要一个一个的在applicationContext中进行注册,myabtis-spring 团队提供了一种自动扫描的形式来配置,采用mybatisScannerConfigurer 类:

需要配置的属性:

  • basePackage:指定映射接口文件的包路径,当扫描多个包时可以使用分号或逗号作为分隔符,指定包路径后,扫描该报及其子包中的所有文件
  • annotationClass:指定要扫描的注解名称,只有被注解标识的类才会被配置为映射器
  • sqlSessionFactoryBeanName:指定在spring中定义的SqlSessionFactory的Bean名称
  • sqlSessionTemplateBeanName:指定在Spring 中定义的SqlSessionTemplate 的Bean名称,如果定义次属性,sqlSessionFactoryBeanName 将不起作用
    • narkerInterface:创建映射器的接口
<!--接口映射器-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.wang.mapper"/>
<!--        <property name="annotationClass" value="org.apache.ibatis.annotations.Mapper"/>-->
    </bean>

这样所有的mapper接口都会注册到IOC容器中,但是映射xml文件还需要继续进行配置。

也可以通过@Mapper 注解到interface 上面,通过配置annotationClass来进行扫描

2.4 整合事务

在Mybatis 中事务是交由spring 进行管理的,而事务的处理主要是通过@Transactional 注解进行处理,而处理的位置则是service 层,及在service 层调用的方法中若爆出异常则会进行事务回滚,事务也就影响不到数据库。

开启事务注解

applicationContext.xml

<!-- 开启事务注解-->
    <tx:annotation-driven transaction-manager="transactionManager" />
开启spring注解扫描
<!--  开启spring的注解扫描-->
    <context:component-scan base-package="com.wang"/>
service层

image-20211231154604671

@Transactional 注解即可以注解到方法上,则本方法开启事务管理,也可以注解到类或接口上,则类和接口里的方法都开启事务管理# spring-mybatis整合

1.环境配置

1.1导入依赖:

sringAop
       <!--Spring 所需Jar包    -->
            <!--AOP所需依赖-->
        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.7</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>
spring核心
    <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>
springJdbc
            <!-- SpringJDBC依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>
springTx
            <!-- Spring 事务管理依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>
springTest
            <!-- spring test 依赖 ,没有它junit无法加载Spring 上下文-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>
mybatis
            <!--mybatis 核心jar-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>
整合中间件
        <!--整合中间件 mybatis写的-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>
数据库驱动
        <!--数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.27</version>
        </dependency>
数据源
        <!--数据源-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.8.1</version>
        </dependency>

日志
<!--日志-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>2.9.1</version>
        </dependency>
辅助工具
<!--辅助工具-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>
测试
<!-- 测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>
mvn配置
    <!--配置加载XML -->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

1.2 数据库配置

  • com.mysql.jdbc.Driver
    • mysql5及以下版本驱动
  • com.mysql.cj.jdbc.Driver
    • mysql6及以上版本驱动
    • url 中必须配置时区serverTimeZone=GMT%2B8
jdbc.driver= com.mysql.cj.jdbc.Driver
jdbc.url= jdbc:mysql://xxx.xxx.xxx.xxx:3306/mybatis?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
jdbc.username= root
jdbc.password= xxxxxx
jdbc.maxTotal= 30
jdbc.maxIdle= 20
jdbc.initialSize= 5

1.3 applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans
        xmlns:tx="http://www.springframework.org/schema/tx"
        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-3.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
">

<!--  读取db.yml 文件-->
    <context:property-placeholder location="db.properties"/>

<!-- 配置数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <!--最大连接数-->
        <property name="maxTotal" value="${jdbc.maxTotal}"/>
        <!--最大空闲连接数-->
        <property name="maxIdle" value="${jdbc.maxIdle}"/>
        <!--初始化连接数-->
        <property name="initialSize" value="${jdbc.initialSize}"/>
    </bean>
<!--事务管理器,依赖于数据源-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
<!-- 开启事务注解-->
    <tx:annotation-driven transaction-manager="transactionManager" />

<!-- 配置mybatis工厂bean -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--数据源-->
        <property name="dataSource" ref="dataSource"/>
        <!--配置文件路径-->
        <property name="configLocation" value="mybatis-config.xml"/>
    </bean>
</beans>

1.4 mybatis-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.wang.po"/>
    </typeAliases>

    <mappers>

    </mappers>
</configuration>

1.5 log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration status="OFF">
<!--输出目的地配置-->
    <appenders>
        <Console name="Console" target="SYSTEM_OUT">
<!-- %d{格式 yyyy-MM-dd HH:mm:ss,SSS} 时间
     %c 全限定类名
     %highlight{%d-5level} 输出打印优先级{颜色类型}
     %style{[%t]} 对线程名添加风格{bright,magenta}
     %L 行数
     %M 调用logger 的方法名
       -->
            <PatternLayout pattern="%d{HH:mm:ss} %highlight{%-5level}{ERROR=Bright RED, WARN=Bright Yellow, INFO=Bright Green, DEBUG=Bright Cyan, TRACE=Bright White} %style{[%t]}{bright,magenta} %style{%c{1.}.%M(%L)}{cyan}->>> %msg%n"/>
        </Console>
    </appenders>
    <loggers>
        <root level="DEBUG">
            <appender-ref ref="Console"/>
        </root>
    </loggers>
</configuration>

2.整合方式

2.1 传统Dao开发整合

整合的统一思想:

需要向持久层注入SqlSessionFactory,因为在Spring 种SqlSessionFactory 默认创建是单例的,所以符合SqlSessionFactory的操作特点(数据库的映射,线程安全)

而持久层的方法体内则需要创建SqlSession 对象,在每一个方法体中都需要创建,因为SqlSession 是非线程安全的,其中包含了所有的SQL信息,唯一标识SQL的就是配置的id

基于传统Dao方式开发有两种情况:

  • 继承SqlSessionDaoSupport:
    • 是一个抽象支持类,继承自DaoSupport,主要作为Dao的基类来使用,可以通过SqlSessionDaoSupport 类的getSqlSession方法来获取所需的SqlSession
  • SqlSessionTemplate
    • mybatis-spring 的核心类,负责管理Mybatis的SqlSession,调用mybatis 的SQL方法,调用SQL方法时,会保证使用的SqlSession 与当前的Spring 事务时相关的,还管理SqlSession 的生命周期,包含必要的关闭、提交和回滚操作

使用SqlSessionDaoSupport 更加的方便,但实际上底层也是通过SqlSessionTemplate 提高的SqlSession 对象

image-20211231113807102

因为SqlSessionDaoSupport 需要SqlSessionFactory对象,所以在使用的时候需要将SqlSessionFactory 对象注入其中

定义接口:
public interface CustomerDao {

    /**
     * @param id 用户id
     * @return 用户
     */
    public Customer findById(Integer id);
}

编写实现类:

继承SqlSessionDaoSupport抽象类,注入SqlSessionFactory 对象,并通过getSqlSession方法获取SqlSession

public class CustomerDaoImpl extends SqlSessionDaoSupport implements CustomerDao {
    @Override
    public Customer findById(Integer id) {
        /*
        继承SqlSessionDaoSupport 类
        使用时,Spring 会给他注入一个SqlSessionFactory 或SqlSessionTemplate 对象
        这样就能通过getSqlSession 来获取SqlSession对象
         */
        return this.getSqlSession().selectOne("findById",id);
    }
}

因为是在SqlSessionDaoSupport 类中SqlSessionFactory 对象是通过setter 方法注入的,所以可以在applicationContext.xml 中直接注入:

<!--实例化-->
    <bean id="customerDao" class="com.wang.dao.impl.CustomerDaoImpl">
        <!-- 注入中间件支持的SqlSessionDaoSupport 所需的 sqlSessionFactory      -->
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
测试:

这里需要注意的是

  1. Junit 和Spring 也是需要整合的,不能简单的通过编写test直接运行,这样并不会加载Spring 的容器,而是仅运行了一个测试类

  2. 首先需要导入Spring-test dependency

    •             <!-- spring test 依赖 ,没有它junit无法加载Spring 上下文-->
              <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>spring-test</artifactId>
                  <version>5.2.12.RELEASE</version>
              </dependency>
      
  3. 其次需要在测试类上写明启动环境以及加载的配置文件

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = { "classpath:applicationContext.xml" })
    
  4. 完整代码:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = { "classpath:applicationContext.xml" })
    @Slf4j
    public class CustomerDaoTest {
    
        @Autowired
        CustomerDao customerDao;
    
        @Test
        public void test1(){
            System.out.println(customerDao.findById(1));
        }
    }
    

2.2 Mapper接口方式开发整合

对于上面的通过SqlSession 进行开发会很繁琐,无形中增加了工作负担,所以Mybatis-spring 提供了根据Mapper 接口动态代理生成Mapper 对象的类——MapperFactoryBean,依赖于:

  • mapperInterface:用于指定接口
  • sqlSessionFactory:用于指定SqlSessionFactory 也可以指定SqlSessionTemplate ,如果同时指定只会启动SqlSessionFactory

这种方式的本质是通过程序员编写Mapper 接口,由框架通过定义创建接口的动态代理对象,这个代理对象的方法体等同于上面Dao接口的实现类方法,也就是获取SqlSession 并且通过sqlSession 根据id调用方法,如果按照以下规范去书写,可以在配置文件(mybatis-config.xml)中不引入映射文件(xxxMapper.xml),框架会直接扫描进行绑定:

  1. Mapper 接口和xml映射文件名称一致:CustomerMapper—CustomerMapper.xml

  2. mapper 和xml 必须需要在一个包内

    image-20211231143842940

  3. xml 中的namspce 和Mapper 接口的类路径一致:

    <mapper namespace="com.wang.dao.CustomerMapper">
    
  4. Mapper 接口中的方法名和xml 中的每个执行语句的id 一致

    image-20211231120836442

    image-20211231120845017

  5. Mapper 接口中的输入参数和xml中的parameterType 一致

  6. Mapper 接口中的输出参数和xml 中resultType 一致

四种Mapper 的配置方式:

image-20211231143920375

  • 面向xml文件:
    • 需要将每个xml都进行注册
  • 面向接口:
    • 需要将每个接口进行注册
  • 面向包:
    • 需要将包的每个接口都注册,且接口名要与xml名一致
  • 不注册:
    • xml必须和接口在一个包下
定义接口:
public interface CustomerMapper {

    /**
     * @param id 用户id
     * @return 用户
     */
    public Customer findById(Integer id);
}
定义xml:

xml 的namespace需要是对应接口的全限定路径:

<?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.wang.mapper.CustomerMapper">


    <select id="findById" parameterType="Integer"
            resultType="com.wang.po.Customer">
        select * from t_customer where id = #{id}
    </select>

</mapper>
注册/不注册:
    <!--mapper 注册 -->
    <mappers>

        <!--<mapper resource="com/wang/mapper/CustomerMapper.xml"/>-->
<!--        <package name="com.wang.mapper"/>-->
<!--        <mapper class="com.wang.dao.CustomerMapper"/>-->
    </mappers>
测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
@Slf4j
public class CustomerDaoTest {

    @Autowired
    CustomerMapper customerMapper;

    @Test
    public void test1(){
        System.out.println(customerMapper.findById(1));
    }
}

2.3 MapperScannerConfigurer

所有的mapper 接口不需要一个一个的在applicationContext中进行注册,myabtis-spring 团队提供了一种自动扫描的形式来配置,采用mybatisScannerConfigurer 类:

需要配置的属性:

  • basePackage:指定映射接口文件的包路径,当扫描多个包时可以使用分号或逗号作为分隔符,指定包路径后,扫描该报及其子包中的所有文件
  • annotationClass:指定要扫描的注解名称,只有被注解标识的类才会被配置为映射器
  • sqlSessionFactoryBeanName:指定在spring中定义的SqlSessionFactory的Bean名称
  • sqlSessionTemplateBeanName:指定在Spring 中定义的SqlSessionTemplate 的Bean名称,如果定义次属性,sqlSessionFactoryBeanName 将不起作用
    • narkerInterface:创建映射器的接口
<!--接口映射器-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.wang.mapper"/>
<!--        <property name="annotationClass" value="org.apache.ibatis.annotations.Mapper"/>-->
    </bean>

这样所有的mapper接口都会注册到IOC容器中,但是映射xml文件还需要继续进行配置。

也可以通过@Mapper 注解到interface 上面,通过配置annotationClass来进行扫描

2.4 整合事务

在Mybatis 中事务是交由spring 进行管理的,而事务的处理主要是通过@Transactional 注解进行处理,而处理的位置则是service 层,及在service 层调用的方法中若爆出异常则会进行事务回滚,事务也就影响不到数据库。

开启事务注解

applicationContext.xml

<!-- 开启事务注解-->
    <tx:annotation-driven transaction-manager="transactionManager" />
开启spring注解扫描
<!--  开启spring的注解扫描-->
    <context:component-scan base-package="com.wang"/>
service层

image-20211231154604671

@Transactional 注解即可以注解到方法上,则本方法开启事务管理,也可以注解到类或接口上,则类和接口里的方法都开启事务管理

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值