Relación de muchos a muchos en JPA

1. Introducción

En este tutorial, veremos varias formas de lidiar con relaciones de muchos a muchos usando JPA .

Para presentar las ideas, usaremos un modelo de estudiantes, cursos y varias relaciones entre ellos.

En aras de la simplicidad, en los ejemplos de código, solo mostraremos los atributos y la configuración de JPA que están relacionados con las relaciones de muchos a muchos.

2. Básico de varios a varios

2.1. Modelar una relación de muchos a muchos

Una relación es una conexión entre dos tipos de entidades. En el caso de una relación de varios a varios, ambos lados pueden relacionarse con múltiples instancias del otro lado.

Tenga en cuenta que es posible que los tipos de entidad tengan una relación con ellos mismos. Por ejemplo, cuando modelamos árboles genealógicos: cada nodo es una persona, por lo que si hablamos de la relación padre-hijo, ambos participantes serán una persona.

Sin embargo, no importa mucho si hablamos de una relación entre tipos de entidades únicos o múltiples. Dado que es más fácil pensar en las relaciones entre dos tipos de entidades diferentes, lo usaremos para ilustrar nuestros casos.

Por ejemplo, cuando los estudiantes marcan los cursos que les gustan: a un estudiante le pueden gustar muchos cursos y a muchos estudiantes les puede gustar el mismo curso:

Como sabemos, en RDBMS podemos crear relaciones con claves foráneas. Dado que ambos lados deberían poder hacer referencia al otro, necesitamos crear una tabla separada para contener las claves externas :

Esta tabla se llama tabla de combinación . Tenga en cuenta que en una tabla de combinación, la combinación de las claves externas será su clave primaria compuesta.

2.2. Implementación en JPA

Modelar una relación de varios a varios con los POJO es fácil. Deberíamos incluir una Colección en ambas clases , que contenga los elementos de las demás.

Después de eso, debemos marcar la clase con @Entity y la clave principal con @Id para convertirlas en entidades JPA adecuadas.

Además, debemos configurar el tipo de relación. Por lo tanto , marcamos las colecciones con anotaciones @ManyToMany :

@Entity class Student { @Id Long id; @ManyToMany Set likedCourses; // additional properties // standard constructors, getters, and setters } @Entity class Course { @Id Long id; @ManyToMany Set likes; // additional properties // standard constructors, getters, and setters }

Además, tenemos que configurar cómo modelar la relación en el RDBMS.

El lado del propietario es donde configuramos la relación, que para este ejemplo elegiremos la clase Student .

Podemos hacer esto con la anotación @JoinTable en la clase Student . Proporcionamos el nombre de la tabla de combinación ( course_like ) y las claves externas con las anotaciones @JoinColumn . El atributo joinColumn se conectará al lado propietario de la relación y el inverseJoinColumn al otro lado:

@ManyToMany @JoinTable( name = "course_like", joinColumns = @JoinColumn(name = "student_id"), inverseJoinColumns = @JoinColumn(name = "course_id")) Set likedCourses;

Tenga en cuenta que no es necesario usar @JoinTable , o incluso @JoinColumn : JPA generará los nombres de tabla y columna para nosotros. Sin embargo, la estrategia que usa JPA no siempre coincidirá con las convenciones de nomenclatura que usamos. De ahí la posibilidad de configurar nombres de tablas y columnas.

En el lado de destino, solo tenemos que proporcionar el nombre del campo, que mapea la relación . Por lo tanto, establecemos el atributo mappedBy de la anotación @ManyToMany en la clase Course :

@ManyToMany(mappedBy = "likedCourses") Set likes;

Tenga en cuenta que, dado que una relación de varios a varios no tiene un propietario en la base de datos , podríamos configurar la tabla de combinación en la clase del curso y hacer referencia a ella desde la clase de estudiante .

3. Muchos a muchos usando una clave compuesta

3.1. Modelado de atributos de relación

Digamos que queremos que los estudiantes califiquen los cursos. Un estudiante puede calificar cualquier número de cursos y cualquier número de estudiantes puede calificar el mismo curso. Por lo tanto, también es una relación de muchos a muchos. Lo que lo hace un poco más complicado es que hay más en la relación de calificación que el hecho de que existe. Necesitamos almacenar la puntuación que el estudiante dio en el curso.

¿Dónde podemos almacenar esta información? No podemos ponerlo en la entidad Estudiante ya que un estudiante puede otorgar diferentes calificaciones a diferentes cursos. Del mismo modo, almacenarlo en la entidad del curso tampoco sería una buena solución.

This is a situation when the relationship itself has an attribute.

Using this example, attaching an attribute to a relation looks like this in an ER diagram:

We can model it almost the same way we did with the simple many-to-many relationship. The only difference is we attach a new attribute to the join table:

3.2. Creating a Composite Key in JPA

The implementation of a simple many-to-many relationship was rather straightforward. The only problem is that we cannot add a property to a relationship that way, because we connected the entities directly. Therefore, we had no way to add a property to the relationship itself.

Since we map DB attributes to class fields in JPA, we need to create a new entity class for the relationship.

Of course, every JPA entity needs a primary key. Because our primary key is a composite key, we have to create a new class, which will hold the different parts of the key:

@Embeddable class CourseRatingKey implements Serializable { @Column(name = "student_id") Long studentId; @Column(name = "course_id") Long courseId; // standard constructors, getters, and setters // hashcode and equals implementation }

Note, that there're some key requirements, which a composite key class has to fulfill:

  • We have to mark it with @Embeddable
  • It has to implement java.io.Serializable
  • We need to provide an implementation of the hashcode() and equals() methods
  • None of the fields can be an entity themselves

3.3. Using a Composite Key in JPA

Using this composite key class, we can create the entity class, which models the join table:

@Entity class CourseRating { @EmbeddedId CourseRatingKey id; @ManyToOne @MapsId("studentId") @JoinColumn(name = "student_id") Student student; @ManyToOne @MapsId("courseId") @JoinColumn(name = "course_id") Course course; int rating; // standard constructors, getters, and setters }

This code is very similar to a regular entity implementation. However, we have some key differences:

  • we used @EmbeddedId, to mark the primary key, which is an instance of the CourseRatingKey class
  • we marked the student and course fields with @MapsId

@MapsId means that we tie those fields to a part of the key, and they're the foreign keys of a many-to-one relationship. We need it, because as we mentioned above, in the composite key we can't have entities.

After this, we can configure the inverse references in the Student and Course entities like before:

class Student { // ... @OneToMany(mappedBy = "student") Set ratings; // ... } class Course { // ... @OneToMany(mappedBy = "course") Set ratings; // ... }

Note, that there's an alternative way to use composite keys: the @IdClass annotation.

3.4. Further Characteristics

We configured the relationships to the Student and Course classes as @ManyToOne. We could do this because with the new entity we structurally decomposed the many-to-many relationship to two many-to-one relationships.

Why were we able to do this? If we inspect the tables closely in the previous case, we can see, that it contained two many-to-one relationships. In other words, there isn't any many-to-many relationship in an RDBMS. We call the structures we create with join tables many-to-many relationships because that's what we model.

Besides, it's more clear if we talk about many-to-many relationships, because that's our intention. Meanwhile, a join table is just an implementation detail; we don't really care about it.

Moreover, this solution has an additional feature we didn't mention yet. The simple many-to-many solution creates a relationship between two entities. Therefore, we cannot expand the relationship to more entities. However, in this solution we don't have this limit: we can model relationships between any number of entity types.

For example, when multiple teachers can teach a course, students can rate how a specific teacher teaches a specific course. That way, a rating would be a relationship between three entities: a student, a course, and a teacher.

4. Many-to-Many With a New Entity

4.1. Modeling Relationship Attributes

Let's say we want to let students register to courses. Also, we need to store the point when a student registered for a specific course. On top of that, we also want to store what grade she received in the course.

In an ideal world, we could solve this with the previous solution, when we had an entity with a composite key. However, our world is far from ideal and students don't always accomplish a course on the first try.

In this case, there're multiple connections between the same student-course pairs, or multiple rows, with the same student_id-course_id pairs. We can't model it using any of the previous solutions because all primary keys must be unique. Therefore, we need to use a separate primary key.

Therefore, we can introduce an entity, which will hold the attributes of the registration:

In this case, the Registration entity represents the relationship between the other two entities.

Since it's an entity, it'll have its own primary key.

Note, that in the previous solution we had a composite primary key, which we created from the two foreign keys. Now, the two foreign keys won't be the part of the primary key:

4.2. Implementation in JPA

Since the coure_registration became a regular table, we can create a plain old JPA entity modeling it:

@Entity class CourseRegistration { @Id Long id; @ManyToOne @JoinColumn(name = "student_id") Student student; @ManyToOne @JoinColumn(name = "course_id") Course course; LocalDateTime registeredAt; int grade; // additional properties // standard constructors, getters, and setters }

Also, we need to configure the relationships in the Student and Course classes:

class Student { // ... @OneToMany(mappedBy = "student") Set registrations; // ... } class Course { // ... @OneToMany(mappedBy = "courses") Set registrations; // ... }

Again, we configured the relationship before. Hence, we only need to tell JPA, where can it find that configuration.

Note, that we could use this solution to address the previous problem: students rating courses. However, it feels weird to create a dedicated primary key unless we have to. Moreover, from an RDBMS perspective, it doesn't make much sense, since combining the two foreign keys made a perfect composite key. Besides, that composite key had a clear meaning: which entities we connect in the relationship.

Otherwise, the choice between these two implementations is often simply personal preference.

5. Conclusion

In this tutorial, we saw what a many-to-many relationship is and how can we model it in an RDBMS using JPA.

Vimos tres formas de modelarlo en JPA. Los tres tienen diferentes ventajas y desventajas cuando se trata de:

  • claridad del código
  • Claridad de DB
  • capacidad para asignar atributos a la relación
  • cuántas entidades podemos vincular con la relación, y
  • soporte para múltiples conexiones entre las mismas entidades

Como de costumbre, los ejemplos están disponibles en GitHub.