【问题标题】:JPA transaction stores insertions inmediatly in DataBaseJPA 事务将插入立即存储在数据库中
【发布时间】:2021-08-30 08:54:34
【问题描述】:

当我在事务 (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);
    }
}

【问题讨论】:

    标签: java transactions jta


    【解决方案1】:

    @TransactionAttribute 仅在从另一个 Bean 调用方法时才有效。
    如果您从某个其他 Bean 调用 aMethod(),该调用将被拦截以挂起最终处于活动状态的事务。
    然后createEntities() 在没有事务活动的情况下被调用,但是这个调用不会被拦截,因为它是从 MyClass-Bean 内部调用的。
    因此不会启动任何事务。
    createEntity()-Method 没有注释,因此 TransactionAttribute.Required 处于活动状态。
    而且因为这个方法不是从同一个 Bean 调用的,并且没有事务处于活动状态,容器将启动一个新的。此事务在方法结束时提交。

    有关容器管理事务的更多信息:https://docs.oracle.com/javaee/6/tutorial/doc/bncij.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-01
      相关资源
      最近更新 更多