Spring事务管理,声明式事务和编程式事务实现

数据库操作过程中,对于增删改等操作,因为涉及到数据库状态的变更,为保证数据安全,需要进行事务管理;Spring事务管理有两种方式,即声明式事务管理和编程式事务管理;

连接池配置:

jdbc configuration
jdbc.url=jdbc\:mysql\://127.0.0.1\:3306/ssm?useUnicode\=true&characterEncoding\=utf8&characterSetResults\=utf8
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=123456

以下为 优化配置
jdbc.filters=stat

jdbc.maxActive=20
jdbc.initialSize=1
jdbc.maxWait=60000
jdbc.minIdle=10
jdbc.maxIdle=15

jdbc.timeBetweenEvictionRunsMillis=60000
jdbc.minEvictableIdleTimeMillis=300000

jdbc.validationQuery=SELECT 'x'
jdbc.testWhileIdle=true
jdbc.testOnBorrow=false
jdbc.testOnReturn=false

jdbc.maxOpenPreparedStatements=20
jdbc.removeAbandoned=true
jdbc.removeAbandonedTimeout=1800
jdbc.logAbandoned=true


代码演示:

package com.dongzz.ssm.modules.system.service;

import com.dongzz.ssm.SpringBaseJunit;
import com.dongzz.ssm.modules.system.entity.SysUser;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.sql.DataSource;

/**
 * 编程式事务管理
 */
public class UserServiceTest extends SpringBaseJunit {

    @Autowired
    PlatformTransactionManager transactionManager;
    @Autowired
    DataSource dataSource;

    JdbcTemplate jdbcTemplate;

    @Test
    public void transactionTest() {
        String sql1 = "update book set name = '算法导论(原书篇3版)' where id = 1";
        String sql2 = "update book set name = 'Java编程思想(篇4版)' where id = 2";
        // 设置事务隔离级别 传播特性
        DefaultTransactionDefinition dtd = new DefaultTransactionDefinition();
        dtd.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
        dtd.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        // 获取事务状态,spring根据传播行为来开启事务
        TransactionStatus status = transactionManager.getTransaction(dtd);
        jdbcTemplate = new JdbcTemplate(dataSource);
        try {
            jdbcTemplate.update(sql1);
            jdbcTemplate.update(sql2);
            transactionManager.commit(status); // 提交事务
        } catch (Exception e) {
            e.printStackTrace();
            transactionManager.rollback(status); // 回滚事务
        }
    }
}

借助 spring 的 TransactionTemplate 工具类简化事务管理编码;

@Test
public void transactionTemplateTest() {
    String sql1 = "update book set name = '算法导论(原书篇3版)' where id = 1";
    String sql2 = "update book set name = 'Java编程思想(篇4版)' where id = 2";

    jdbcTemplate = new JdbcTemplate(dataSource);
    TransactionTemplate template = new TransactionTemplate(transactionManager);
    template.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
    template.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    template.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
            jdbcTemplate.update(sql1);
            jdbcTemplate.update(sql2);
        }
    });
}

spring xml 添加如下配置:


使用演示:

在需要开启事务管理的类或方法上添加 @Transactional 注解即可;

package com.dongzz.ssm.modules.system.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import cn.hutool.core.util.StrUtil;
import com.dongzz.ssm.common.base.impl.BaseMybatisServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dongzz.ssm.common.plugin.datatables.PageTableHandler;
import com.dongzz.ssm.common.plugin.datatables.PageTableHandler.CountHandler;
import com.dongzz.ssm.common.plugin.datatables.PageTableHandler.ListHandler;
import com.dongzz.ssm.common.plugin.datatables.PageTableHandler.OrderHandler;
import com.dongzz.ssm.common.exception.ServiceException;
import com.dongzz.ssm.common.plugin.datatables.PageTableRequest;
import com.dongzz.ssm.common.plugin.datatables.PageTableResponse;
import com.dongzz.ssm.modules.system.dao.SysUserMapper;
import com.dongzz.ssm.modules.system.entity.SysUser;
import com.dongzz.ssm.modules.system.service.UserService;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl extends BaseMybatisServiceImpl implements UserService {

    @Autowired
    private SysUserMapper userMapper;

    @Override
    @Transactional
    public void addUser(SysUser user) throws Exception {
        SysUser u = userMapper.selectUserByUname(user.getUsername());
        if (null != u) {
            throw new ServiceException("用户名已存在");
        }
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        user.setStatus("1");
        user.setIsDel("0");
        userMapper.insertSelective(user);
    }
}

spring xml 添加如下配置:


上述配置将 txAdvice 切面中的通知方法动态的切入到名称为 pc 的切入点表达式对应的位置,所有通配符匹配的方法均纳入事务管理;

Original: https://www.cnblogs.com/herokevin/p/15837679.html
Author: 暴走编程
Title: Spring事务管理,声明式事务和编程式事务实现

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/621664/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • zabbix部署

    zabbix zabbix zabbix介绍 zabbix特点 zabbix部署 zabbix介绍 zabbix是一个基于WEB界面的提供分布式系统监视以及网络监视功能的企业级的开…

    Linux 2023年6月13日
    0138
  • 计算机辅助数据绘图(matlabpythonjs)

    1. matlab绘图 官方说明:https://ww2.mathworks.cn/help/matlab/creating_plots/types-of-matlab-plots…

    Linux 2023年6月14日
    0123
  • CRC校验

    ​ 一:CRC概念 1.1、参考博客 参考的教程如下: 手算CRC及其实现 CRC校验算法原理分析 一文讲透CRC校验码-附赠C语言实例 CRC校验(手算与直观演示) CRC(循环…

    Linux 2023年6月13日
    090
  • 小团队如何妙用 JuiceFS

    早些年还在 ENJOY 的时候, 就已经在用 JuiceFS, 并且一路伴随着我工作过的四家小公司, 这玩意对我来说, 已经成了理所应当不可或缺的基础设施, 对于我服务过的小团队而…

    Linux 2023年6月14日
    0118
  • ssh远程连接服务

    TCP/22 SSH 应用层协议 作用:远程连接设备, 方便操作 1、本地管理方式 安装系统、故障修复 2、远程连接的方式 centos7.x版本中的ssh默认是开启的,所以查看一…

    Linux 2023年6月7日
    095
  • 《Redis开发与运维》——(五)Redis持久化(脑图)

    posted @2021-01-09 15:04 雪山上的蒲公英 阅读(122 ) 评论() 编辑 / 返回顶部代码 / Original: https://www.cnblogs…

    Linux 2023年5月28日
    0101
  • 【socket】基于Linux使用select上报温度–服务端

    select使用 * – select函数 – select流程图 – 服务端代码实现 select函数 select监视并等待多个文件描述符的…

    Linux 2023年6月13日
    095
  • 二叉树的基本操作(C语言版)

    今天走进数据结构之二叉树 二叉树的基本操作(C 语言版) 1 二叉树的定义 二叉树的图长这样: 二叉树是每个结点最多有两个子树的树结构,常被用于实现二叉查找树和二叉堆。二叉树是链式…

    Linux 2023年6月14日
    0110
  • Sublime快捷键大全

    Ctrl+Shift+P:打开命令面板Ctrl+P:搜索项目中的文件Ctrl+G:跳转到第几行Ctrl+W:关闭当前打开文件Ctrl+Shift+W:关闭所有打开文件Ctrl+Sh…

    Linux 2023年6月13日
    080
  • Python 装饰器

    直接进入主题 原代码 以下是原代码,要求给改代码添加统计时间功能 版本1(直接在原函数上修改) 可能有的同学就做出了下面这个版本 版本2(将函数当做参数传入) 经过修改上面的版本我…

    Linux 2023年6月13日
    0106
  • 国产化之虚拟ARM64-CPU安装银河麒麟操作系统

    背景 某个项目需要实现基础软件全部国产化,其中操作系统指定银河麒麟v4,CPU使用飞腾处理器。我本地没有这个国产的处理器,但飞腾是基于 _ARMv8_架构的64位处理器,所以理论上…

    Linux 2023年5月27日
    0330
  • Question05-查询所有同学的学生编号、学生姓名、选课总数、所有课程的总成绩

    * SELECT a.SID, a.Sname, COUNT(b.CID) 选课总数, SUM(score) 总成绩 FROM Student a , SC b WHERE a.S…

    Linux 2023年6月7日
    0145
  • pod(三):pod的管理

    服务器版本 docker软件版本 CPU架构 CentOS Linux release 7.4.1708 (Core) Docker version 20.10.12 x86_64…

    Linux 2023年6月7日
    098
  • Netty-如何写一个Http服务器

    前言 动机 最近在学习Netty框架,发现Netty是支持Http协议的。加上以前看过Spring-MVC的源码,就想着二者能不能结合一下,整一个简易的web框架(PS:其实不是整…

    Linux 2023年6月7日
    0104
  • Emacs Lisp 入门

    ;; This gives an introduction to Emacs Lisp in 15 minutes (v0.2d);;;; 英文原作者: Bastien / @bz…

    Linux 2023年6月13日
    0113
  • Redisson 分布式锁实战与 watch dog 机制解读

    源地址:https://www.cnblogs.com/keeya/p/14332131.html Original: https://www.cnblogs.com/SimonH…

    Linux 2023年5月28日
    0118
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球