简体   繁体   中英

Is version checked when we delete an entity in hibernate?

I believed that version was checked on deleting an entity. But i have just read that..

In JPA, You have to merge the detached instance first and then remove the merged object (or, alternatively, get a reference with the same identifier, and remove that).

Am confused with alternative approach suggested by Gavin King in his book on Hibernate

item1.setName("iphone")// this is a detached object

EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();

// this will give a proxy as we don't have any instance with this ID in
// persistence context. Now if this is a proxy it doesn't have any version.
// How hibernate decides whether to delete such an object or not.    
Item item2 = em.getReference(Item.class, item1.getId());
em.remove(item2);

tx.commit();
em.close();

If above is allowed, does it mean version is not checked in case of delete ?

For deleting an object, Hibernate requires that the object is in persistent state. Thus, Hibernate first fetches the object (SELECT) and then removes it (DELETE).

After some more digging... I agree with Zealous, that an object has to be loaded into the persistence context to be removed (a proxy is also good enough). The reason is : You may have Hibernate interceptors enabled, and the object must be passed through these interceptors to complete its life-cycle. If you delete rows in the database directly, the interceptor won't run.

And to answer my question it has 2 options:

  1. If object to be deleted is an uninitialized proxy, it will be deleted without version check, because proxy itself means we never verified or accessed, hence it is safe to delete.
  2. If object was a detached object, it will be first merged and brought in persistence context. Now when delete is called version will be checked and if entity is found to be stale, exception will be thrown.

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