users@glassfish.java.net

JPA - One to Many persistence issue

From: <glassfish_at_javadesktop.org>
Date: Tue, 13 Oct 2009 10:01:52 PDT

Hi All,

We are facing an issue with one to many relationship persistence using JPA.

We have a one to many relationship between Company and Personnel. When A personnel is created, the company(the parent in the relationship) is selected and that needs to be persisted along with the new Personnel Entity

Find below the Entity Definitions and the code snippet to persist the Entity into the database.

Entity - Company:
@OneToMany(mappedBy = "company", cascade=CascadeType.ALL, fetch = javax.persistence.FetchType.EAGER)
private Collection<Personnel> personnelCollection;

Entity Personnel:

@ManyToOne(optional = true)
private Company company;

public ErrorCode createAndAssignPersonnel(String personnelName, String company, String email, String title, String user)
{
PersonnelPK personnelPK = new PersonnelPK(personnelName, this.appInfoEJB.getSiteId());
Personnel personnel = new Personnel(personnelPK);
personnel.setEmail(email);
personnel.setTitle(title);

CompanyPK companyPK = new CompanyPK(company, this.appInfoEJB.getSiteId());
Company companyObj = this.companyEJB.find(companyPK);

//Double Wiring the personnel and company records
companyObj.getPersonnelCollection().add(personnel);
personnel.setCompany(companyObj);

//Running merge on the parent entity
em.merge(companyObj);

return ErrorCode.OK;
}

The personnel entity is being persisted into the database but the company is not getting associated with it. (The company value remains blank)

We are using the Toplink JPA Implementation with Glassfish application server. Any pointers would be greatly appreciated.

Thanks and Regards,
GK
[Message sent by forum member 'gkari' (gurpreet.ari_at_higtek.com)]

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