JPA EntityManager: Why use persist() over merge()?

后端 未结 15 1447
说谎
说谎 2020-11-22 03:09

EntityManager.merge() can insert new objects and update existing ones.

Why would one want to use persist() (which can only create new objec

15条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 03:42

    There are some more differences between merge and persist (I will enumerate again those already posted here):

    D1. merge does not make the passed entity managed, but rather returns another instance that is managed. persist on the other side will make the passed entity managed:

    //MERGE: passedEntity remains unmanaged, but newEntity will be managed
    Entity newEntity = em.merge(passedEntity);
    
    //PERSIST: passedEntity will be managed after this
    em.persist(passedEntity);
    

    D2. If you remove an entity and then decide to persist the entity back, you may do that only with persist(), because merge will throw an IllegalArgumentException.

    D3. If you decided to take care manually of your IDs (e.g by using UUIDs), then a merge operation will trigger subsequent SELECT queries in order to look for existent entities with that ID, while persist may not need those queries.

    D4. There are cases when you simply do not trust the code that calls your code, and in order to make sure that no data is updated, but rather is inserted, you must use persist.

提交回复
热议问题