我为我想要实现的代码编写了一个示例,我在Constraint“Student_Teacher_FK”已经存在时出错。
@embiddable类有一个使用当前代码创建两次的外键。
@Entity
public class Teacher {
@Id
@GeneratedValue
private Long id;
@Column(name = "Name")
private String name;
}
@Entity
public class Student{
@Id
@GeneratedValue
private Long id;
@Column(name = "Name")
private String name;
}
@Embeddable
public class StudentList implements Serializable {
@ManyToMany
@JoinTable(name = "Student_Teacher",
joinColumns =
@JoinColumn(name = "Student_ID", referencedColumnName = "ID"),
inverseJoinColumns =
@JoinColumn(name = "Teacher_ID", referencedColumnName = "ID")
)
@ForeignKey(name = "Student_Teacher_FK", inverseName = "Teacher_Student_FK")
public List<Student> studentList = new ArrayList<Student>();
}
@Entity
public class HistoryTeacher extends Teacher {
@Embedded
@NotNull
private StudentList StudentList = new StudentList ();
}
@Entity
public class LangTeacher extends Teacher {
@Embedded
@NotNull
private StudentList StudentList = new StudentList ();
}
@Entity
public class RetiredTeacher extends Teacher {
// has no students
}
答案 0 :(得分:1)
@embeddable:定义一个类,其实例存储为拥有实体的内在部分并共享实体的身份(http://docs.oracle.com/javaee/6/api/javax/persistence/Embeddable.html)
当您在2个不同的实体中声明它时,jpa将创建关联的关联表(学生 - 教师)2次,并使用相关的fk,这是明确命名的,因此也创建了2次同名。这是你的错误。
我认为使用@embeddable并不适用于您打算做的事情。学生有自己的存在,不属于教师本身(不是uml作品/黑钻石),所以它不是一个可嵌入的实体。学生列表应由教师实体使用简单的manyToMany关联持有。