spring 事务管理

基本概念

  事务:一组操作,要么都成功,要么都失败。

  举例:a转账给b 有2个操作,a账户扣钱,b账户加钱。必须保证扣钱 和加钱操作同时成功或失败。这里暂时不讨论分布式事务。

  特性:acid 

A:原子性(Atomicity)
事务是数据库的逻辑工作单位,事务中包括的诸操作要么全做,要么全不做。
C:一致性(Consistency)
事务执行的结果必须是使数据库从一个一致性状态变到另一个一致性状态。一致性与原子性是密切相关的。
I:隔离性(Isolation)
一个事务的执行不能被其他事务干扰。
D:持续性/永久性(Durability)
一个事务一旦提交,它对数据库中数据的改变就应该是永久性的。
============================================================

oracle 默认的事务级别是Read committed

mysql 默认的事务级别是Repeatable Read
事务隔离级别越高,数据出现错乱的问题就越低,但是性能就越低。

Spring 是怎么管理事务的呢?编程式事务管理 和声明式事务管理 ,实际开发中 一般使用声明式事务管理。举例如下

第一步:导入相应jar.

       * aspectj

第二步:配置xml【需要注意:1引入切面和事务的xml约束 】

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <!-- 注册事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 数据源 --> <property name="dataSource" ref="dataSource" /> </bean> <!-- 通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 传播行为 REQUIRED ab a有事务 b不开启事 务 ,a没有事务 开启新的事务 a b 就在一个事务 SUPPORTS 有事务就在那个事务,没有事务就不开启事务 --> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="create*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="find*" propagation="SUPPORTS" read-only="true" /> <tx:method name="select*" propagation="SUPPORTS" read-only="true" /> <tx:method name="get*" propagation="SUPPORTS" read-only="true" /> </tx:attributes> </tx:advice> <!-- 切面 配置事务 proxy-target-class="true" 强制使用cglib代理 --> <aop:config > <aop:advisor advice-ref="txAdvice" <!-- 其中第一个*代表返回值,第二*代表dao下子包,第三个*代表方法名,“(..)”代表方法 参数 --> pointcut="execution(* com.xxx.service.*.* (..))" /> </aop:config> </beans>

 

  

 

注意:这里只截取了事务配置代码,详细的将在后面的ssm整合中写出来。



原文地址:https://www.cnblogs.com/javabigdata/p/5672054.html