EntityManager.merge()
can insert new objects and update existing ones.
Why would one want to use persist()
(which can only create new objec
The JPA specification says the following about persist()
.
If X is a detached object, the
EntityExistsException
may be thrown when the persist operation is invoked, or theEntityExistsException
or anotherPersistenceException
may be thrown at flush or commit time.
So using persist()
would be suitable when the object ought not to be a detached object. You might prefer to have the code throw the PersistenceException
so it fails fast.
Although the specification is unclear, persist()
might set the @GeneratedValue
@Id
for an object. merge()
however must have an object with the @Id
already generated.