【问题标题】:Hibernate - ensure that all entities are persisted or none?休眠 - 确保所有实体都被持久化或没有?
【发布时间】:2020-12-14 03:11:07
【问题描述】:

我有以下代码将两个不同的entities 持久化到我的MYSQL DB。

这按预期工作,但是如果一个表而不是另一个表存在问题,则一个表正在填充,而另一个则没有。

注意 - 我在 jboss EAP 服务器中将我的应用程序作为 EAR 文件运行。

我想确保两个表都已填充或没有

我该怎么做?

Persistence.xml

<persistence-unit name="entitystore" transaction-type="JTA">
    <jta-data-source>java:/jdbc/datasources/global</jta-data-source>

Java 服务类:

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);
        }
}

编辑:

我已尝试添加:

 @TransactionAttribute(value = TransactionAttributeType.REQUIRES_NEW)

但是,问题仍然存在,成功的持久化工作而不成功的不成功 - 而是全部或全部持久化。

【问题讨论】:

  • 有交易吗?
  • @Shadow 你能举个例子吗,我目前只学习hibernate

标签: java hibernate orm transactions ejb


【解决方案1】:

只需使用事务。

使用 spring 使用 @Transactional 注释。

不用spring框架也可以

doInJPA(entityManager -> {
    ...
    entityManager.persist(obj);
    ...
});

见:https://vladmihalcea.com/high-performance-java-persistence-github-repository/

【讨论】:

  • OP 已经有 EJB 和 JTA 可用。他很可能没有正确使用它们。告诉 OP 使用 Spring 而不是解释正确的方法是没有意义的。
猜你喜欢
  • 2012-01-09
  • 2020-02-14
  • 1970-01-01
  • 2013-02-17
  • 1970-01-01
  • 2010-10-29
  • 1970-01-01
  • 1970-01-01
  • 2018-09-09
相关资源
最近更新 更多