给定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

最佳答案

由于Student表中的studentidstudentid表中的student_to_class相同,因此无需按联接表进行过滤。只需对student.student_id运行where子句

关于java - 多对多where子句,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14679039/

10-13 22:46