问题
I need to make a change in the project's model. Nowadays we have two classes with bidirectional many-to-many relationship (which implies in an relationship table) and need now to add extra informations to the relationship.
My question is: The only way to do it is create a class for the relationship (e.g. creating this one with the same name of the relationship table that already exists)?
I'm asking it because if we need to change the above relationship in the project, the change will be very impacting, almost the whole project (seriously).
The two classes that I'm talking about, just to make it clearer:
@Entity
public class Serie extends AbstractEntity {
@ManyToMany
private List<Disciplina> disciplinas;
}
@Entity
public class Disciplina extends AbstractEntity {
@ManyToMany(mappedBy = "disciplinas")
private List<Serie> series;
}
回答1:
As advised in the comments you need a join entity but do not need to expose this to clients of your domain model: by doing something like the below you would only need to change any client code that directly modifies the collections to call the addXXX/removeXXX methods. No client code is only aware of Join entity. So changes to your Java code should be minor.
As for queries well you will obviously need to change these as required.
Serie
@Entity
public class Serie extends AbstractEntity {
@OneToMany(mappedBy = "serie")
private List<SerieDisciplina> serieDisciplinas;
public List<Disciplina> getDisciplinas(){
//disciplinas extracted from serieDisciplinas
return Collections.unmodifiableList(...);
}
public void addDisciplina(Disciplina disciplina){
SerieDisciplina sd = new SerieDisciplina();
sd.stSerie(this);
sd.setDisciplina(disciplina);
serieDesciplinas.add(sd);
}
}
Disciplina
@Entity
public class Disciplina extends AbstractEntity {
@ManyToMany(mappedBy = "disciplina")
private List<SerieDisciplina> serieDisciplinas;
public List<Serie> getSeries(){
//series extracted from serieDisciplinas
return Collections.unmodifiableList(...);
}
public void addSerie(Serie serie){
SerieDisciplina sd = new SerieDisciplina();
sd.stSerie(Serie);
sd.setDisciplina(this);
serieDesciplinas.add(sd);
}
}
Join Entity
@Entity
public class SerieDisciplina{
@ManyToOne
private Serie serie;
@ManyToOne
private Disciplina disciplina;
//fields for the additional data about the relationship
//getters and setters
}
The Hibernate docs suggest avoiding @ManyToMany
in the first place to avoid such problems. See discussion at: Hibernate Best Practices: Avoiding Many-To-Many and 'exotic' relationships
来源:https://stackoverflow.com/questions/50222777/extra-columns-in-many-to-many-spring-data-jpa-relationship-with-minimal-changes