Hello,
I have a question about one-to-many bidirectional relationships and their inverse many-to-one. I am using Spring JPARespository to make all my DB calls.
I have the following two classes.
Code:
@Entity
public class Member {
@Id
@GeneratedValue
private Long id
@ManyToOne(cascade = CascadeType.MERGE, optional = false, fetch = FetchType.EAGER)
private OrgUnit orgUnit;
public OrgUnit getOrg() {
return orgUnit;
}
public void setOrg(OrgUnit orgUnit) {
this.orgUnit = orgUnit;
}
}
Code:
@Entity
public class OrgUnit{
@Id
@GeneratedValue
private Long id
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<Member> members = new HashSet<Member>();
public Set<Member> getMembers() {
return members;
}
public void addMember(Member member) {
this.members.add(member);
member.setOrg(this);
}
}
Now, I can add a member to an Org Unit by calling the OrgUnit.addMember(Member) method. If I save that, the relationship in the DB holds. However, if I do the inverse, and assign an Org Unit to a member, the member is never added to the Org Unit's member list.
Do I have to explicitly maintain these relationships like I have in the Org Unit class (Where I set the Member's org unit to be 'this' and add it to the Member collection) or should that be maintained by the DB for me?
Thank you for any help.