您的位置:首页 > 编程语言 > Java开发

spring事务方面解读: 基础配置,及事务回滚操作

2017-02-24 00:00 447 查看
摘要: spring事务边界配置,及事务回滚

很久没用过spring事务了,在这里做下简要介绍

事务边界



这句话说明,配置了事务边界,service方法里,只要运行过程中,出现异常bug ,service方法中存取操作都会回滚

配置事务边界

<!-- 事务通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="updAdvertByObj"  propagation="SUPPORTS" isolation="DEFAULT" read-only="true" />
<tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT"/>
<tx:method name="add*" propagation="REQUIRED" isolation="DEFAULT"/>
<tx:method name="edit*" propagation="REQUIRED" isolation="DEFAULT"/>
<tx:method name="remove*" propagation="REQUIRED" isolation="DEFAULT"/>
<tx:method name="*Tran"  propagation="REQUIRED" isolation="DEFAULT" />
<tx:method name="*" propagation="REQUIRED" isolation="DEFAULT" />
</tx:attributes>
</tx:advice>


<!-- 配置事务拦截器拦截哪些类的哪些方法,一般设置成拦截Service -->
<aop:config proxy-target-class="true">
<aop:pointcut id="serviceMethod" expression=" execution(* com.*.*.*.service..*.*(..)) or  execution(* com.*.*.*.*.impl..*.*(..))" />
<aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice" />
</aop:config>


@注解事务操作

// 指定回滚
@Transactional(rollbackFor=Exception.class)

抛出throw new RuntimeException("...");会回滚


事务传播行为类型

事务传播行为类型
说明
PROPAGATION_REQUIRED
如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。这是最常见的选择。
PROPAGATION_SUPPORTS
支持当前事务,如果当前没有事务,就以非事务方式执行。
PROPAGATION_MANDATORY
使用当前的事务,如果当前没有事务,就抛出异常。
PROPAGATION_REQUIRES_NEW
新建事务,如果当前存在事务,把当前事务挂起。
PROPAGATION_NOT_SUPPORTED
以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
PROPAGATION_NEVER
以非事务方式执行,如果当前存在事务,则抛出异常。
PROPAGATION_NESTED
如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与PROPAGATION_REQUIRED类 似的操作。
手动型事务操作

xml配置

<!-- 事务管理器(在service层面上实现事务管理) -->

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 事物模板 -->
<bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager" ref="transactionManager" />
</bean>


public service方法内部写上

@Autowired
private TransactionTemplate transactionTemplate;

public ResponseObj  doXXXX(){
ResponseObj obj;
// 新增基础信息
obj = transactionTemplate.execute(new TransactionCallback<ResponseObj>() {
ResponseObj responseObj =  new ResponseObj();
@Override
public ResponseObj doInTransaction(TransactionStatus status) {
try {
// 业务代码
} catch (Exception e) {
responseObj.setStatus(0);
responseObj.setShowMessage("操作失败");
status.setRollbackOnly();
e.printStackTrace();
}
responseObj.setStatus(1);
responseObj.setShowMessage("操作成功");
return responseObj;
}
});

return obj;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java EE Spring