@ManyToMany? Wait a moment.

@ManyToMany? Wait a moment.

Pure Many-To-Many relationships rarely exist, thus it's worth to think about it when designing JPA Entities.

Sometimes in projects when modeling #JPA Entities we come to a point using the @ManyToMany annotation. Like for example the relationship between an Employee and a Project seems to be a classic example of a Many-to-Many relationship. An employee can work on many projects and in a project can work many employees.

Before slapping that @ManyToMany annotation on our Java class and call it a day ask yourself if you see any additional attributes that someone might want to persist on this relationship. If you cannot find the need for additional attributes ask your business team if they see anything that might be worth persisting now or in the foreseeable future.

If yes you can drop that @ManyToMany idea and proceed to create an additional Entity that connects these two Entities. In the Employee-Project example above one might want to know the amount of hours worked by employees in a project.

import org.springframework.data.jpa.domain.AbstractPersistable;

import javax.persistence.*;

@Entity
public class ProjectEmployee extends AbstractPersistable<Long> {

    @ManyToOne
    @JoinColumn(name = "project_id")
    private Project project;

    @ManyToOne
    @JoinColumn(name = "employee_id")
    private Employee employee;

    @Column
    private Integer hoursWorked;

}

This way you save yourself a refactoring later on, maybe a migration of the data and schema and evade the temptation to use some esoteric methods to persist the data in the join table.

Summary

Usually pure @ManyToMany relationships rarely exist in the real world. Thus it's worth spending some time upfront to get this right now rather than refactor later. If you want to be a bit radical you could start always start with an intermediate Entity and ban @ManyToMany from your repertoire.