简体   繁体   中英

JPA/hibernate: ignored persist after named query

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM