2

hi i'm updating parent entity (Department) which has some child(Employees) ,along with update i want to delete all child and add new set of child . and i have unique constraint for EMPLOYEE_NAME by DB side . first i'm finding department and calling clear (collection clear ) for list of employees then adding new child to that department and committing . But i'm getting unique constraint violation .if i use em.flush() after clear() it is deleting child and inserting new child . But as i know Flush() is an exceptional use, commit also uses flush() internally . is there any solution to delete and insert child in a single transaction ?? and i'm using orphanremoval = true in department entity

public void deleteEmployee(Department updatingDepartment){
    List<Employee> employees = new ArrayList<Employee>();
    Employee employee1 = new Employee();
    employee1.setEmployeeAlary(16667);
    employee1.setEmployeeName("manju");


    Employee employee2 = new Employee();
    employee2.setEmployeeAlary(16667);
    employee2.setEmployeeName("SUNIL");



    entityManager.getTransaction().begin();

    Department foundDepartment = entityManager.find(Department.class, updatingDepartment.getDepartmentId());

    foundDepartment.getEmployees().clear();




      employee2.setDepartment(foundDepartment);
        employee1.setDepartment(foundDepartment);
        employees.add(employee1);
        employees.add(employee2);



        /*entityManager.flush();*/
        foundDepartment.getEmployees().add(employee1);
        foundDepartment.getEmployees().add(employee2);

        entityManager.merge(foundDepartment);

    entityManager.getTransaction().commit();

}
manjunath
  • 31
  • 4

1 Answers1

0

First of all you don't need to merge your entity as it is still in attached state (retrieved fron an entityManager which is not disposed yet). See entity life cycle.

You need to understand what's exactly is the merge function JPA EntityManager: Why use persist() over merge()?

In fact here you have nothing to do except commiting and closing the em, changes will be automatically reported.

Then, the orphanremoval feature is the one to use in your case (remove child entities when they are removed from parent collection) so it should do the trick.

Concerning the 'flush() / clear()' right use case, it's mainly when you're processing batch operation on lot's of entities and don't want them to stay in level 1 cache (entityManager one) in order to limit memory consumption.

You can also have a look to this : Struggling to understand EntityManager proper use

Community
  • 1
  • 1
Gab
  • 7,869
  • 4
  • 37
  • 68
  • thanks a lot for your information . But my example is not batch operation , with out flush i cant achieve my requirement (Unique constraint violation exception ) , without flush is not possible to achieve? – manjunath Apr 24 '15 at 12:02