Home > Back-end >  How to obtain the bi-directional entity
How to obtain the bi-directional entity

Time:01-03

Let's say we have two entities, EntityA and EntityB, and those entities are bidirectional. How we should obtain entityB? Does it make sense to add a new method to the repository like findAllByEntityA() or we may use getEntitiesA() getter?

CodePudding user response:

You could add a new spring repo method, or simply use a @Getter annotation, or implement your own getter method.

You could do findAllByEntityA() as a way of fetching EntityB if you expect to have a List<EntityB> returned. On the other hand, I would expect based on the naming convention that getEntitiesA() would be for fetching a List<EntityA> & not for B's.

It really depends on your bi-directional relationship but, basically all of the jpa one-to-one, one-to-many, many-to-one, many-to-many mappings simply boil down to foreign key constraints.

CodePudding user response:

as turbofood already said. There are differet kinds of mappings:

  1. One-to-One mappings. Like a Driver and a Car: One car can only be driven by one Driver and one Driver can only drive one Car.
  2. Many-To-One mappings: Like a father and a child, one Father can have multiple children but one children can only have one father.
  3. Many-To-Many mappings: Like student and teacher. A student can have multiple teachers and one teacher can have multiple students.

For One-To-One-Mappings and for Many-To-One mappings you have exactly one foreign-key. But for Many-To-Many-Mappings you have two foreign-keys that are part of a db-relation-table (that must not have a jpa-entity).

Using JPA/Hibernate we differenciate the endpoints between relations into two kinds: The owning-Side (getter and setter) and the non-owning side (getter and setter).

For many-to-many-relations this is the owning-side:

@OrderBy
@ManyToMany
@JoinTable(name="`STUDENT_TO_TEACHER`", joinColumns = {
  @JoinColumn(name="`student_id`", referencedColumnName="`id`", nullable=false),
}, inverseJoinColumns = {
  @JoinColumn(name="`teacher_id`", referencedColumnName="`id`", nullable=false)
})
public Set<Student> getStudents() {
  return this.students;
}

And the non-owning-side:

@ManyToMany(mappedBy="students")
public Set<Teacher> getTeachers() {
  return teachers;
}

Now why owning-side and non-owning side is important:

Student student = ...
Teacher teacher = ...

// a bad example:
student.getTeachers().add(teacher); // STUDENT.TEACHERS IS NOT THE OWNING SIDE
entityManager.persist(student); // THIS IS NOT POSSIBLE!

// a good example
teacher.getStudents().add(student); // good
entityManager.persist(teacher); // possible, teacher have a new student.

There is another rare case of mapping beside this 1-1/n-m/1-n sides the Map<> association. The Map<> association let you use a map as a getter in hibernate. I never used it so I can not elaborate experience in this.

  • Related