hibernate - In JPA , Is em.flush() is exceptional usage or not -
hi i'm updating parent entity (department) has child(employees) ,along update want delete child , add new set of child . , have unique constraint employee_name db side . first i'm finding department , calling clear (collection clear ) list of employees adding new child department , committing . i'm getting unique constraint violation .if use em.flush() after clear() deleting child , inserting new child . know flush() exceptional use, commit uses flush() internally . there solution delete , insert child in single transaction ?? , 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(); }
first of don't need merge entity still in attached state (retrieved fron entitymanager not disposed yet). see entity life cycle.
you need understand what's merge
function jpa entitymanager: why use persist() on merge()?
in fact here have nothing except commiting , closing em, changes automatically reported.
then, orphanremoval feature 1 use in case (remove child entities when removed parent collection) should trick.
concerning 'flush() / clear()' right use case, it's when you're processing batch operation on lot's of entities , don't want them stay in level 1 cache (entitymanager one) in order limit memory consumption.
you can have : struggling understand entitymanager proper use