• Spring


    总结

    • 声明式事务:非侵入式,本质是AOP,推荐!
    • 编程式事务:侵入式,需要在代码中调用 commit()、rollback()等事务管方法,还需要在代码中通过try catch,不推荐!

    ①编程式事务管理使用TransactionTemplate。

    ②声明式事务管理建立在AOP之上的。其本质是通过AOP功能,对方法前后进行拦截,将事务处理的功能编织到拦截的方法中,也就是在目标方法开始之前启动一个事务,在执行完目标方法之后根据执行情况提交或者回滚事务。

    声明式事务最大的优点就是不需要在业务逻辑代码中掺杂事务管理的代码,只需在配置文件中做相关的事务规则声明或通过@Transactional注解的方式,便可以将事务规则应用到业务逻辑中,减少业务代码的污染。

    唯一不足地方是,最细粒度只能作用到方法级别,无法做到像编程式事务那样可以作用到代码块级别。

    一、声明式事务配置(XML方式)

    1-pom文件中,添加 AOP Aspectj 的支持

    maven pom.xml 添加 Aspectj 的支持

    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.8.13</version>
    </dependency>

    2-准备给deleteUser()增加事务操作

    package constxiong.interview.transaction;
     
    import java.util.List;
    import java.util.Map;
     
    import org.springframework.jdbc.core.support.JdbcDaoSupport;
     
    public class UserDaoImpl extends JdbcDaoSupport implements UserDao {
        
        /**
         * 查询用户
         * @return
         */
        public List<Map<String, Object>> getUsers() {
            String sql = "select * from user";
            return this.getJdbcTemplate().queryForList(sql);
        }
        
        /**
         * 删除用户
         * @param id
         * @return
         */
        //@Transactional(rollbackFor=RuntimeException.class)
        public int deleteUser(int id){
            String sql = "delete from user where id = " + id;
            int result = this.getJdbcTemplate().update(sql);
            if (id == 1) {
                throw new RuntimeException();
            }
            return result;
        }
    }

    3-Spring配置文件中,配置声明式事务管理器 DataSourceTransactionManager

    <?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:context="http://www.springframework.org/schema/context"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
            
        <bean id="driver" class="com.mysql.jdbc.Driver"></bean>
        
        <bean id="datasource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
            <constructor-arg index="0" name="driver" ref="driver" />
            <constructor-arg index="1">
                <value>jdbc:mysql://localhost:3306/test</value>
            </constructor-arg>
            <constructor-arg index="2">
                <value>root</value>
            </constructor-arg>
            <constructor-arg index="3">
                <value>root</value>
            </constructor-arg>
        </bean>
        
        <bean id="userDao" class="constxiong.interview.transaction.UserDaoImpl">
            <property name="dataSource" ref="datasource"></property>
        </bean>
        
        <!-- 事务管理器 -->
        <bean id="tracnsactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="datasource"></property>
        </bean>
        
    </beans>

    4-配置事务通知 ,“确定为哪个/哪些方法配置事务”

    注意:<tx:method name="add*"> 表示事务会在所有以add开头的方法上,例如addUser(), addGoods()等

        <tx:advice id="txAdvice" transaction-manager="tracnsactionManager">
            <tx:attributes>
                <!-- 为连接点指定事务属性 -->
                <tx:method name="deleteUser" rollback-for="java.lang.RuntimeException"/>
            </tx:attributes>
        </tx:advice>

    另一个例子:

    5-配置事务切入,“确定切入点(哪个类)”

    <aop:config>
            <!-- 切入点配置 -->
            <aop:pointcut id="point" expression="execution(* *constxiong.interview.transaction.UserDao.deleteUser(..))" />
            <aop:advisor advice-ref="txAdvice" pointcut-ref="point"/>

    另一个例子:

    6-测试

    package constxiong.interview.transaction;
     
    import java.util.Map;
     
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
     
    public class TransactionTest {
     
        static ApplicationContext context = new ClassPathXmlApplicationContext("spring_transaction.xml");
        
        public static void main(String[] args) throws Exception {
            testAspectjTransaction();
        }
        
        
        private static void testAspectjTransaction() {
            UserDao userDao = (UserDao)context.getBean("userDao");
            printUsers(userDao);
            userDao.deleteUser(1);
        }
     
     
        private static void printUsers(UserDao userDao) {
            for (Map<String, Object> user : userDao.getUsers()) {
                System.out.println(user);
            }
        }
     
    }

    输出结果

    {id=1, username=user1}
    {id=2, username=user2}
    Exception in thread "main" java.lang.RuntimeException
        at constxiong.interview.transaction.UserDaoImpl.deleteUser(UserDaoImpl.java:28)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
        at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
        at com.sun.proxy.$Proxy2.deleteUser(Unknown Source)
        at constxiong.interview.transaction.TransactionTest.testAnnotationTransaction(TransactionTest.java:20)
        at constxiong.interview.transaction.TransactionTest.main(TransactionTest.java:13)

    二、声明式事务配置(@Transactional注解方式)

    和XML方式相比,有以下不一样的点

    1-在deleteUser()上增加@Transactional注解

    package constxiong.interview.transaction;
     
    import java.util.List;
    import java.util.Map;
     
    import org.springframework.jdbc.core.support.JdbcDaoSupport;
    import org.springframework.transaction.annotation.Transactional;
     
    public class UserDaoImpl extends JdbcDaoSupport implements UserDao {
        
        /**
         * 查询用户
         * @return
         */
        public List<Map<String, Object>> getUsers() {
            String sql = "select * from user";
            return this.getJdbcTemplate().queryForList(sql);
        }
        
        /**
         * 删除用户
         * @param id
         * @return
         */
        @Transactional(rollbackFor=RuntimeException.class)
        public int deleteUser(int id){
            String sql = "delete from user where id = " + id;
            int result = this.getJdbcTemplate().update(sql);
            if (id == 1) {
                throw new RuntimeException();
            }
            return result;
        }
    }

    2-pom文件里,启用事务注解

    同时,删除“切点”“切面”的配置

    <?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:context="http://www.springframework.org/schema/context"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
            
        <bean id="driver" class="com.mysql.jdbc.Driver"></bean>
        
        <bean id="datasource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
            <constructor-arg index="0" name="driver" ref="driver" />
            <constructor-arg index="1">
                <value>jdbc:mysql://localhost:3306/test</value>
            </constructor-arg>
            <constructor-arg index="2">
                <value>root</value>
            </constructor-arg>
            <constructor-arg index="3">
                <value>root</value>
            </constructor-arg>
        </bean>
        
        <bean id="userDao" class="constxiong.interview.transaction.UserDaoImpl">
            <property name="dataSource" ref="datasource"></property>
        </bean>
        
        <!-- 事务管理器 -->
        <bean id="tracnsactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="datasource"></property>
        </bean>
        
        <!-- 启用事务注解 -->
        <tx:annotation-driven transaction-manager="tracnsactionManager"/>
        
    </beans>

    三、编程式事务

    1-pom引入driver和DataSource

    可以通过 java.sql.Connection 控制事务

    <?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:context="http://www.springframework.org/schema/context"
        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">
            
        <bean id="driver" class="com.mysql.jdbc.Driver"></bean>
     
        <bean id="datasource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
            <constructor-arg index="0" name="driver" ref="driver" />
            <constructor-arg index="1">
                <value>jdbc:mysql://localhost:3306/test</value>
            </constructor-arg>
            <constructor-arg index="2">
                <value>root</value>
            </constructor-arg>
            <constructor-arg index="3">
                <value>root</value>
            </constructor-arg>
        </bean>
        
    </beans>

    2-编程式事务内核:在代码中侵入式控制事务

    package constxiong.interview.transaction;
     
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
     
    import javax.sql.DataSource;
     
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
     
    public class TransactionTest {
     
        public static void main(String[] args) throws Exception {
            testManualTransaction();//测试函数式控制事务
        }
        
        private static void testManualTransaction() throws SQLException {
            ApplicationContext context = new ClassPathXmlApplicationContext("spring_transaction.xml");
            DataSource ds = (DataSource)context.getBean("datasource");
            Connection conn = ds.getConnection();
            try {
                initTable(conn);//初始化表
                conn.setAutoCommit(false);//设置不自动提交事务
                queryUsers(conn);//查询打印用户表
                deleteUser(conn);//删除 id=1 用户
                conn.rollback();//回滚
                queryUsers(conn);//查询打印用户表
            } finally {
                conn.close();
            }
        }
     
        private static void initTable(Connection conn) throws SQLException {
            conn.createStatement().execute("drop table if exists user");
            conn.createStatement().execute("create table user(id int, username varchar(60)) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");//是否支持事务与数据库引擎有关,此处删除 ENGINE=InnoDB DEFAULT CHARSET=utf8 可能不支持事务
            conn.createStatement().execute("insert into user values(1, 'user1')");
            conn.createStatement().execute("insert into user values(2, 'user2')");
        }
     
        private static void deleteUser(Connection conn) throws SQLException {
            conn.createStatement().execute("delete from user where id = 1");
        }
     
        private static void queryUsers(Connection conn) throws SQLException {
            Statement st = conn.createStatement();
            st.execute("select * from user");
            ResultSet rs = st.getResultSet();
            while (rs.next()) {
                System.out.print(rs.getString("id"));
                System.out.print(" ");
                System.out.print(rs.getString("username"));
                System.out.println();
            }
        }
        
    }

    删除用户语句回滚,打印出两个用户

    1 user1
    2 user2
    1 user1
    2 user2
  • 相关阅读:
    谬论之程序猿的眼光看世界
    phpStudy-坑爹的数据库管理器-phpMyAdmin的默认用户名和密码
    解决Delphi 2010启动时出现cannot create xxxxEditorLineEnds.ttr问题
    数据库中增加操作insert into的用法和查询select的用法
    TRichEdit怎样新增的内容到最后一行?
    BCB将RichEdit光标移到最后一行
    怎么把焦点放在RichEdit的最后一行
    Panel自动变颜色
    怎么判断pagecontrol下的TabSheet是否打开还是关闭求答案
    用Setup Factory7.0怎样打包delphi的BDE?
  • 原文地址:https://www.cnblogs.com/frankcui/p/14071006.html
Copyright © 2020-2023  润新知