【问题标题】:How can I get a "start of transaction" timestamp in Spring + JPA + Hibernate setup?如何在 Spring + JPA + Hibernate 设置中获得“事务开始”时间戳?
【发布时间】:2011-01-13 06:19:58
【问题描述】:

我正在使用 Spring 3.0.5、JPA、Hibernate 3.5.5-Final 和 Spring 的 JpaTransactionManager。有人知道以编程方式获取每个事务开始的时间戳的简单方法吗?

【问题讨论】:

    标签: java hibernate spring jpa transactions


    【解决方案1】:

    想法

    因为JpaTransactionManager 扩展了AbstractPlatformTransactionManager 每个事务都以调用#getTransaction 方法开始,您可以在该方法周围写一个aspect。

    方面

    @Aspect
    public class AspectAroundTransactions() {
       @Pointcut("execution(* org.springframework.*.AbstractPlatformTransactionManager.getTransaction(..))" )
       public void newTransaction() {}
    
       @Before("newTransaction() && args(transactionDefinition,..)")
       public void beforeStartOfTransaction(TransactionDefinition transactionDefinition) {
          // here goes you code
          long start = System.nanoTime();
          System.out.println("Transaction " + transactionDefinition.getName() + " started at " + start );
       }
    }
    

    【讨论】:

    • 谢谢。而且我想我可以使用 TransactionSynchronizationManager.bindResource 将时间戳与 tx 关联起来。
    • 你确定吗?使用 TransactionSynchronizationManager.bindResource(Object, Object) 您将资源绑定到线程,而不是事务,因此如果您在同一个线程中使用多个事务,您将始终覆盖您的时间戳...
    • 我在切面方面遇到了一些麻烦,所以我只是扩展了 JpaTransactionManager(不是我知道的那么干净)并使用 doBegin 和 doCleanupAfterCompletion 来设置/清除时间戳。我没有在一个线程上激活多个 tx,所以现在还可以。
    • 既然所有 tx 管理器都应该实现 PlatformTransactionManager 接口 (static.springsource.org/spring/docs/3.0.x/javadoc-api/org/…),也许最好做一个方面来绕过它的 getTransaction 方法 (static.springsource.org/spring/docs/3.0.x/javadoc-api/org/…)。
    • 所以 pointcout 应该是这样的:@Pointcut("execution(* org.springframework.transaction.PlatformTransactionManager.getTransaction(..))" )
    【解决方案2】:

    可以在 WEB-INF 中使用过滤器来执行此操作 - 它会将时间戳作为命名属性注入到请求上下文中。时间戳不会是“事务”时间戳,而是请求时间戳。但我怀疑它会做你想做的事。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-03
      • 2021-12-14
      • 2011-08-22
      • 1970-01-01
      • 2016-01-26
      相关资源
      最近更新 更多