仅为一种方法更改 Hibernate 事务超时?

Alter Hibernate transaction timeout for only one method?

有没有办法改变Hibernate default transaction timeout value for only one method in a Spring Boot 2 JPA Repository? I want to keep the default 30s for my application (which contains both JPA Repositories and legacy repositories using a Hibernate SessionFactory), but allow a job (EDIT: taking place in a standalone transaction) that usually takes considerably more to be run. I'm wondering whether there is a way to specify exceptional situations, like you can except Transactions from rollbacking in certain situations

我正在寻找不需要创建与我用于其他方法不同的 HibernateTransactionManager 的解决方案。

Spring 有一个 @Transactional 注释,用于标记在事务上下文中应该 运行 的方法(以及范围)。此注释具有 timeout 属性,可用于覆盖默认超时。

请注意,超时只能在事务级别设置,因此 timeout 属性仅在注释导致启动新事务时使用。该文档明确指出:“专为与 Propagation.REQUIRED 或 Propagation.REQUIRES_NEW 一起使用而设计,因为它仅适用于新启动的交易。”

Propagation.REQUIRED 只会在还没有活动事务时启动新事务,因此如果您想确保设置超时,则需要启动新事务,因此最好使用 Propagation.REQUIRES_NEW.

注释因此为:@Transactional(timeout = 30, propagation = Propagation.REQUIRES_NEW)