多对多where子句

时间:2013-02-04 00:40:07

标签: java hibernate

给出3个表:

student (id)
student_to_class (student_id, class_id)
class (id)

我想在student_to_class上应用where子句,其中student_id =:studentId。我发现很多例子适用于“class”表或“student”表中的where子句,而不是多对多表。

学生表有@ManyToMany

@ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(
    name = "student_to_class",
    joinColumns = { @JoinColumn(name = "student_id", nullable = false) },
    inverseJoinColumns = { @JoinColumn(name = "class_id", nullable = false) }
)
private Set<ClassEntity> classes;

班级表有@ManyToMany

@ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(
    name = "student_to_class",
    joinColumns = { @JoinColumn(name = "class_id", nullable = false) },
    inverseJoinColumns = { @JoinColumn(name = "student_id", nullable = false) }
)
private Set<StudentEntity> students;

以下是我要翻译成条件的查询:

select * from student, student_to_class where student_to_class.student_id = 1 and student.id = student_to_class.class_id

我正在试图弄清楚如何引用多对多表,因为我没有代表该表的实际类。

Criteria c = sessionFactory.getCurrentSession().createCriteria(ClassEntity.class);
c.createAlias("student_to_class", "entities"); // how to reference the student_to_class ?
c.add(Restrictions.eq("entities.user_id", studentEntity.getId()));

但是我得到了一个错误,这对我来说很有意义,但我没有太多运气来解决它:     无法解析属性:student_to_class

1 个答案:

答案 0 :(得分:1)

由于Student表中的studentidstudentid表中的student_to_class相同,因此无需按连接表进行过滤。只需针对student.student_id

运行where子句