I am using Hibernate and have (as an example) an Employee
entity with 10000 entries. Let's assume 1000 of them have a salary of 4000 which I want to increase to 5000. I have difficulties to find an effective way to do this.
Doing it in code by getting all employees and updating the relevant entries seems ineffective, slow and also seems to cause "Batch update returned unexpected row count from update" errors in some situations.
So it seems to be better to use a native query as suggested here, but then you need to update the Hibernate cache to see the changes on the next request:
Employee e = em.find(Employee.class, <id ???>);
em.flush();
em.detach(e);
em.createNativeQuery("UPDATE employee SET salery = 5000 where salery = 4000")
.executeUpdate();
However, what I do not understand is how to detach the entities before issuing the native update query. The second argument to the em.find
call seems to be the id of a single entity? But the Emloyees
are used all over the whole application so how should I know which ones to detach? Is there a way to detach all (e.g. something like em.detachAll(Employee.class)) or am I supposed to iterate over all 1000 enployees in a loop and detach them individually?
I am also open for other solutions solving my initial problem.