我有3个表格:学生,课程和Student_Course。每个学生可能有几门课程,每门课程可能有几个学生。 (很多对多)。我需要写一个能够让所有学生学习课程的方法。在SQL中它是2个内部连接。我尝试这样做:Hibernate加入3个表格
Criteria criteria = session.createCriteria(Student.class, "s");
criteria.createAlias("student_course", "s_c");
criteria.createAlias("course", "c");
criteria.add(Restrictions.eq("s.student_id", "s_c.student_id"));
criteria.add(Restrictions.eq("s_c.course_id", "c.course_id"));
criteria.add(Restrictions.eq("c.course_id", course.getId()));
courses = criteria.list();
但我得到一个org.hibernate.QueryException: could not resolve property: student_course of: com.example.entity.Student
@Entity
@Table(name = "STUDENT")
public class Student {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "STUDENT_ID", unique = true, nullable = false)
private long id;
@ManyToMany(targetEntity = Course.class, fetch = FetchType.EAGER)
@JoinTable(name = "STUDENT_COURSE", joinColumns = { @JoinColumn(name = "student_id") }, inverseJoinColumns = { @JoinColumn(name = "course_id") })
private Set<Course> courses = new HashSet<Course>();
和:
@Entity
@Table(name = "COURSE")
public class Course{
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "COURSE_ID", unique = true, nullable = false)
private long id;
如何编写正确的代码?
你可以发布你的学生课吗? –
为了回答这个问题,我们需要知道你是如何建模关系的。所以请提供带注释的课程。也许你只需要阅读http://viralpatel.net/blogs/hibernate-many-to-many-annotation-mapping-tutorial – luksch
我发布的代码在 –