persistence@glassfish.java.net

Should the foreign key be set automatically when an element is added to a Collection?

From: Ellen Kraffmiller <ekraffmiller_at_hmdc.harvard.edu>
Date: Thu, 31 Aug 2006 10:31:26 -0400

Hi,
I have two Entities with a OneToMany relationship. When I deploy the
Entities, the correct foreign key relationship is generated in the
"many" side of the relationship. (Although the generated schema does
not define the foreign key column as required.)
When I add an element to the in the collection in the owning object, the
foreign key of the owning object is not set in the dependent object. Is
this the correct behavior?

Here are the details of the two entities:

@Entity
public class Study {
 @Id
    private Long id;
 @OneToMany (mappedBy="study", cascade={CascadeType.REMOVE})
    private java.util.Collection<StudyAuthor> studyAuthors;
 ...getters and setters ...
}

@Entity
public class StudyAuthor {
    @Id
    private Long id;
    private String value;
    @ManyToOne
    private Study study;
 ...getters and setters ...
}

Here is my code which adds a StudyAuthor to the collection in Study (I
have defined cascade-persist for the persistence unit):

       Study study = new Study();
       StudyAuthor sa = new StudyAuthor();
        sa.setValue(getAuthor());
        study.setStudyAuthors(new ArrayList<StudyAuthor>());
        study.getStudyAuthors().add(sa);
          em.persist(study);

The two entities are both saved in the database, but the foreign key in
studyAuthor is not generated unless I specifically set it
by adding sa.setStudy(study) before persisting. This seems like
something the persistence layer should be doing for me.

Thanks,
Ellen