Does JPA / Hibernate save, even if not invoked

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 am not calling persist , this is commented out because I run this code first. However, as it turned out, this is not so dry. After checking the database, I see that the data has changed (fortunately, this is a test database).

My understanding of Hibernate / JPA seems to be erroneous. Does persist require data to be modified? And if not, what are the rules when something is saved?

+6
source share
2 answers

Yes, managed objects are saved when a flash (the flash is also executed with a commit) is executed, if any change is detected, it is called a dirty check.

+9
source
 StringData sd = em.find(StringData.class, key); 

This line of code retrieves the sd StringData instance from the em session, any changes you make will be saved to the flash (when the transactions are completed), because the object instance is associated with the em session (i.e., it is managed).

You can detach it or return it from a method. Outside of the transaction, it is not associated with an em session, and the changes will not be saved until it is reattached via merge.

+2
source

Source: https://habr.com/ru/post/907964/


All Articles