我正在尝试在我的代码上设置ManyToMany注释:
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(name = "user")
public class User extends AbstractUser
{
@ManyToMany(mappedBy = "promotors", cascade = CascadeType.PERSIST)
@JoinTable(name = "user_student",
joinColumns=@JoinColumn(name="promotor_id", referencedColumnName="id"),
inverseJoinColumns=@JoinColumn(name="student_id", referencedColumnName="id")
)
private Collection<User> students;
@ManyToMany
private Collection<User> promotors;
}
但是每次我尝试运行应用程序并生成db时,它会为ManyToMany创建2个表,1个新表,我在下面定义了一个名为user_student的表,但它还创建了第二个表user_user,我没有&# 39; t定义但是从启动子生成。
答案 0 :(得分:1)
这是正确的,你不能在一张桌子上映射多对多的关系。因为您只有一个可能的列来映射它。什么强制执行一对一的关系。
您始终必须拥有映射表。它也是在不同表格上映射多对多关系的最便捷方式。
答案 1 :(得分:0)
显然,我没有正确定义第二个ManyToMany,这是正确的代码:
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(name = "user")
public class User extends AbstractUser
{
@ManyToMany
@JoinTable(name = "user_student",
joinColumns={@JoinColumn(name="promotor_id", referencedColumnName="id")},
inverseJoinColumns={@JoinColumn(name="student_id", referencedColumnName="id")}
)
private Collection<User> students;
@ManyToMany(mappedBy = "students", cascade = CascadeType.PERSIST)
private Collection<User> promotors;
}