我正在嘗試使用復合主鍵在學生和教學課程之間建立許多聯系:我的課程:@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
提交
取消