【问题标题】:Spring/Hibernate, share Session between two Physical TransactionsSpring/Hibernate,在两个物理事务之间共享 Session
【发布时间】:2018-09-15 09:50:36
【问题描述】:

Spring 和 Hibernate 是否支持两个不同(嵌套或顺序)物理事务之间的会话共享?

我知道 Spring 支持嵌套事务,但它是相同的物理事务,只是具有保存点,即嵌套事务在逻辑上是分开的:

来自 Spring 文档:

PROPAGATION_NESTED 使用具有多个可以回滚的保存点的单个物理事务。

那么,我可以实现类似于以下的行为吗:

@Transactional
void invokeOuterTransaction() {
    invokeInnerTransaction();
}
@Transactional
void invokeInnerTransaction() {
    // here are the same Session as in 'invokeOuterTransaction', 
    // but this transaction is new PHYSICAL transaction
}

【问题讨论】:

  • Hibernate 不支持保存点。

标签: java spring hibernate transactions spring-transactions


【解决方案1】:

因此,通过使用下面的设置探索这个问题,我发现 Hibernate Session “每个请求”而不是“每个事务”非常有趣。

设置: 休眠 5、Spring 5、PostgreSQL

下面是一个简短的类似java的快速伪代码:

@Controller {
    @Inject FirstService fServ;
    @Inject SecondService sServ;

    @RequestMapping
    handleHttpRequest() {
          fServ.invokeFirstTransactional();
          sServ.invokeSecondTransactional();
    }
}
FirstService {
   @Transactional
   void invokeFirstTransactional() {
        // Session object system hashcode = 187000543
        // Thread object system hashcode = 167000522

        // Transaction_ID in database = 650
   }
}
SecondService {
   @Transactional
   void invokeSecondTransactional() {
        // Session object system hashcode = 187000543
        // Thread object system hashcode = 167000522

        // Transaction_ID in database = 651
   }
}

如您所见 - 相同的 Hibernate 会话,相同的线程,但不同的物理事务!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-06
    • 2017-05-09
    • 2017-09-23
    • 2019-03-17
    • 1970-01-01
    • 2014-05-18
    • 2012-02-27
    • 2020-02-14
    相关资源
    最近更新 更多