编程式事务需要在代码中加入处理事务的逻辑,可能需要在代码中显示调用beginTransaction(),commit(),rollback()等事务管理相关的方法,如在执行a方法时候需要事务处理,那么就要在a方法开始时候开启事务结束关闭事务
编程式事务部分重要代码:
<span class="comment" style="line-height: 18px; font-family: Consolas, 'Courier New', Courier, mono, serif; margin: 0px; padding: 0px; border: none; color: rgb(0, 130, 0); background-color: inherit;">//通过DefaultTransactionDefinition对象来持有事务处理属性</span><span style="line-height: 18px; font-family: Consolas, 'Courier New', Courier, mono, serif; margin: 0px; padding: 0px; border: none; background-color: inherit;"> </span>
<span style="white-space:pre"> </span>final DefaultTransactionDefinition definition=new DefaultTransactionDefinition();
definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
<span style="color: rgb(0, 130, 0); font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 18px;"><span style="white-space:pre"> </span>//获取事务的状态</span>
final TransactionStatus status=transactionManager.getTransaction(definition);
<span style="white-space:pre"> </span>try{
<span style="white-space:pre"></span><pre name="code" class="java"><span class="comment" style="margin: 0px; padding: 0px; border: none; color: rgb(0, 130, 0); font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 18px; background-color: rgb(248, 248, 248);"><span style="white-space:pre"> </span>//调用需要进行事务处理的目标方法提交</span>
transactionManager.commit(status);
<span style="white-space:pre"> </span>}catch(){
<pre name="code" class="java"><span><span style="color: rgb(0, 130, 0); font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 18px; background-color: rgb(248, 248, 248);"><span style="white-space:pre"> </span>//调用目标方法过程中产生异常,则对事务进行回滚处理</span></span>
transactionManager.rollback(status);
<span style="white-space:pre"> </span>}
声明式事务的做法是在a方法外围添加注解或者直接在配置文件中定义,a方法需要事务处理,在springzhong 会通过配置文件在a方法前后拦截,并添加事务
声明事务实现部分代码是在方法或类添加如下的注解
<span style="white-space:pre"> </span>@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
2钟事务的spring配置我学习没有找到不一样的地方,希望路过的大神看到有错帮忙指正下