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

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

    Another observation:

    merge() will only care about an auto-generated id(tested on IDENTITY and SEQUENCE) when a record with such an id already exists in your table. In that case merge() will try to update the record. If, however, an id is absent or is not matching any existing records, merge() will completely ignore it and ask a db to allocate a new one. This is sometimes a source of a lot of bugs. Do not use merge() to force an id for a new record.

    persist() on the other hand will never let you even pass an id to it. It will fail immediately. In my case, it's:

    Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist

    hibernate-jpa javadoc has a hint:

    Throws: javax.persistence.EntityExistsException - if the entity already exists. (If the entity already exists, the EntityExistsException may be thrown when the persist operation is invoked, or the EntityExistsException or another PersistenceException may be thrown at flush or commit time.)

提交回复
热议问题