Spring中的声明式事务管理

方式一:基于xml配置文件方式

1.创建一个测试类

package com.dzj.service;

import com.dzj.dao.UserDaoImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

@Service
public class UserService {

    @Autowired
    UserDaoImpl userDao;

    public String addAndReduce(int account){
        try {
            userDao.add(account);
            int i = 10/0;  //模拟异常
            userDao.reduce(account);
            return "成功了";
        }catch (Exception e){
            System.out.println("操作失败:"+e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();  //手动回滚
//            throw new RuntimeException("heihei");
            return "操作失败,有异常!";
        }

    }
}

2.编写xml配置文件 applicationbean.xml


3.测试方法

@Test
public void userTest1(){

    ClassPathXmlApplicationContext context =
            new ClassPathXmlApplicationContext("applicationbean.xml");
    UserService userService = context.getBean("userService", UserService.class);
    System.out.println(userService.addAndReduce(100));
}

方式二:基于xml配置文件的注解方式

1.创建一个测试类

package com.dzj.service;

import com.dzj.dao.UserDaoImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

@Service
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ)  //事务注解,可以加在类上面,也可以加在方法上
public class UserService {

    @Autowired
    UserDaoImpl userDao;

    public String addAndReduce(int account){
        try {
            userDao.add(account);
            int i = 10/0;  //模拟异常
            userDao.reduce(account);
            return "成功了";
        }catch (Exception e){
            System.out.println("操作失败:"+e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();  //手动回滚
//            throw new RuntimeException("heihei");
            return "操作失败,有异常!";
        }

    }
}

2.编写xml配置文件 applicationbean2.xml**


3.测试方法

@Test
public void userTest(){

    ClassPathXmlApplicationContext context =
            new ClassPathXmlApplicationContext("applicationbean2.xml");
    UserService userService = context.getBean("userService", UserService.class);
    System.out.println(userService.addAndReduce(100));
}

方式三:完全注解方式

1.创建一个配置类,替代xml配置文件

package com.dzj.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration  //配置类
@ComponentScan(basePackages = "com.dzj")  //注解扫描
@EnableTransactionManagement //开启事务
public class TxConfig {

    //1.创建数据库连接池
    @Bean
    public DruidDataSource getDruidDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///user_db");
        dataSource.setUsername("root");
        dataSource.setPassword("aadzj");
        return dataSource;
    }

    //2.配置JdbcTemplate对象,注入dataSource
    @Bean
    public JdbcTemplate getJdbcTemplate(DataSource dataSource){  //根据类型到ioc中找到DataSource
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        //注入DataSource
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }

    //3.创建事务管理器
    @Bean
    public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource){
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource);
        return transactionManager;
    }
}

2.创建一个测试类

package com.dzj.service;

import com.dzj.dao.UserDaoImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

@Service
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ)  //事务注解,可以加在类上面,也可以加在方法上
public class UserService {

    @Autowired
    UserDaoImpl userDao;

    public String addAndReduce(int account){
        try {
            userDao.add(account);
            int i = 10/0;  //模拟异常
            userDao.reduce(account);
            return "成功了";
        }catch (Exception e){
            System.out.println("操作失败:"+e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();  //手动回滚
//            throw new RuntimeException("heihei");
            return "操作失败,有异常!";
        }

    }
}

3.测试方法

@Test
public void userTest3(){

    AnnotationConfigApplicationContext context =
            new AnnotationConfigApplicationContext(TxConfig.class);
    UserService userService = context.getBean("userService", UserService.class);
    System.out.println(userService.addAndReduce(100));
}

Original: https://www.cnblogs.com/aadzj/p/15719776.html
Author: 小公羊
Title: Spring中的声明式事务管理

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

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

(0)

大家都在看

  • powershell 运行带路径的exe

    &"C:\Program Files\Python38\python.exe" demo_view.py 起因是nodejs16安装时,顺带装了pyth…

    Linux 2023年5月28日
    081
  • 绝了!起个好标题的9大技巧

    许多自媒体经常发一些标题雷人的文章,内容却非常空洞甚至低俗,技术创作领域也未能幸免,这个搞法被大家笑称为”标题党”。互联网是眼球经济,靠标题骗点击量的恶习将…

    Linux 2023年6月6日
    092
  • 009 Linux 文件大小统计与排序( du于df和sort)

    01 du 与 df 作用与区别? – du(disk usage) df(disk free) 02 du 常用命令示例 03 sort 常用参数 04 常用组合 d…

    Linux 2023年5月27日
    0152
  • 部署solr服务

    前言:请各大网友尊重本人原创知识分享,谨记本人博客:南国以南i 一、S orl单机部署 准备:solr5.5、tomcat8.5、jdk1.8 2.复制./solr-5.5.0/s…

    Linux 2023年6月14日
    0107
  • mac 如何仅安装redis-cli客户端

    brew tap ringohub/redis-cli brew update && brew doctor brew install redis-cli 【注】需…

    Linux 2023年5月28日
    0104
  • 高速USB转4串口产品设计-RS485串口

    基于480Mbps 高速USB转8路串口芯片CH344Q,可以为各类主机扩展出4个独立的串口。CH344芯片支持使用操作系统内置的CDC串口驱动,也支持使用厂商提供的VCP串口驱动…

    Linux 2023年6月7日
    092
  • 惊了!修仙=编程??

    大家好,我是良许。 在我记忆中,我们接触到的所有编程书籍都是这样的: [En] As far as I can remember, all the programming book…

    Linux 2023年5月27日
    084
  • CentOS7 源码安装Nginx及Nginx基本管理设置

    CentOS7 安装 参考文档 CentOS7最小安装后初始化安装工具 1:yum install net-tools 参考文档 2:源码安装wget 参考文档 或者执行 yum …

    Linux 2023年5月27日
    0110
  • redis的间隔性速度慢的问题

    php操作redis,偶尔间歇性很慢.查看redis日志发现:Asynchronous AOF fsync is taking too long (disk is busy?). …

    Linux 2023年5月28日
    074
  • short, int, long, long long各个类型的范围

    类型名称 字节数 取值范围 signed char 1 -2^7 ~ 2^7-1 -128~+127 short int 2 -2^14 ~ 2^14-1 -32768~+3276…

    Linux 2023年6月8日
    099
  • Linux 下统计文件夹下文件的数量

    1、查看当前目录下的文件数量(不包含子目录中的文件) 2、查看当前目录下的文件数量(包含子目录中的文件) 3、 查看当前目录下的文件夹目录个数(不包含子目录中的目录),同上述理,如…

    Linux 2023年6月13日
    098
  • Ubuntu系统报错The system is running in low-graphics mode

    我遇到过两次这种请况,这次解决了。很nice! 在csdn上搜到的大部分操作是: 鼠标进入系统 使用快捷键 Ctrl+Alt+F1 进入用户 输入密码 然后按照以下代码进行 cd …

    Linux 2023年5月27日
    091
  • Mysql数据库 ALTER 基本操作

    背景: ALTER作为DDL语言之一,工作中经常遇到,这里我们简单介绍一下常见的几种使用场景 新建两个测试表offices 和 employess CREATE TABLE off…

    Linux 2023年6月6日
    0101
  • Common LISP 命令大全

    书籍下载地址: Ansi Common Lisp 中文版|百度网盘 实用Common.Lisp编程 .pdf|百度网盘 LISP指令速查网站推荐: Simplified Commo…

    Linux 2023年6月6日
    0114
  • tcpreplay重放报文,tcpdump能抓到包,应用程序收不到包

    现象: 生产环境中有两台服务器A、B,A服务器实时有报文发往B服务器。为了在测试环境测试新功能,故在现网A服务器上tcpdump抓取发往B服务器的报文,然后在测试环境tcprewr…

    Linux 2023年6月14日
    095
  • ASP.NET MVC实现POST方式的Redirect

    我们知道,在ASP.NET MVC中,要从一个Action跳转到另一个Action,通常是用一系列以”Redirect”开头的方法 Redirect Red…

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