Video in progress
You suddenly need an extra column (for example, `added_at` or `role`) on a `@ManyToMany` join table. How do you change the mapping?
@ManyToMany can't express an extra column. You have to make the join table its own entity (ProjectMember) and link it from both sides with @ManyToOne. Both parent entities keep an @OneToMany(mappedBy = ...) collection. A data migration usually isn't needed, because the table is the same.
📖 Answer
Before:
@ManyToMany
@JoinTable(name = "project_member",
joinColumns = @JoinColumn(name = "project_id"),
inverseJoinColumns = @JoinColumn(name = "user_id"))
private Set<User> members;
After:
@Entity
@Table(name = "project_member")
class ProjectMember {
@EmbeddedId
private ProjectMemberId id = new ProjectMemberId();
@MapsId("projectId") @ManyToOne(fetch = FetchType.LAZY)
private Project project;
@MapsId("userId") @ManyToOne(fetch = FetchType.LAZY)
private User user;
@Enumerated(EnumType.STRING)
private Role role;
private Instant addedAt;
}
// inside Project
@OneToMany(mappedBy = "project", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<ProjectMember> members = new HashSet<>();
public void addMember(User u, Role r) {
members.add(new ProjectMember(this, u, r, Instant.now()));
}
In the migration you only add the new columns (role, added_at) and give the old rows a default value. You can also add a surrogate id: then instead of @EmbeddedId you have a plain Long id and a unique constraint on (project_id, user_id).
The change affects all the code: project.getMembers() now returns ProjectMember, not User, and the JPQL becomes join p.members m join m.user u. That's why I often write a new @ManyToMany with an intermediate entity from the start: "we'll need a column later" comes up very often.
A bonus: with an intermediate entity, Hibernate's "delete everything and write it again" problem with a @ManyToMany bag goes away too, since each row is its own entity.
Sign up to mark studied questions and save your progress.