当我在事务(TransactionAttributeType.REQUIRED)方法createEntities
中保存一个新实体时,这些实体在事务完成之前立即存储在DB中。我期望当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);
}
}
只有当方法从另一个Bean调用时,@TransactionAttribute
才工作。
如果您从其他Bean调用aMethod()
,该调用将被拦截以挂起最终激活的事务。
然后在没有事务活动的情况下调用createEntities()
,但是这个调用不会被拦截,因为它是从MyClass-Bean内部调用的。
因此不会启动任何事务。createEntity()
-方法没有注释,因此TransactionAttribute.Required
处于活动状态。
因为这个方法不是从同一个Bean调用的,而且没有活动的事务,所以容器将启动一个新的事务。此事务在方法结束时提交。
更多关于容器管理事务的信息:https://docs.oracle.com/javaee/6/tutorial/doc/bncij.html