我尝试创建解析两个@ManyToMany关系的桥表是不成功的。但是,此表必须包含其他字段。例如:
Course: -course_id - pk
Student: -student_id -pk
Bridge: -(course_id, student_id) - pk
-additional_field
我的学生班看起来像这样:
@Entity
public class Student extends Model {
@Id
@OneToMany
public List<Bridge> student_id;
}
课程类基本相同。
Bridge table看起来像这样:
@Entity
public class Bridge extends Model{
@EmbeddedId
public compound_key student_course;
public String additional_field;
@Embeddable
public class compound_key{
@ManyToOne
public Student student_id;
@ManyToOne
public Student course_id;
}
}
感谢您的帮助。
答案 0 :(得分:2)
我找到了以下解决方案。这是Bridge中没有复合键的解决方案。我在Bridge类中添加了正常的@Id字段,与Student和Course的关系是正常的关系。 此解决方案在数据库的“桥”表中包含一个额外的“id”字段。
以下是代码:
Student.java:
@Entity
public class Student extends Model {
@Id
public Integer id;
@OneToMany(mappedBy="student")
public List<Bridge> bridges;
public static Finder<Integer,Student> find = new Finder<Integer,Student>(
Integer.class, Student.class
);
}
Course.java:
@Entity
public class Course extends Model {
@Id
public Integer id;
@OneToMany(mappedBy="course")
public List<Bridge> bridges;
public static Finder<Integer,Course> find = new Finder<Integer,Course>(
Integer.class, Course.class
);
}
Bridge.java:
@Entity
public class Bridge extends Model {
@Id
public Integer id;
@ManyToOne public Student student;
@ManyToOne public Course course;
public String additional_field;
public static Finder<Integer,Bridge> find = new Finder<Integer,Bridge>(
Integer.class, Bridge.class
);
}
修改强>
经过多次尝试,我在Bridge类中找到了带有复合键的解决方案。类Student和Course与以前的解决方案相同。
Bridge.java更改为以下内容:
@Entity
public class Bridge extends Model {
Bridge() {
bridgeId = new BridgeId();
}
@EmbeddedId
protected BridgeId bridgeId;
@ManyToOne
@JoinColumn(name = "student_id", insertable = false, updatable = false)
private Student student;
@ManyToOne
@JoinColumn(name="course_id", insertable = false, updatable = false)
private Course course;
public String additional_field;
public Student getStudent() {
return student;
}
public void setStudent(Student aStudent) {
student=aStudent;
bridgeId.student_id = aStudent.id;
}
public Course getCourse() {
return course;
}
public void setCourse(Course aCourse){
course=aCourse;
bridgeId.course_id = aCourse.id;
}
}
还有额外的BridgeId.java:
@Embeddable
public class BridgeId implements Serializable
{
public Integer student_id;
public Integer course_id;
public int hashCode() {
return student_id + course_id;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
BridgeId b = (BridgeId)obj;
if(b==null)
return false;
if (b.student_id == student_id && b.course_id == course_id) {
return true;
}
return false;
}
}
此代码中更重要的是:
以上解决方案有几个解决方法。但我无法找到更容易和更清洁的人。