users@glassfish.java.net

persist() and merge() and queries: what affects persistence context?

From: <glassfish_at_javadesktop.org>
Date: Tue, 17 Jun 2008 08:56:40 PDT

I am still humbly thick and slow when it comes to figuring out just when to call merge() vs. persist().

I am working with detached entities in an EJB3 application.

The cycle that is giving me trouble goes like this:
1. EntityManager runs a SELECT query like this: SELECT p FROM Person p
2. These objects/entities get shipped over the wire to my fat client.
3. The fat client navigates around, etc.
4. The fat client ultimately selects one such entity, and calls a stateless session bean that, on its behalf, asks the EntityManager to "save" the (quite possibly modified) entity.
5. Laird gets confused. First, Laird tries to see if the entityManager already knows about the entity via a contains() call. The entityManager says no, never seen this item before, even though the entity manager is the one who saved it many moons ago, and, more relevantly, is the one who just loaded it up as a result of the query.
6. So Laird's persist() statement fires instead of the merge() statement, and Laird's code blows up, because of course the Person entity in question [i]has[/i] been persisted before with its current ID, so an EntityExistsException is thrown.

So that tells me that entities returned by a query are not placed into the persistence context on their way "out". I suppose this makes sense.

But [i]that[/i] tells me that I shouldn't decide whether to call persist() or merge() based on an EntityManager#contains() call, because the entity in question I'm asking the entityManager about could simply be a persistent entity that for whatever reason just isn't in the EntityManager's persistence context yet.

And [i]that[/i] makes me wonder: what is the best failsafe way to ask the entityManager if it has ever seen a detached entity before? Or is the best approach to try to slam a persist() home, catch the exception, and then try a merge() (ick, yuck, I hope not)?

Thanks,
Laird
[Message sent by forum member 'ljnelson' (ljnelson)]

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