我正在尝试使用复合主键在学生和教学课程之间建立许多联系:我的课程:@Entity@Table(name="Student_mtm_cId")public class Student {
private String id;
private Set<StudentTClass> teachingClasses = new HashSet<StudentTClass>();
@OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.student")
public Set<StudentTClass> getTeachingClasses() {
return teachingClasses;
}
public void setTeachingClasses(Set<StudentTClass> teachingClasses) {
this.teachingClasses = teachingClasses;
}
public void addStudentToClass(TeachingClass teachingClass){
StudentTClass studentTClass = new StudentTClass();
studentTClass.setStudent(this);
studentTClass.setTeachingClass(teachingClass);
teachingClasses.add(studentTClass);
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Id @GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid", strategy = "uuid")
@Column(name = "student_id", nullable = false)
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
//all other setters and getters and isequal/hashCode omitted.}TeachingClass:@Entity@Table(name="TechingClass_MTM")public class TeachingClass {
private String id;
private String name;
private String description;
private Set<StudentTClass> teachingClasses = new HashSet<StudentTClass>();
public TeachingClass(){}
public TeachingClass(String name, String description) {
super();
this.name = name;
this.description = description;
}
public void addStudentToClass(Student student){
StudentTClass studentTClass = new StudentTClass();
studentTClass.setStudent(student);
studentTClass.setTeachingClass(this);
teachingClasses.add(studentTClass);
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.teachingClass")
public Set<StudentTClass> getTeachingClasses() {
return teachingClasses;
}
3 回答
德玛西亚99
TA贡献1770条经验 获得超3个赞
我解决了这个问题。我映射了Getter而不是field。
public class StudentTClass { //@EmbeddedId private StudentTClassPK pk = new StudentTClassPK(); @EmbeddedId public StudentTClassPK getPk() { return pk; }
互换的青春
TA贡献1797条经验 获得超6个赞
如果可以的话,我强烈建议您删除组合键。只需简单的主键,就可以解决很多问题并简化代码。过去,我无法在数据库中使用复合键,因为我无法修改数据库。不幸的是我没有代码。但是我确实记得需要花费一些时间才能使它们全部正常工作。抱歉,无法提供更多帮助。
慕容森
TA贡献1853条经验 获得超18个赞
仅由于我们不知道如何使用ORM框架而使ORM变得简单,这并不是一种恕我直言的方法。我喜欢DB提供的所有可能性,也希望将它们保存在后端代码中。另一件事是,设置按我们想要的方式工作的ORM有点复杂。
添加回答
举报
0/150
提交
取消