Issue
I'm trying to learn about JPA
and Hibernate
and I was trying to learn about some database terms.
In a video on youtube, the teacher (at 2:42) said:
One-To-Many is only Unidirectional.
and she said suppose thsese two class:
class Person {
List<Address> addresses;
}
class Address {
Person p;
}
and she said:
this is One-To-Many. but Address cannot have a collection of Person because if it has a collection of Person, it's going to be Many-To-Many.
but I think she is not right, because we can have these two:
thePerson.getAddresses().get(i);
and
anAddress.getPerson();
When we can have these two statements, then it is Bidirectional. Then why she said it can be just Unidirectional?
What is Bidirectional's exact definition with which she came to such a conclusion?
Solution
First of all, any relationship can be unidirectional or bidirectional, it's all depend on how you want to display or retrieve your data, and your business rules.
When we can have these two statements, then it is Bidirectional. Then why she said it can be just Unidirectional?
There is also a big mismatch between the object oriented
approach of ORMs
like Hibernate
and how tables and relationships are defined in a relational database
. She can be wright, because, in the point of view of a database, relationships are by default unidirectional.
The difference between unidirectional and bidirectional is defined by the fact that you can access the records of the other side of your relationship from where you are.
What is Bidirectional's exact definition with which she came to such a conclusion?
In your example we can interpret your relationship like this:
Unidirectional: you can get all your addresses from person, but not the inverse
class Person { @OneToMany List<Address> addresses; } class Address { // Here you don't add the ManyToOne Person p; }
Bidirectional: you can get all your addresses from person and get a person from an address
class Person { @OneToMany List<Address> addresses; } class Address { @ManyToOne Person p; }
Take a look at those links below:
Difference between unidirectional and bidirectional relational relationship
https://www.baeldung.com/spring-data-rest-relationships
What is Object/Relational mismatch
Answered By - Harry Coder
Answer Checked By - Candace Johnson (JavaFixing Volunteer)