在使用JTA时,在调用另一个EJB中的函数之前提交事务

问题描述 投票:0回答:1

@Stateless(name =“A”)公共类A {

    @PersistenceContext
    private EntityManager entityManager;

    @EJB
    private B serviceB;

    public void doSomeProcessA(List<AnyEntity> entities) {
        for (AnyEntity entity: entities) {
            //do some process.
            entityManager.persist(entity);
            serviceB.b(entity.getPrimaryKey());
        }

    }
}

@Stateless(name = B)
public class B {
    @PersistenceContext
    private EntityManager entityManager;

    @Resource
    private SessionContext sessionContext;

    public void b (String id) {
        AnyEntity entity = entityManager.find(AnyEntity.class, id);

        try {
            //do some process

            entityManager.merge(entity);
        } catch (Exception e) {
            sessionContext.setRollbackOnly();
        }
    }
}

这是我的情景。我想先坚持实体。并在b函数中对实体进行一些其他更改。如果发生任何异常,我想进行实体的事务回滚更新,但我想保留持久化实体。

如果我使用此代码作为示例,如果发生任何异常,则不提交持久化实体。如果我在函数上使用@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW),则进程未在服务A上完成,事务未被编译并写入db,我无法在服务B上到达实体。我不能将b更改为b(AnyEntity实体)因为我们使用的业务逻辑。我该怎么做才能解决这个问题。

hibernate ejb jta
1个回答
0
投票

你试过了吗?

 @Stateless(name = "A") 
 @TransactionManagement(TransactionManagementType.BEAN)
 public class A {

    @PersistenceContext
    private EntityManager entityManager;

    @Resource
    private UserTransaction transaction;

    @EJB
    private B serviceB;

    public void doSomeProcessA(List<AnyEntity> entities) {
        for (AnyEntity entity: entities) {
          try {
            //do some process.
            transaction.begin();

            entityManager.persist(entity);

            transaction.commit();

            serviceB.b(entity.getPrimaryKey());
         } catch (Exception e) {
           try {
             this.transaction.rollback();
               } catch (IllegalStateException | SecurityException
                       | SystemException e1) {
                e1.printStackTrace();
            }
        }

    }
}

@Stateless(name = B)
public class B {
    @PersistenceContext
    private EntityManager entityManager;    

    @Transactional(value = Transactional.TxType.REQUIRES_NEW, rollbackOn = Exception.class)
    public void b (String id) {
        AnyEntity entity = entityManager.find(AnyEntity.class, id);
        //do some process    
        entityManager.merge(entity);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.