users@glassfish.java.net

Re: JPA - why persist and merge, why not a sigle save

From: <glassfish_at_javadesktop.org>
Date: Mon, 23 Jul 2007 06:18:04 PDT

I believe there are two methods because there are two different ways of working with an EntityManager. One way is to make all changes to the objects while the EntityManager is open (while the objects are in a managed state). The other way is to load your objects in one EntityManager, close the EntityManager, make changes to the objects, then merge these changes into the managed objects of a second open EntityManager (objects that are in a detached state).

I have used the EntityManager both of these ways in an application. The first was used for batch processing. The second was used for interaction with the user.

When used the first way, there is no method that needs to be called on a managed object to have its changes persisted when commit is called. This happens automatically (see http://www.hibernate.org/hib_docs/entitymanager/reference/en/html_single/#d0e868). However, the EntityManager cannot know anything about the new objects to be persisted. Hence you must explicitly tell the EntityManager of new objects that you want to have managed by calling persist on them (in much the same way that you call delete on objects you want deleted).

When used the second way merge is used for both new and detached objects (see http://www.hibernate.org/hib_docs/entitymanager/reference/en/html_single/#d0e902).

Hibernate's documentation gives a little more detail on the subject. Have a look at http://www.hibernate.org/hib_docs/entitymanager/reference/en/html_single/#objectstate
[Message sent by forum member 'simon_t' (simon_t)]

http://forums.java.net/jive/thread.jspa?messageID=227688