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

后端 未结 15 1704
说谎
说谎 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:34

    persist(entity) should be used with totally new entities, to add them to DB (if entity already exists in DB there will be EntityExistsException throw).

    merge(entity) should be used, to put entity back to persistence context if the entity was detached and was changed.

    Probably persist is generating INSERT sql statement and merge UPDATE sql statement (but i'm not sure).

提交回复
热议问题