Hi Ellen,
The JPA specification requires that the application maintain all
relationships.
In your example, your call to sa.setStudy(study) is the correct way to
maintain that relationship.
Thanks,
Tom
Ellen Kraffmiller wrote:
>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
>
>
--
Tom Ware
Principal Software Engineer
Oracle Canada Inc.
Direct: (613) 783-4598
Email: tom.ware_at_oracle.com