Spring-Mybatis(整合的三种方式,spring管理事务的两种方式)

1. Mybatis-Spring简介

MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中。
它将允许 MyBatis 参与到 Spring 的事务管理之中,创建映射器 mapper 和 SqlSession 并注入到 bean 中,以及将 Mybatis 的异常转换为 Spring 的 DataAccessException。
最终,可以做到应用代码不依赖于 MyBatis,Spring 或 MyBatis-Spring。

2.Mybatis-Spring的对应版本

在这里插入图片描述

3.Mybatis-Spring的第一种整合方式

(1)导入相关依赖
  <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.6.RELEASE</version>
    </dependency>
    <!--做spring事务用到的-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.2.6.RELEASE</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.6.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.4</version>
    </dependency>
    <!--mysql-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.47</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.3</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.22</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>5.2.6.RELEASE</version>
    </dependency>
(2)编写实体类
package Pojo;
import lombok.Data;
@Data
public class User {
    private int id;
    private String name;
    private String pwd;
    public User() {
    }
    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }
}
(3)编写接口UserMapper
package Mapper;
import Pojo.User;
import java.util.List;
public interface UserMapper {
   public List<User> getUserList();
}
(4)编写UserMapper.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="Mapper.UserMapper">
    <select id="getUserList" resultType="Pojo.User">
        select * from user;
    </select>
</mapper>
(5)编写Spring配置文件(ApplicationContext.xml)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd   
        ">
    <bean id="dataSource"     class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8"/>
    <property name="username" value="root"/>
    <property name="password" value="123456"/>
</bean>
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath:Mapper/*.xml"></property>
        <!--<property name="configLocation" value="classpath:mybatis-config.xml"></property>-->
    </bean>
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory" />
    </bean>
    <bean id="UserMapperImpl" class="Mapper.Impl.UserMapperImpl">
        <property name="sessionTemplate" ref="sqlSession"></property>
    </bean>
</beans>

1.为什么使用datasource?
因为整合时,不能使用Mybatis数据库,可以使用spring自带的数据库
- org.springframework.jdbc.datasource
2.为什么要使用SqlSessionTemplate?为什么不能采用构造器注入?

  • SqlSessionTemplate等同于SqlSession.
  • SqlSessionTemplate 是线程安全的,可以被多个 DAO 或映射器所共享使用。
  • SqlSessionTemplate 还有一个接收 ExecutorType 参数的构造方法。这允许你使用 Spring 配置来批量创建对象
  • 不能采用构造器注入,因为其没有set方法。
(6)编写UserMapperImpl实现类
package Mapper.Impl;
import Mapper.UserMapper;
import Pojo.User;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
public class UserMapperImpl implements UserMapper {
    private SqlSessionTemplate sessionTemplate;
    public void setSessionTemplate(SqlSessionTemplate sessionTemplate) {
        this.sessionTemplate = sessionTemplate;
    }
    public List<User> getUserList() {
        UserMapper mapper = sessionTemplate.getMapper(UserMapper.class);
        return mapper.getUserList();
    }
}

为什么整合必须要编写实现类?

因为spring的东西会自动创建,而Mybatis的东西无法创建,只能手动通过实现类中的set方法进行创建。

(7)编写测试类
import Mapper.Impl.UserMapperImpl;
import Mapper.UserMapper;
import Pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class Text {
    @Test
    public void Text1(){
        ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        UserMapper bean = (UserMapper) context.getBean("UserMapperImpl");
        List<User> userList = bean.getUserList();
        for (User ser : userList) {
            System.out.println(ser);
        }
    }
}

4.Mybatis-Spring的第二种整合方式

相比第一种整合方式,第二种的方式更加的简单,步骤代码与第一种基本相同,只有少量步骤有些差别,更见简单,代码量更少

(1)实现类继承SqlSessionDaoSupport
SqlSessionDaoSupport 是一个抽象的支持类,用来为你提供 SqlSession。
调用 getSqlSession() 方法你会得到一个 SqlSessionTemplate,之后可以用于执行 SQL 方法

代码实现:

package Mapper.Impl;
        import Mapper.UserMapper;
        import Pojo.User;
        import org.mybatis.spring.SqlSessionTemplate;
        import org.mybatis.spring.support.SqlSessionDaoSupport;
        import java.util.List;
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper {
    public List<User> getUserList() {
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        return mapper.getUserList();
    }
}
(2)编写Spring配置文件(ApplicationContext.xml)
因为 SqlSessionDaoSupport 提供SqlSessionTemplate,所以不需要再注入

代码实现:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="mapperLocations" value="classpath:Mapper/*.xml"></property>
</bean>
<bean id="UserMapperImpl" class="Mapper.Impl.UserMapperImpl">
    <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>

5.Mybatis-Spring的第三种整合方式

与第一种方式类似

(1)声明数据源(采用Druid)
    <context:property-placeholder location="classpath:do.properties"></context:property-placeholder>
    <!--声明数据源-->
    <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8"></property>
        <property name="username" value="root"></property>
       <property name="password" value="123456"></property>
        <property name="maxActive" value="20"></property>
    </bean>
(2)创建sqlSessionFactory
 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
           <property name="dataSource" ref="myDataSource"></property>
         <property name="configLocation" value="classpath:mybatis-config.xml"></property>
    </bean>
(3)创建dao对象
 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
          <!--指定包名,把包中的每个接口都执行一次getMApper()方法得到每个接口的dao对象,并放入spring容器中-
         MapperScannerConfigurer :在内部调用getMapper()生成每个dao接口的代理对象->
           <property name="basePackage" value="org.example.dao"></property>
    </bean>

6.spring事务管理(事务处理的两种方式)

(1)事务的隔离级别

在这里插入图片描述

mysql默认的隔离级别是:TRANSACTION_REPEATABLE_READ
Oracle的默认隔离级别是:TRANSACTION_READ_COMMITTED

(2)事务的7大传播行为

在这里插入图片描述

(3)事务的超时时间

表示一个方法最长的执行时间,如果方法执行时超过了时间,事务就回滚,单位是秒,整数值,默认是-1.

由于数据访问技术的多样性,有不同的事务处理机制,而spring完成了统一处理事务
spring把每一种数据库访问技术对应的事务处理类都创建好了接口PlatformTransactionManager
mybatis------------DataSourceTransactionManager
hibernate----------HibernateTransactionManager

(4)使用aspectj配置事务(实现了业务代码与事务的解耦合)
<!-- 配置事务 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <constructor-arg ref="dataSource" />
</bean>

配置事务的通知:(使用Spring的事务命名空间tx)

<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <!--propagation事务的传播特性,默认为REQUIRED-->
        <tx:method name="*" propagation="REQUIRED"/>
    </tx:attributes>
</tx:advice>

结合AOP实现事务的切入:

<aop:config>
    <aop:pointcut id="txPointCut" expression="execution(* Mapper.*.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
(5)使用注解(适合中小型项目)
核心配置文件中开启注解
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
       <!--数据原-->
       <property name="dataSource" ref="myDataSource"></property>
   </bean>
    <!--开启事务注解-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
方法上使用注解@Transactional
@Transactional(
    * rollbackFor 发生指定的异常进行回滚,处理逻辑:先检查是否在rolback的属性中,不管是什么类型,一定回滚
    * 检查方法抛出的异常是不是运行期异常,是一定回滚
            propagation = Propagation.REQUIRED,
            isolation = Isolation.DEFAULT,
            readOnly = false,
            rollbackFor = {RuntimeException.class}
    )

Time waits for no one. Treasure every moment you have.
时间不等人,珍惜你所拥有的每分每秒吧!

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贫僧洗发爱飘柔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值