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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With