Richard G
Richard G

Reputation: 5683

Transactions JPA and setting values

This isn't an issue per say, but I noticed something strange in my code when I do this:

  1. Load an object.
  2. Merge the values into that object.
  3. Don't save it explicitly - so at this point I've only called setter methods on the object that was loaded from the repository,and set the new values.
  4. Issue a query that would otherwise match the new value.

Then I noticed the object is actually returned as a match on the query, even though by my reckoning the new value shouldn't have been persisted yet until I call save.

Environment is Spring JPA with Hibernate.

Can anyone explain why the object would match the query condition even though the new values haven't been persisted? Is calling a setter considered an update to the object?

(note I debugged and the object definitely doesn't match the criteria query before the values are merged, and I've triple checked, there is no other call to save the object, just setters.

Richard.

Upvotes: 0

Views: 89

Answers (1)

JB Nizet
JB Nizet

Reputation: 691785

even though by my reckoning the new value shouldn't have been persisted yet until I call save

That's where you're wrong. JPA automatically persists all the changes made to managed entities. You don't need to ever call save() or merge() or anything to have the state of managed entities persistent.

JPA watches the state of these entities and, when it needs to be flushed, the modified state is transparently written to the database. This automatic flush happens before the transaction is committed or, as you just saw, before a query is executed, to make sure that the query takes into account the previous changes made on the entities.

Upvotes: 2

Related Questions