Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JPA/Hibernate save even when not calling persist

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?

like image 801
Bart van Heukelom Avatar asked Feb 08 '12 16:02

Bart van Heukelom


2 Answers

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.

like image 118
Pablo Avatar answered Oct 12 '22 22:10

Pablo


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.

like image 39
NimChimpsky Avatar answered Oct 12 '22 22:10

NimChimpsky