users@glassfish.java.net

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

From: Wolfram Rittmeyer <w.rittmeyer_at_jsptutorial.org>
Date: Sun, 01 Mar 2009 14:00:07 +0100

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.

You could merge the department object:

public void newEmployee(Employee emp) {
    myEntityManager.merge(emp.getDepartment());
    myEntityManager.persist(emp);
}

If would have to add a null check if the department could be null.

--
Wolfram Rittmeyer
> 
> Am I missing something here? I thought it a very simple usecase but still I
> couldn't find a clean solution.
> 
> Thanks for helpers!
>