我有一个在EJB中设计ManyToMany的问题,一个连接表怎么可以有一个属性?
下面是一个例子,学生和课程是ManyToMany,每个学生都有很多课程,许多学生选择一门课程。JPA ManyToMany,JoinTable如何拥有一个属性?
@Entity
public class Student implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
String name;
private Collection<Course> courses;
@ManyToMany(mappedBy = "students",cascade=CascadeType.ALL)
public Collection<Course> getCourses() {
return this.courses;
}
public void setCourses(Collection<Course> courses) {
this.courses = courses;
}
}
@Entity
public class Course implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
String name;
private Collection<Student> students;
@ManyToMany(cascade=CascadeType.ALL)
@JoinTable(name = "Student_Course",
joinColumns = {@JoinColumn(name = "Course_ID", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "Student_ID", referencedColumnName = "id")})
public Collection<Student> getStudents() {
return this.students;
}
public void setStudents(Collection<Student> students) {
this.students = students;
}
}
但是,如果我在JoinTable中有一个属性,例如每个学生在一个课程中都有一个分数。如何使用ManyToMany在EJB中创建它?
非常感谢您的关注!
如果你的关系有属性,那么你应该把它建模为实体。这个问题几乎是一样的:http://stackoverflow.com/questions/7602386/mapping-value-in-junction-table-to-entity/7603036#7603036即使代表关系的实体名称(CourseAssignment)也很适合你案件。 – 2011-12-21 08:16:57
这是不可能的,你不能添加属性关系。如果您需要访问连接表中的属性,那么该属性属于某个实体,因此您需要第三个实体。 – 2011-12-21 09:16:21
对不起,我纠正了这一点。我还有一个问题,当我使用@Embeddable类作为连接表的PK时,它不起作用(编译失败),有人说JPA2.0不支持它!请看看[jpa-eclipselink-manytomany-with-dat](http://stackoverflow.com/questions/4013397/jpa-eclipselink-manytomany-with-data),有什么办法可以使它工作吗? – seaguest 2011-12-21 10:47:45