java12399900
java12399900

Reputation: 1671

Hibernate - ensure that all entities are persisted or none?

I have the following code to persist two different entities to my MYSQL DB.

This works as expected, however if there is an issue with one table and not the other then one table is getting populated, and the other not.

Note - I am running my application as an EAR file within a jboss EAP server.

I want to ensure that either both tables are populated or none.

How can I do so?

Persistence.xml

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

Java service class:

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

Edit:

I have tried adding:

 @TransactionAttribute(value = TransactionAttributeType.REQUIRES_NEW)

However, the issue still remains that the successful persists work and the non-successful don't - rather that all or nothing being persisted.

Upvotes: 0

Views: 173

Answers (1)

Maneki
Maneki

Reputation: 357

Simply use a transaction.

With spring use the @Transactional annotation.

Without spring framework, you can do

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

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

Upvotes: 1

Related Questions