事务配置-基于tx/aop配置切面增强事务

来源:互联网 发布:视听语言 知乎 编辑:程序博客网 时间:2024/05/17 20:27

什么是事务?

所谓事务是用户定义的一个数据库操作序列,这些操作要么全做,要么全不做,是一个不可分割的工作单位

事务的特性?

原子性:要么全做,要么全不做。
一致性:说的是全部做,和全不做,这时数据库处于一致性,如果一个做,一个不做,就认为不一致。
隔离性:一个事务的执行不能被其他事务干扰,即一个事务的内部操作以及使用的数据对其他并发事务是隔离的。
持续性:一个事务一旦提交,它对数据库中数据的改变就应该是永久行的。

如何声明事务管理

基于TransactionProxyFactoryBean方式
基于tx/aop配置切面增强事务
基于注解
本篇主要说下,基于tx/aop配置切面增强事务。

1:引入命名空间
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/tx  http://www.springframework.org/schema/tx/spring-tx-3.2.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
2:tx\aop核心配置
  <!-- 配置事务属性 --><tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes>    <tx:method name="add*" propagation="REQUIRES_NEW" />    <tx:method name="update*" propagation="REQUIRES_NEW" />    <tx:method name="delete*" propagation="REQUIRES_NEW" />    <tx:method name="*" read-only="true"/></tx:attributes></tx:advice><!-- 配置事务切入点,以及把事务切入点和事务属性关联起来 --><aop:config proxy-target-class="true"><aop:pointcut expression="execution(* com.yc.service.*.*(..))"    id="ServicePointcut" /><aop:advisor advice-ref="txAdvice" pointcut-ref="ServicePointcut" /></aop:config> 

在标签中,常见属性及其说明如下,其中,除了name属性是必选外,其他都是可选的:

属性 说明 默认 允许值 name 匹配方法名 必须声明,至少为* 可使用*通配符 propagation 事务传播行为 REQUIRED REQUIRED,SUPPORTS和MANDATORY和REQUIRES_NEW和NOT_SUPPORTED和NEVER和NESTED read-only 设置当前事务是否只读 false true,false isolation 事务隔离级别 DEFAULT READ_UNCOMMITTED和READ_COMMITTED和REPEATABLE_READ和SERIALIZABLE timeout 设置事务的超时时间 -1 默认由顶层事务系统决定 rollback-for 内容为异常名,表示当抛出这些异常时事务回滚,可以用逗号分隔配置多个 无默认值 可以使用异常名称的片段进行匹配如ception等 no-rollback-for 内容为异常名,表示当抛出这些异常时继续提交事务,可以用逗号分隔配置多个 无默认值 可以使用异常名称的片段进行匹配如ception等
原创粉丝点击