Reputation: 44114
em.getTransaction().begin();
StringData sd = em.find(StringData.class, key);
System.out.println("Old value: " + sd.getData());
sd.setData(newValue);
// em.persist(sd);
em.getTransaction().commit();
As you can see, I'm not calling persist
, it's commented out, because I'm dry running this code first. However, as it turns out it's not so very dry. Upon inspecting the database, I see the data is changed (fortunately it's a test database).
Apparently my understanding of Hibernate/JPA is flawed. Isn't calling persist
always required to change data? And if not, what are the rules on when something is saved?
Upvotes: 9
Views: 5228
Reputation: 3673
Yes, when a flush (flush are also done with a commit) is done managed entities are saved if any change is detected on that entity, it's called dirty checking.
Upvotes: 11
Reputation: 9182
The accepted answer is slightly misleading. Managed entities are saved automatically on flush but flush is not issued "if any change is detected". This is misleading as it implies that flush happens on any change instantly.
Instead, with the default AUTO flush mode, a flush is triggered on very specific conditions.
Example 1 - If you interleave a native SQL within your transaction.
Example 2 - If you write a JPQL/HQL query that overlaps with cache.
Example 3 - If you exit the transaction normally.
My point is that it's not an immediate flush but rather triggered only when certain conditions are met. This is subtle but important distinction.
Reference - https://docs.jboss.org/hibernate/orm/5.1/userguide/html_single/chapters/flushing/Flushing.html
Upvotes: 0
Reputation: 47300
StringData sd = em.find(StringData.class, key);
That line of code retrieves the StringData instance sd from the em session, any changes you make will be saved on flush (when transactions ends) because the object instance is associated with the em session (ie managed).
You could detach it, or return it from the method. Outside of the transaction it is not associated with em session and changes will not be persisted until it is re-attached via merge.
Upvotes: 4