ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Spring整合Mybatis,声明式事务(狂神)

2021-08-01 14:33:26  阅读:166  来源: 互联网

标签:xml 事务 Spring UserMapper user Mybatis 狂神 public


Spring整合Mybatis,声明式事务(狂神)

1、整合Mybatis

代码:https://gitee.com/deza-to/spring_mybatis

B站 https://www.bilibili.com/video/BV1WE411d7Dv

参考博客:https://mp.weixin.qq.com/s/gXFMNU83_7PqTkNZUgvigA

https://mp.weixin.qq.com/s/mYOBJdygHDcXPYBls7cxUA

步骤

  1. 导入相关jar包

    • junit
    • mybatis
    • mysql数据库
    • spring相关
    • aop织入
    • mybatis-spring【核心】

    pom.xml

    <dependencies>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.47</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>5.1.9.RELEASE</version>
            </dependency>
            <!--Spring操作数据库需要一个spring-jdbc-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>5.1.9.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.2</version>
            </dependency>
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>1.9.7</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>2.0.2</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13.2</version>
                <scope>test</scope>
            </dependency>
        </dependencies>
    
  2. 配置Maven静态资源过滤问题

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>
  1. 编写配置文件

  2. 测试

1.1、回忆Mybatis

  1. 编写实体类
  2. 编写核心配置文件
  3. 编写接口
  4. 编写Mapper.xml
  5. 测试

1.2、Mybatis-Spring

整合方式一

  1. 编写数据源配置【spring-dao.xml】
<!--DataSource:使用Spring的数据源替换Mybatis的配置-->
<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=false&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=Asia/Shanghai"/>
    <property name="username" value="root"/>
    <property name="password" value="cqp123"/>
</bean>
  1. sqlSessionFactory
<!--SqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <!--绑定Mybatis配置文件-->
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
    <!--注册mapper.xml-->
    <property name="mapperLocations" value="classpath:com/chen/dao/*.xml"/>
</bean>

mybatis-config.xml一般配置setting和typeAliases

<?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核心配置文件-->
<configuration>

    <!--setting也合适放在这个配置文件-->
    <!--    <settings>-->
    <!--        <setting name="" value=""/>-->
    <!--    </settings>-->

    <typeAliases>
        <package name="com.chen.pojo"/>
    </typeAliases>

    <!--<environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=Asia/Shanghai"/>
                <property name="username" value="root"/>
                <property name="password" value="cqp123"/>
            </dataSource>
        </environment>
    </environments>-->
    <!--<mappers>
        <package name="com.chen.dao"/>
    </mappers>-->
</configuration>
  1. sqlSessionTemplate
<!--SqlSessionTemplate:就是我们使用的sqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
    <!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
    <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
  1. 需要给接口加实现类
import com.chen.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;

import java.util.List;

public class UserMapperImpl implements UserMapper{
    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    public List<User> getUsers(){
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.getUsers();
        return userList;
    }

    public int addUser(User user){
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int i = mapper.addUser(user);
        return i;
    }

    public int deleteUser(int id){
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int i = mapper.deleteUser(id);
        return i;
    }

}
  1. 将自己写的实现类注入到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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--将dao的配置导入-->
    <import resource="spring-dao.xml"/>

    <bean id="userMapperImpl" class="com.chen.dao.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>

</beans>
  1. 测试
@Test
public void test() throws IOException {
    ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
    UserMapper userMapper = (UserMapper) context.getBean("userMapperImpl");
    List<User> userList = userMapper.getUsers();
    for (User user : userList) {
        System.out.println(user);
    }
}

整合方式二

mybatis-spring1.2.3版以上的才有这个

  1. 继承SqlSessionDaoSupport,直接利用getSqlSession()获得,然后注入SqlSessionFactory 。

比起方式1 , 不需要管理SqlSessionTemplate , 而且对事务的支持更加友好。

import com.chen.pojo.User;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import java.util.Date;
import java.util.List;

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
    //继承SqlSessionDaoSupport可以直接获得SqlSession对象
    public List<User> getUsers() {
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        return mapper.getUsers();
    }
}
  1. 在ApplicationContext.xml中配置bean
<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="spring-dao.xml"/>

    <bean id="userMapperImpl2" class="com.chen.dao.UserMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
</beans>
  1. 测试
@Test
public void test2(){
    ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
    UserMapper userMapper = (UserMapper) context.getBean("userMapperImpl2");
    List<User> userList = userMapper.getUsers();
    for (User user : userList) {
        System.out.println(user);
    }
}

2、声明式事务

2.1、回顾事务

  • 把一组业务当成一个业务来做,要么都成功,要么都失败
  • 事务在项目开发中十分重要,涉及到数据的一致性问题,不能马虎
  • 确保完整性和一致性

事务的ACID原则:

  • 原子性
    • 事务是原子性操作,由一系列动作组成,事务的原子性确保动作要么全部完成,要么都不起作用。
  • 一致性
    • 一旦所有事务动作完成,事务就要被提交。数据和资源处于一种满足业务规则的一致性状态中。
  • 隔离性
    • 多个业务可能操作同一个资源,因此每个事务都应该与其他事务隔离开,防止数据损坏。
  • 持久性
    • 事物一旦提交,无论系统发生什么问题,结果都不会被影响,被持久化的写到存储器中。

2.2、编写代码

1、给UserMapper接口增加两个方法

//添加一个用户
int addUser(User user);

//删除一个用户
int deleteUser(@Param("id") int id);

2、相应的添加mapper.xml的实现(故意将delete写错成deletes)

<insert id="addUser" parameterType="user">
    insert into user (name,pwd,createTime) values(#{name},#{pwd},#{createTime})
</insert>

<delete id="deleteUser" parameterType="int">
    deletes from USER where id = #{id}
</delete>

3、编写接口的实现类

import com.chen.pojo.User;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import java.util.Date;
import java.util.List;

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{

    //继承SqlSessionDaoSupport可以直接获得SqlSession对象
    public List<User> getUsers() {

        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);

        User user = new User("小山", "33333", new Date());
        mapper.addUser(user);
        mapper.deleteUser(8);
        return mapper.getUsers();

    }

    public int addUser(User user){
        return getSqlSession().getMapper(UserMapper.class).addUser(user);
    }

    public int deleteUser(int id){
        return getSqlSession().getMapper(UserMapper.class).deleteUser(id);
    }

}

4、测试

@Test
public void test2(){
    ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
    UserMapper userMapper = (UserMapper) context.getBean("userMapperImpl2");
    List<User> userList = userMapper.getUsers();
    for (User user : userList) {
        System.out.println(user);
    }
}

报错:sql异常,delete写错了

结果:插入成功

没有进行事务的管理;我们想让他们都成功才成功,有一个失败,就都失败,我们就应该需要事务!

以前我们都需要自己手动管理事务,十分麻烦!

但是Spring给我们提供了事务管理,我们只需要配置即可;

2.3、Spring中的事务管理

  • 声明式事务:AOP
    • 一般情况下比编程式事务好用。
    • 将事务管理代码从业务方法中分离出来,以声明的方式来实现事务管理。
    • 将事务管理作为横切关注点,通过aop方法模块化。Spring中通过Spring AOP框架支持声明式事务管理。
  • 编程式事务:需要在代码中,进行事物的管理
    • 将事务管理代码嵌到业务方法中来控制事务的提交和回滚
    • 缺点:必须在每个事务操作业务逻辑中包含额外的事务管理代码

使用Spring管理事务,注意头文件的约束导入 : tx

xmlns:tx="http://www.springframework.org/schema/tx"

http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">

事务管理器

  • 无论使用Spring的哪种事务管理策略(编程式或者声明式)事务管理器都是必须的。
  • 就是 Spring的核心事务管理抽象,管理封装了一组独立于技术的方法。

JDBC事务

<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <constructor-arg ref="dataSource" />
</bean>

配置好事务管理器后我们需要去配置事务的通知

<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
   <tx:attributes>
       <!--配置哪些方法使用什么样的事务,配置事务的传播特性-->
       <tx:method name="add" propagation="REQUIRED"/>
       <tx:method name="delete" propagation="REQUIRED"/>
       <tx:method name="update" propagation="REQUIRED"/>
       <tx:method name="search*" propagation="REQUIRED"/>
       <tx:method name="get" read-only="true"/>
       <tx:method name="*" propagation="REQUIRED"/>
   </tx:attributes>
</tx:advice>

spring事务传播特性:

事务传播行为就是多个事务方法相互调用时,事务如何在这些方法间传播。spring支持7种事务传播行为:

  • propagation_requierd:如果当前没有事务,就新建一个事务,如果已存在一个事务中,加入到这个事务中,这是最常见的选择。
  • propagation_supports:支持当前事务,如果没有当前事务,就以非事务方法执行。
  • propagation_mandatory:使用当前事务,如果没有当前事务,就抛出异常。
  • propagation_required_new:新建事务,如果当前存在事务,把当前事务挂起。
  • propagation_not_supported:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
  • propagation_never:以非事务方式执行操作,如果当前事务存在则抛出异常。
  • propagation_nested:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与propagation_required类似的操作

Spring 默认的事务传播行为是 PROPAGATION_REQUIRED,它适合于绝大多数的情况。

假设 ServiveX#methodX() 都工作在事务环境下(即都被 Spring 事务增强了),假设程序中存在如下的调用链:Service1#method1()->Service2#method2()->Service3#method3(),那么这 3 个服务类的 3 个方法通过 Spring 的事务传播机制都工作在同一个事务中。

就好比,我们刚才的几个方法存在调用,所以会被放在一组事务当中!

配置AOP

导入aop的头文件!

<!--配置事务切入-->
<aop:config>
    <aop:pointcut id="txPointCut" expression="execution(* com.chen.dao.*.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>

进行测试

删掉刚才插入的数据,再次测试!

@Test
public void test2(){
    ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
    UserMapper userMapper = (UserMapper) context.getBean("userMapperImpl2");
    List<User> userList = userMapper.getUsers();
    for (User user : userList) {
        System.out.println(user);
    }
}

思考:

为什么需要事务?

  • 如果不配置事务,可能存在数据提交不一致的情况
  • 如果我们不在Spring中去配置声明式事务,就需要在代码中手动配置事务
  • 事务在项目开发中十分重要,涉及数据的一致性和完整性问题

标签:xml,事务,Spring,UserMapper,user,Mybatis,狂神,public
来源: https://www.cnblogs.com/buzhuo/p/15086597.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有