How to achive nestsed transaction in CUBA ?

Hi
We have some custom screens that are created with multiple entities. We are having a service class to store the data. We want to store one entity and also want to use the generated ID(Long value) of the stored entity second entity.
For example We have one Department Entity and an Employee Entity. In one page we are creating the department object and in the next page we are creating the employee. we want to store the department id in employee and it should store the department only if it is storing the employee(Nested Transaction and Rollback).

The methods in service is like below.

   
    private void saveEmployee(Employee employee,Department department){
        try (Transaction tx = persistence.createTransaction()) {
            EntityManager em = persistence.getEntityManager();
            saveDepartment(department)
            employee.setDepartmentId(department.getId());
            em.persist(employee);
            tx.commit();
        }
    }

    private void saveDepartment(Department department){
        try (Transaction tx = persistence.getTransaction()) {
            EntityManager em = persistence.getEntityManager();
            em.persist(department);
            tx.commit();
        }
    }

Kindly suggest how to implement this.

Thanks,
Saumm

1 Like

Hi Saumm,

First of all, if your Department is inherited from BaseLongIdEntity, it will have an identifier value right after the creation of an instance in memory, so you don’t have to wait until Department is committed to the database to assign its identifier to Employee. BTW, why do you use identifier value and not just a reference to Department?

Second, why do you need nested transactions here, saving Department and Employee in one transaction results in exactly this - Department will be saved only if Employee was saved before?