Reputation: 36
Following java code:
fooDAO.resetField(); // ...namedQuery
foo.setField(true);
fooDAO.persist(foo);
foo.field
is a boolean attribute.
resetField()
executes a named query that sets the field to FALSE in all db rows.
If foo.field
is initially FALSE, hibernate executes 2 SQL queries, ie. the named query and the update query of the setField/persist combo.
But if foo.field
is initially TRUE, just the first SQL query gets executed that sets the field to FALSE in all rows, the 2nd SQL query gets ignored!? ...why?
Upvotes: 0
Views: 171
Reputation: 3956
Let me quote authors of ProJPA 2 book from the chapter Using Bulk Update and Delete.
...the persistence context is not updated to reflect the results of the operation. Bulk operations are issued as SQL against the database, bypassing the in-memory structures of the persistence context.(...) The developer can rely only on entities retrieved after the bulk operation completes.(...) this means that the bulk operation should either execute in a transaction all by itself or be the first operation in the transaction
In your case I'm recommending either rearranging the code to enclose bulk update in its own transaction or calling EntityManager.refresh()
on foo
before trying to change it.
What you described is an expected behaviour because after a bulk update your foo
instance becomes stale. It exists in memory but does not reflect reality.
Upvotes: 1