Even though my question is worded specifically to the way Entity relationships are depicted in the Play framework, which uses Hibernate, I am sure this is a general concept.
When we have a one-to-many relationship, we are always asked to specify the owning side.
So, for example if we had a one-to-many relationship between Person and PhoneNumber, we would write code like this.
@Entity
class Person {
@OneToMany(mappedBy="person")
public Set<PhoneNumber> phoneNumbers;
}
@Entity
class PhoneNumber {
@ManyToOne
public Person person;
}
In the code above, the owning Entity is PhoneNumber. What are the pros and cons of either side being the owning entity ?
I realize when the owning entity is PhoneNUmber, the relationship represented is ManyToOne, which will not result in a join table, whereas when the owning side is Person, the relationship depicted would be OneToMany, in which case a relationship table will be created.
Is this the main reason for determining the owning side, or are there other reasons as well ?
Update: I just realized that this thread provides part of the answer, but I am hoping there may be other points as well.
The many side is always the owning side of the relationship. For one-to-one bidirectional relationships, the owning side corresponds to the side that contains the corresponding foreign key. For many-to-many bidirectional relationships, either side may be the owning side.
The inverse side has to have the mappedBy attribute of the OneToOne, OneToMany, or ManyToMany mapping declaration. The mappedBy attribute contains the name of the association-field on the owning side. The owning side has to have the inversedBy attribute of the OneToOne, ManyToOne, or ManyToMany mapping declaration.
On the other hand, the mappedBy attribute is used to define the referencing side (non-owning side) of the relationship.
An important point to keep in mind is that the owning relation is the one that actually persist the relation on save. With an example:
Person person = new Person();
PhoneNumber pn = new PhoneNumber();
pn.phone = "12345678";
person.phoneNumbers.add(pn);
session.save(person);
The relation is not save infact if you reload the entity from the database you'll see no numbers. To actually add the relation you need to set the person on the owner side (PhoneNumber) and then save.
// the relation is not saved
Person loadedPerson = (Person)session.load(Person.class, person.id);
System.out.println(loadedPerson.phoneNumbers.size()); // prints 0!
pn.person = person;
session.save(pn);
loadedPerson = (Person)session.load(Person.class, person.id);
System.out.println(loadedPerson.phoneNumbers.size()); // prints 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With