Java Spring hibernate,事务提交或事务回滚后如何调用某些方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23651464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 00:31:15  来源:igfitidea点击:

Spring hibernate , how to call some method after transaction commit or transaction rollback

javaspringhibernatetransactions

提问by Josef Procházka

I need to call some method after transaction succes or rollback. I am using as

我需要在事务成功或回滚后调用一些方法。我正在使用

    <bean name="openSessionInViewInterceptor" class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
                <property name="sessionFactory">
                    <ref local="mysessionFactory"/>
                </property>
    </bean>

    <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory">
            <ref local="mysessionFactory"/>
        </property>
    </bean>

<tx:annotation-driven transaction-manager="txManager" proxy-target-class="true"/>

The application use some external web services which needs to be "cleaned" when the internal transaction gets rollbacked. Is there way how to accomplish this without using declarative transaction management.

当内部事务回滚时,应用程序使用一些需要“清理”的外部 Web 服务。有没有办法在不使用声明性事务管理的情况下实现这一点。

采纳答案by Jose Luis Martin

  • From Hibernate, you could extends EmptyInterceptorand override afterTransactionCompletion()method and register it in SessionFactoryBeanor HibernateTransactionManager.

  • From Spring you could extends TransactionSynchronizationAdapterand override afterCompletion()and register when appropriate with TransactionSynchronizationManager#registerSynchronization().

  • 在 Hibernate 中,您可以扩展EmptyInterceptor和覆盖 afterTransactionCompletion()方法并将其注册到 SessionFactoryBean或 中HibernateTransactionManager

  • 从春天你可以延伸TransactionSynchronizationAdapter和覆盖afterCompletion(),并注册时用适当的 TransactionSynchronizationManager#registerSynchronization()

Edit

编辑

An Example of using Spring Aop to add a synchronization to all methods annotated with @Transactional

使用 Spring Aop 向所有标注的方法添加同步的示例 @Transactional

@Aspect
class TransactionAspect extends TransactionSynchronizationAdapter {

    @Before("@annotation(org.springframework.transaction.annotation.Transactional)")
    public void registerTransactionSyncrhonization() {
        TransactionSynchronizationManager.registerSynchronization(this);

    }

    @Override
    public void afterCompletion(int status) {
        // code 
    }
}

回答by Alan Hay

Spring has various classes which might be of interest here:

Spring 有各种可能在这里感兴趣的类:

http://docs.spring.io/spring/docs/3.2.x/javadoc-api/org/springframework/transaction/support/TransactionSynchronization.html

http://docs.spring.io/spring/docs/3.2.x/javadoc-api/org/springframework/transaction/support/TransactionSynchronization.html

http://docs.spring.io/spring/docs/3.2.x/javadoc-api/org/springframework/transaction/support/TransactionSynchronizationAdapter.html

http://docs.spring.io/spring/docs/3.2.x/javadoc-api/org/springframework/transaction/support/TransactionSynchronizationAdapter.html

http://docs.spring.io/spring/docs/3.2.x/javadoc-api/org/springframework/transaction/support/TransactionSynchronizationManager.html

http://docs.spring.io/spring/docs/3.2.x/javadoc-api/org/springframework/transaction/support/TransactionSynchronizationManager.html

There's some example code here:

这里有一些示例代码:

http://azagorneanu.blogspot.co.uk/2013/06/transaction-synchronization-callbacks.html

http://azagorneanu.blogspot.co.uk/2013/06/transaction-synchronization-callbacks.html



Update 2016

2016 年更新

The event handling infrastructure introduced in Spring 4.2 makes this much simpler.

Spring 4.2 中引入的事件处理基础设施使这变得更加简单。

See:

看:

https://spring.io/blog/2015/02/11/better-application-events-in-spring-framework-4-2#transaction-bound-events

https://spring.io/blog/2015/02/11/better-application-events-in-spring-framework-4-2#transaction-bound-events

Another popular improvement is the ability to bind the listener of an event to a phase of the transaction. The typical example is to handle the event when the transaction has completed successfully

另一个流行的改进是能够将事件的侦听器绑定到事务的一个阶段。典型的例子是在事务成功完成时处理事件

@Component
public class MyComponent {

  @TransactionalEventListener(condition = "#creationEvent.awesome")
  public void handleOrderCreatedEvent(CreationEvent<Order> creationEvent) { 
    ...
  }

}

@TransactionalEventListeneris a regular @EventListenerand also exposes a TransactionPhase, the default being AFTER_COMMIT. You can also hook other phases of the transaction (BEFORE_COMMIT, AFTER_ROLLBACK and AFTER_COMPLETION that is just an alias for AFTER_COMMIT and AFTER_ROLLBACK).

@TransactionalEventListener是一个常规的@EventListener,也公开一个 TransactionPhase,默认是 AFTER_COMMIT。您还可以挂钩事务的其他阶段(BEFORE_COMMIT、AFTER_ROLLBACK 和 AFTER_COMPLETION,它们只是 AFTER_COMMIT 和 AFTER_ROLLBACK 的别名)。

回答by Michail Michailidis

Using Spring 4+: The easiest/cleanest way without using global aspects and configurations is based on my answer here: https://stackoverflow.com/a/43322052/986160

使用 Spring 4+:不使用全局方面和配置的最简单/最干净的方法基于我在此处的回答:https: //stackoverflow.com/a/43322052/986160

If you need a callback on a @Transactionalmethod after it successfully commits just add that in the beginning of the method:

如果@Transactional在成功提交后需要对方法进行回调,只需在方法的开头添加:

@Service
public class OneService {

    @Autowired
    OneDao dao;

    @Transactional
    public void a transactionalMethod() {
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter(){
            public void afterCommit(){
                //do stuff right after commit
                System.out.println("commit!!!");

            }
        });
        //do db stuff
        dao.save();
    }
}