users@glassfish.java.net

Re: how to persist a new entity that refers to already existing entity

From: gufiya <gufiya_at_hotmail.com>
Date: Sun, 1 Mar 2009 06:29:29 -0800 (PST)

Thanks for the answers.
Indeed, merge() sounds better than explicit find() operation.
But still, doesn't it mean an additional access to the database?
One underlying query for merge() and another for persist()?



gufiya wrote:
>
> Hello,
>
> I'm new to JPA and I have a question that might be basic but I coulnd't
> find an obvious solution.
>
> I have two classes - employee and department, while employee refers to
> department with many-to-one unidirectional relationship.
>
> Suppose I have a remote interface that allows me to add new employees:
>
> public void newEmployee(Employee emp) {
> myEntityManager.persist(emp);
> }
>
> Note that I have a field in "emp" that refers to some "Department" object.
> Since the department object is detached, and I'm not using cascading, I
> get the error "During synchronization a new object was found through a
> relationship that was not marked cascade PERSIST".
>
> As I understand, I have two possible solutions here:
> 1) add persist-cascading - I'm not sure this will help because the
> department object is already in database and should not be persisted
> again.
> 2) find the department object before calling persist, update "emp" so it
> will refer to this reference, and only then persisting emp. This sounds
> pretty ugly, not mentioning the fact that now I need 2 queires against the
> database instead of 1.
>
> Am I missing something here? I thought it a very simple usecase but still
> I couldn't find a clean solution.
>
> Thanks for helpers!
>
>

-- 
View this message in context: http://www.nabble.com/how-to-persist-a-new-entity-that-refers-to-already-existing-entity-tp22271066p22273527.html
Sent from the java.net - glassfish users mailing list archive at Nabble.com.