首页 > 解决方案 > Hibernate 和 EJB:如何正确使用 @TransactionAttribute(value = TransactionAttributeType.REQUIRES_NEW)?

问题描述

我有以下代码,我希望在方法中保留全部或不entities保留。

然而,有些entities是被创建的,而另一些不是 - 即整体transaction没有被回滚。

为什么会这样?

注意 - 我正在将我的代码作为服务器中的EAR文件运行JBOSS EAP

  @TransactionAttribute(value = TransactionAttributeType.REQUIRES_NEW)
  public void createCompanyStatuses(String client, CompanyStatusPostDTO companyStatusPostDTO) {
    
            EntityManager entityManager = null;
    
            try {
    
                CompanyStatus companyStatus = new CompanyStatus();
                companyStatus.setCompanyLabel(candidateMaskedStatusPostDTO.getCompanyLabel());
    
                entityManager = entityManagement.createEntityManager(client);
                entityManager.persist(companyStatus);
    
                for(Integer employeeStatusId: companyStatusPostDTO.getEmployeeStatuses()){
    
                    CompanyStatusEmployeeStatus companyStatusEmployeeStatus = new CompanyStatusEmployeeStatus();
                    companyStatusEmployeeStatus.setEmployeeId(employeeStatusId);
                    companyStatusEmployeeStatus.setCompanyId(companyStatus.getCompanyId()); //todo - how will get this?
                    entityManager.persist(CompanyStatusEmployeeStatus);
                }
    
            } catch(Exception e){
                log.error("An exception has occurred in inserting data into the table" + e.getMessage(), e);
            } finally {
                entityManagement.closeEntityManager(client, entityManager);
            }
    }

标签: javamysqlhibernatejbosstransactions

解决方案


答案对 有效Hibernate

TransactionAttributeType.REQUIRES_NEW不支持。

很难在 java 对象上实现回滚。想象一下场景:

  1. 交易开始
  2. 创建并保存对象
  3. 子事务开始
  4. 对象已修改
  5. 子事务回滚。

您希望对象处于子事务开始之前的状态,因此您需要跟踪有关在子事务中修改该对象的信息以及回滚这些修改的能力。

或者,您可以从 DB 重新加载状态,但您需要跟踪哪个对象属于哪个事务。

我假设开发人员只是认为这是太多的努力而收效甚微。


推荐阅读