给定3张桌子:
student (id)
student_to_class (student_id, class_id)
class (id)
我想在 student_to_class 上应用 where 子句,其中 student_id = :studentId。我发现许多示例适用于“班级”表或“学生”表上的 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