当我在事务 (TransactionAttributeType.REQUIRED) 方法中保存一个新实体时,createEntities
这些实体在事务完成之前被立即存储在数据库中。我希望在 createEntities 方法完成时事务已完成并且更改会传播到 DB,但是如果我在 syso 行中调试并暂停执行,我可以在外部应用程序(例如 Toad)中看到 DB 中的更改。
我的猜测是错误的还是我配置的方法错误?
我的代码如下所示:
@Stateless
public class MyClass {
@Inject
private MyService myService;
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public void aMethod() {
// don't want a transaction because this method does a lot of calculations
// and lasts a lot of time resulting in transaction timeout otherway
createEntities();
}
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void createEntities() {
myService.createEntity(new MyEntity(1, "111"));
System.out.println("Paused execution, checked DB and saw the entity was already inserted");
myService.createEntity(new MyEntity(2, "222"));
System.out.println("Paused execution, checked DB and saw the entity was already inserted");
}
}
@Stateless
public class MyService {
@PersistenceContext
private EntityManager em;
public void createEntity(MyEntity entity) {
em.merge(entity);
}
}
在@TransactionAttribute
只有当该方法是从另一个bean称为工作。
如果您aMethod()
从某个其他 Bean 调用,该调用将被拦截以挂起最终处于活动状态的事务。
然后createEntities()
在没有事务活动的情况下调用 then ,但不会拦截此调用,因为它是从 MyClass-Bean 内部调用的。
因此不会启动任何事务。
本createEntity()
-方法没有被标注,因此具有TransactionAttribute.Required
积极的。
因为这个方法不是从同一个 Bean 调用的,并且没有事务处于活动状态,容器将启动一个新的。此事务在方法结束时提交。
更多关于容器管理的交易:https ://docs.oracle.com/javaee/6/tutorial/doc/bncij.html
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句