简体   繁体   中英

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?

是的,如果在该实体上检测到任何更改,则在完成刷新(也通过提交完成刷新)时保存托管实体,这称为脏检查。

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM