事务开始时的侦听器 [英] Listener on transaction start

查看:97
本文介绍了事务开始时的侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个干净的解决方案,以使事务开始时具有侦听器.这意味着我希望在春季上下文中,侦听器是一个bean(组件),它将在启动新事务时从TransactionPlatformManager或Hibernate Session或类似的东西接收事务启动事件.

发生的事情:

@Component
class TransactionListener implements ?? {

    @Autowired
    private Something x;

    public void onTransactionBegin(...) {
        x.doSomething()
    }

}

具体来说,我正在缓解系统范围的问题,我需要在事务开始时设置一个本地线程,以便可以在休眠实体的处理中进一步访问该本地线程以获取信息.

我调查了资料来源,发现没有任何痕迹可以实现这种侦听器.我发现的唯一解决方案是将HibernateTransactionManager及其doBegin()方法作为子类,但我觉得它不是特别好.

解决方案

Spring的afterTransactionBegin可能会有些运气#afterTransactionBegin(org.hibernate.Transaction)"rel =" nofollow> https://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/Interceptor.html#afterTransactionBegin(org.hibernate.Transaction)

I am looking for a clean solution to have a listener for transaction start. That means I would like the listener to be a bean (component) in the spring context that would receive an event on transaction start from TransactionPlatformManager or Hibernate Session or something similar, at the point where a new transaction is started.

Something along:

@Component
class TransactionListener implements ?? {

    @Autowired
    private Something x;

    public void onTransactionBegin(...) {
        x.doSomething()
    }

}

To be concrete, I am mitigating a system wide problem and I need to set a thread local when transaction starts, so I can access that thread local further in the processing of hibernate entities to retrieve info.

I looked into sources and found no traces for such listener to be achievable. The only solution I found was to subclass HibernateTransactionManager and its doBegin() method, which I don't find particularly nice.

解决方案

Spring have some transaction callbacks in its TransactionSynchronization, however as you correctly have noticed, there is no callback for transaction start, my mistake.

As far as I know, Spring will not let you know when transactions start, although this may vary from different implementations PlatformTransactionManager. If you want to hook into Spring transaction, I believe you are left with

  1. Subclass the transaction manager and invoke some callback
  2. Create an advice for @Transactional with spring-aop (this will only work if you use annotations, obviously)

If you're using Hibernate, you might have some luck with afterTransactionBegin in https://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/Interceptor.html#afterTransactionBegin(org.hibernate.Transaction)

这篇关于事务开始时的侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆