我有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
我發佈的代碼在 –