• 事务框架之编程式事务(手动开启,手动提交)


    编程式事务:需要手动的开启事务,提交。

    声明式事务:Spring 中的事务是利用AOP 编程思想,底层是通过动态代理的方式(cglib动态代理),cglib 底层是通过asm字节码框架,实现动态的事务功能,不许要手动的开启,提交

    以下例子是通过编程事务实现手动事务来对比Spirng 中的AOP封装手动事务:

    例1:手动事务的begin() , commit() ,rollback()

     测试数据库:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd">
        <context:component-scan base-package="com.hella.thread.transaction"></context:component-scan>
        <aop:aspectj-autoproxy></aop:aspectj-autoproxy> <!-- 开启事物注解 -->
    
        <!-- 1. 数据源对象: C3P0连接池 -->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
            <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/testdb"></property>
            <property name="user" value="root"></property>
            <property name="password" value="123456"></property>
        </bean>
    
        <!-- 2. JdbcTemplate工具类实例 -->
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
    
        <!-- 3.配置事务 -->
        <bean id="dataSourceTransactionManager"
            class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
    
    </beans>

    表结构:cat 表   id ,cat_age,cat_name 三个字段

    CREATE TABLE `cat` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `cat_age` varchar(255) DEFAULT NULL,
      `cat_name` varchar(255) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

    Service 层:

    public interface UserService {
        
        public void addUser();
    
    }
    @Service
    public class UserServiceImpl implements UserService {
        @Autowired
        private UserDao userDao;
        
        public void addUser() {        
            //添加到数据库
            System.out.println("开始添加");
            userDao.add(1, "tom", "12"); //service 层没有事务的情况下,很容易出现问题,不能保证原子性
        }
    
    }

    dao 层:

    @Repository
    public class UserDao {
        @Autowired
        private JdbcTemplate jdbcTemplate;
    
        public void add(int id, String age, String name) {
            String sql = "INSERT INTO cat(id,cat_age,cat_name) VALUES(?,?,?);";
            int updateResult = jdbcTemplate.update(sql, id, age, name);
            System.out.println("updateResult:" + updateResult);
        }
    }

    程序的入口:

    public class App {
        public static void main(String[] args) {
            ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext(
                    "spring.xml");
            UserService userService = (UserService) classPathXmlApplicationContext.getBean("userServiceImpl");
            userService.addUser();
        }
    
    }

    这是没有配置事务的情况的下,当往数据库插入多条数据的时候,一个数据有问题,其他数据也可以插入,不能保证原子性,所以我们需要添加事务:

    AOP log:额外的功能

    @Component // 放入到Spring容器中
    @Aspect // 定义切面类 公共的log部分
    public class AspectLog {
    
        // aop 编程的通知 前置通知 后置通知 环绕通知 异常通知 运行通知
    
        @Before("execution (* com.hella.thread.transaction.service.UserService.addUser(..) )")
        public void before() {
            System.out.println("前置通知。。。。");
    
        }
    
        @After("execution (* com.hella.thread.transaction.service.UserService.addUser(..) )")   // 若是包名写的不对,或是类名不对:[Xlint:invalidAbsoluteTypeName]error
    public void after() {
            System.out.println("后置通知。。。");
        }
    
        @Around("execution (* com.hella.thread.transaction.service.UserService.addUser(..) )")
        public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
            System.out.println("环绕通知  proceed前 。。。");
            proceedingJoinPoint.proceed();
            System.out.println("环绕通知 proceed后。。。"); // 异常则proceed后就不会执行
        }
    
        @AfterReturning("execution (* com.hella.thread.transaction.service.UserService.addUser(..) )")
        public void returning() {
            System.out.println("运行通知 。。。");
    
        }
    
        @AfterThrowing("execution (* com.hella.thread.transaction.service.UserService.addUser(..) )")
        public void afterThrowing() {
            System.out.println("异常通知");
        }
    
    }

    编写事务类:包含begin() commit() rollback()

    @Component
    public class TransactionUtils {
    
        @Autowired
        private DataSourceTransactionManager dataSourceTransactionManager;
    
        // 开启事务
        public TransactionStatus begin() {
            TransactionStatus transaction = dataSourceTransactionManager.getTransaction(new DefaultTransactionAttribute());
            return transaction;
        }
        // 提交事务
        public void commit(TransactionStatus transaction) {
            dataSourceTransactionManager.commit(transaction);
        }
    
        // 回滚事务
        public void rollback(TransactionStatus transaction) {
            dataSourceTransactionManager.rollback(transaction);
        }
    }

    service 层的方法需要加入事务:

    @Service
    public class UserServiceImpl implements UserService {
    
        @Autowired
        private UserDao userDao;
        @Autowired
        private TransactionUtils transactionUtils;
    
        @Override
        public void addUser() {
            TransactionStatus transactionStatus = null;
            try {
                transactionStatus = transactionUtils.begin();
                // 添加到数据库
                System.out.println("开始添加");
                userDao.add(1, "tom", "12");
                int i = 1 / 0;
                if (transactionStatus != null) {
                    transactionUtils.commit(transactionStatus);
                }
            } catch (Exception e) {
                e.printStackTrace();
                // if (transactionStatus != null) {
                // transactionUtils.rollback(transactionStatus);
                // }
            } finally { // 在catch 里面回滚也可以,但是catch 回滚后异常通知就接收不到了
                if (transactionStatus != null) {
                    transactionStatus.rollbackToSavepoint(transactionStatus);
                }
            }
        }
    
    }

    这样编程式事务就OK 了

  • 相关阅读:
    感知机简单算法的实现
    C语言博客作业02
    我的第二次C语言作业
    [原]wpf foundation Part 1 of n (object resource )
    [orginal]TabControlView based on css ,js and html .
    [orginal]checkBox based on web(thinking in & implementation)
    [orginal] Progressbar implementation with js,css,and html
    [orginal]Combolist visual design & and implementation ( based on css ,js and html)
    [orginal] nice look ListBox with powerful methodes designing & implementation based on web technology.
    [orginal]treeView control based on WEB
  • 原文地址:https://www.cnblogs.com/pickKnow/p/11135310.html
Copyright © 2020-2023  润新知