05、Spring事务详解
创始人
2024-04-12 19:25:17
0

本文主要介绍Spring中的事务相关知识:
1、熟悉事务管理的三个核心接口
2、了解Spring事务的两种方式
3、掌握基于XML和注解的事务使用

1、Spring事务管理概述

1、事务管理的核心接口

1、PlatformTransactionManager

PlatformTransactionManage接口是Spring平台提供的平台事务管理器,主要用于管理事务。该接口中主要包含3个事务操作方法。

  • TransactionStatus getTransaction(TransactionDefinition definition):根据事务定义信息从事务环境中返回一个已存在的事务,或者创建一个新的事务。
  • void commit(TransactionStatus status):根据事务的状态提交事务,如果事务状态已经标识为 rollback-only,该方法执行回滚事务的操作。
  • void rollback(TransactionStatus status):将事务回滚,当 commit 方法抛出异常时,rollback 会被隐式调用。

2、使用事务选用实现类

  • JDBC 和 MyBatis 使用 DataSourceTransactionManager。
  • Hibernate 使用 HibernateTransactionManager。
  • JPA 使用 JpaTransactionManager。

3、TransactionDefinition接口

  • int getPropagationBehavior():获取事务的传播行为。
  • int getIsolationLevel();:获取事务的隔离级别。
  • int getTimeout();:获取事务的超时时间。
  • boolean isReadOnly();:判断事务是否只读。
  • String getName();:获取事务对象名称。

4、TransactionStatus

  • boolean isNewTransaction(); 判断是否是新的事务
  • boolean hasSavepoint(); 判断是否存在保存点
  • void setRollbackOnly(); 设置事务回滚
  • boolean isRollbackOnly(); 判断是否回滚
  • void flush(); 刷新事务
  • boolean isCompleted(); 判断事务是否完成

2、事务管理的方式

  • 编程式事务:通过编写代码来管理事务;
  • 声明式事务:通过XML配置或注解来管理事务。

2、基于XML方式的声明式事务

1、创建一个maven项目导入相关依赖

    mysqlmysql-connector-java5.1.45runtimecom.alibabadruid1.1.9org.mybatismybatis3.4.5org.mybatismybatis-spring1.3.1org.slf4jslf4j-log4j121.7.25org.springframeworkspring-jdbc5.0.8.RELEASEorg.aspectjaspectjweaver1.8.13org.springframeworkspring-webmvc5.0.8.RELEASEorg.springframeworkspring-test5.0.8.RELEASEtestjunitjunit4.12testorg.projectlomboklombok1.18.22provided

2、准备数据库

CREATE TABLE `account`  (`id` bigint(20) NOT NULL AUTO_INCREMENT,`balance` decimal(10, 0) NULL DEFAULT NULL,PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;INSERT INTO `account` VALUES (1, 10000);
INSERT INTO `account` VALUES (2, 0);

3、编写dao接口及Mapper.xml文件

  • dao接口
package cn.simplelife.mapper;import org.apache.ibatis.annotations.Param;import java.math.BigDecimal;/*** @ClassName AccountMapper* @Description* @Author simplelife* @Date 2022/11/23 15:34* @Version 1.0*/public interface AccountMapper {void addBalance(@Param("inId") Long inId, @Param("amount") BigDecimal amount);void subtractBalance(@Param("outId") Long outId, @Param("amount") BigDecimal amount);
}
  • mapper.xml文件


UPDATE accountSET balance=balance + #{amount}WHERE id = #{inId}UPDATE accountSET balance=balance - #{amount}WHERE id = #{outId}

4、编写实体类

package cn.simplelife.domain;import lombok.Data;import java.math.BigDecimal;/*** @ClassName Account* @Description* @Author simplelife* @Date 2022/11/23 15:15* @Version 1.0*/
@Data
public class Account {private Long id;private BigDecimal balance;
}

5、编写mybatis-config.xml配置文件





6、编写业务接口及实现类

  • 业务层接口
package cn.simplelife.service;import java.math.BigDecimal;/*** @ClassName IAccountService* @Description* @Author simplelife* @Date 2022/11/23 17:09* @Version 1.0*/public interface IAccountService {void transfer(Long outId, Long inId, BigDecimal amount);
}
  • 业务层实现类
package cn.simplelife.service.impl;import cn.simplelife.mapper.AccountMapper;
import cn.simplelife.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import java.math.BigDecimal;/*** @ClassName IAccountServiceImpl* @Description* @Author simplelife* @Date 2022/11/23 17:10* @Version 1.0*/@Service
public class IAccountServiceImpl implements IAccountService {@Autowiredprivate AccountMapper accountMapper;@Overridepublic void transfer(Long outId, Long inId, BigDecimal amount) {accountMapper.subtractBalance(outId, amount);System.out.println(10 / 0);accountMapper.addBalance(inId, amount);}
}

7、编写applicationContext.xml配置文件




8、编写测试类

import cn.simplelife.service.IAccountService;
import cn.simplelife.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import java.math.BigDecimal;/*** @ClassName SqlSessionFactoryTest* @Description* @Author simplelife* @Date 2022/11/23 15:26* @Version 1.0*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SqlSessionFactoryTest {@Autowiredprivate IAccountService iAccountService;@Testpublic void getSqlSessionTest() {System.out.println(MybatisUtils.getSqlSession());iAccountService.transfer(1L, 2L, new BigDecimal("100"));}
}

9、测试结果

  • 成功
    在这里插入图片描述
    在这里插入图片描述
  • 失败

在这里插入图片描述
在这里插入图片描述

3、基于注解的事务

1、修改配置文件如下




2、修改业务层方法

添加注解

package cn.simplelife.service.impl;import cn.simplelife.mapper.AccountMapper;
import cn.simplelife.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import java.math.BigDecimal;/*** @ClassName IAccountServiceImpl* @Description* @Author simplelife* @Date 2022/11/23 17:10* @Version 1.0*/@Service
public class IAccountServiceImpl implements IAccountService {@Autowiredprivate AccountMapper accountMapper;@Override@Transactionalpublic void transfer(Long outId, Long inId, BigDecimal amount) {accountMapper.subtractBalance(outId, amount);System.out.println(10 / 0);accountMapper.addBalance(inId, amount);}
}

相关内容

热门资讯

监控摄像头接入GB28181平... 流程简介将监控摄像头的视频在网站和APP中直播,要解决的几个问题是:1&...
Windows10添加群晖磁盘... 在使用群晖NAS时,我们需要通过本地映射的方式把NAS映射成本地的一块磁盘使用。 通过...
protocol buffer... 目录 目录 什么是protocol buffer 1.protobuf 1.1安装  1.2使用...
在Word、WPS中插入AxM... 引言 我最近需要写一些文章,在排版时发现AxMath插入的公式竟然会导致行间距异常&#...
【PdgCntEditor】解... 一、问题背景 大部分的图书对应的PDF,目录中的页码并非PDF中直接索引的页码...
Fluent中创建监测点 1 概述某些仿真问题,需要创建监测点,用于获取空间定点的数据࿰...
educoder数据结构与算法...                                                   ...
MySQL下载和安装(Wind... 前言:刚换了一台电脑,里面所有东西都需要重新配置,习惯了所...
MFC文件操作  MFC提供了一个文件操作的基类CFile,这个类提供了一个没有缓存的二进制格式的磁盘...
有效的括号 一、题目 给定一个只包括 '(',')','{','}'...