persistence@glassfish.java.net

Re: Why does EntityManager.merge() return a reference and persist() doesn't?

From: Wonseok Kim <guruwons_at_gmail.com>
Date: Wed, 17 Jan 2007 01:14:54 +0900

Hi Jon,

In the same Persistence Context(PC) it should maintain one managed object
for the same PK so the same object can be returned by em.find() or query. If
the object passed in merge() is detached one, there may be already the
corresponding managed one in the PC, so the managed one is returned.

But for a new object merge() does like persist() and two operations could
behave a little different depending on implementations. TopLink doesn't use
the new object which is passed in merge() directly, it makes a new managed
copy and return it internally. I don't know merge() should always return a
new managed copy for a new object, but TopLink is implemented in that way.

Cheers,
-Wonseok

On 1/13/07, Jon Miller <jemiller_at_uchicago.edu> wrote:
>
> I'm starting to get confused here. Why does merge() return a reference
> that
> is in the persistence context? Why doesn't it just use the reference that
> you pass in? I don't understand why the behavior is different for merge()
> than for persist().
>
> I've been using merge() for both adding and updating objects. I'm thinking
> that maybe I should be using persist() for adding new objects and only use
> merge() for existing objects.
>
> Jon
>