0

我有 3 个表:Student、Course 和 Student_Course。每个学生可能有几门课程,每门课程可能有几个学生。(多对多)。我需要编写一种方法来获得课程的所有学生。在 SQL 中,它是 2 个内部连接。我试过这个:

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;

如何编写正确的代码?

4

2 回答 2

1

我认为您应该在Course课堂上添加此注释

@ManyToMany(mappedBy="courses")
private Set<Student> students = new HashSet<Student>();

这是通常建模的多对多关系。现在,您可以非常轻松地访问课程的学生。

于 2013-10-01T09:07:45.333 回答
0

你能确保在这种情况下你有正确的休眠映射吗?如果正确定义,您不需要在查询中使用 student_course 映射表。

您的实体类应该看起来像

class Student {

...
.
..
private Set<Course> courses= new HashSet<Course>(0);


}

class Course{

private Set<Student > categories = new HashSet<Student >(0);
}

休眠映射应该有(对于课程实体,它应该有学生设置)

 <set name="courses" table="student_course" 
            inverse="false" lazy="true" fetch="select" cascade="all" >
            <key>
                <column name="STUDENT_ID" not-null="true" />
            </key>
            <many-to-many entity-name="com....Course">
                <column name="COURSE_ID" not-null="true" />
            </many-to-many>
        </set>

然后您检索课程并使用学生集

session = HibernateUtil.getSessionFactory().openSession();
        course= (Course)session.load(Course.class, user_id);
        course.getStudents();

/穆克什

于 2013-10-01T09:08:30.840 回答