• Spring对事务的处理


    1、加入spring-jdbc.jar包

    2、配置数据源

    3、配置spring事务管理器,spring的事务出现在业务层。

        
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
            <property name="driverClassName" value="${jdbc.driverClassName}"/>
            <property name="url" value="${jdbc.url}"/>
            <property name="username" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
        </bean>
        
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
        
        

    4.加入事务包,spring-tx.jar.

    (1)基于xml配置的事务

    (2)在xml中声明命名空间

    xmlns:tx="http://www.springframework.org/schema/tx"
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd

    (3)

     <aop:config>
        <aop:pointcut id="productServiceMethods"
                expression="execution(* product.ProductService.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="productServiceMethods"/>
      </aop:config>
    
      <tx:advice id="txAdvice" transaction-manager="myTxManager">
        <tx:attributes>
          <tx:method name="increasePrice*" propagation="REQUIRED"/>
          <tx:method name="someOtherBusinessMethod" propagation="REQUIRES_NEW"/>
          <tx:method name="*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
      </tx:advice>

    propagation:事务的传播属性,在方法为increasePrice开头的方法中需要在一个事务中运行,指定required

    注意:spring事务,只有在运行时异常时才会发生回滚,如果其他的非运行时异常不会回滚

    这种情况可以修改在

     <tx:method name="increasePrice*" propagation="REQUIRED"/>
    指定rollback-for="java.lang.exception"

    5、基于注解的事务

     (1)在xml中开启事务注解,指定事务管理器名字

    <tx:annotation-driven transaction-manager="transactionManager"/>

    (2)在要执行事务的类或者方法上边添加@Transactional标注

    @Transactional
        public void show(){
            userDao.showUser();
        }

    (3)在只读事务中,加入readonly=true,查找的时候用只读可以提高效率

        @Transactional(readOnly=true)
        public void show(){
            userDao.showUser();
        }
  • 相关阅读:
    sql编码造成的安全问题(基于mysql8.0版本)
    [HY000] [2054] php连接mysql时错误
    jetbrains(phpstrom,webstorm等)破解
    XSS(二)
    XSS(一)
    ctf中rsa攻击方法
    扩展欧几里得算法证明及求乘法逆元
    mac泛洪攻击&arp欺骗(python脚本)
    Flutter 中 实现 单选对话框 和页面中实现单选框
    解决Flutter混合开发时 is not a readable directory 问题
  • 原文地址:https://www.cnblogs.com/hpustudent/p/4316537.html
Copyright © 2020-2023  润新知