【问题标题】:Fetch data from 4 tables join together using hibernate query使用休眠查询从 4 个表中获取数据连接在一起
【发布时间】:2016-04-07 00:42:27
【问题描述】:

我有 4 张桌子:

Teacher、Student、Course 及其公共连接表 TeacherStudentCourse。

前三个表都与最后一个表有一对多的关系。 这是来自我的数据库DataBase sample 的屏幕截图 因此,例如,我应该能够通过提供教师 ID 和课程 ID 来获得所需的学生。

我之前问过一个关于连接表的问题。 Previous Question 我确实得到了答案。 我正在尝试根据以前的代码进行改进

    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    List<Object> list = session.createQuery("select s from Student s join s.teacherStudentCourses tsc where tsc.teacher = :teacher and tsc.course = :course")
            .setParameter("teacher", teacher)
            .setParameter("course", course)
            .list();
    session.getTransaction().commit();
    session.close();

但经过无数次尝试,我似乎并没有让它工作。也许查询不能以这种方式创建?任何帮助将不胜感激!

[更新]

我得到的错误是:

org.hibernate.QueryException: 无法解析属性:teacherStudentCourses of: model.Student [select s from model.Student s join s.teacherStudentCourses tsc where tsc.teacher = :teacher and tsc.course = :course]

【问题讨论】:

  • 错误表明学生实体没有正确映射teacherStudentCourses 字段。如果您需要更多帮助,只需发布​​您的实体代码
  • org.hibernate.QueryException: could not resolve property: search this error on SO有很多关于这个错误的QA。我相信你会找到答案的。顺便说一句,您似乎没有在 student 中映射 teacherStudentCourses。
  • 嗯,我想我是我的错误,当我在学生课上编写teacherStudentCourses 归档属性时,我有些为teacherStudentCourse 有一个双's'ss.. 现在它给我带来了一些其他错误,仍在调试中
  • @Joker,我确实有映射,但它没有显示在使用 MySQL 工作台中的逆向工程生成的 ERD 中

标签: java hibernate join hql


【解决方案1】:

这里的表通过外键相互关联,因此所有子表(教师、课程、学生)的 POJO 中都应该有一个父类型变量。

让这是 Student.class 中的“TeacherStudentCource tsc”。 现在查询将是..

select s.studentId,s.name,s.gender,s.birthdate, from Student s inner join s.tsc b where b.teacherId=:tid and b.courceId=:cid;

教师 ID=tid 课程 ID =cid

【讨论】:

    猜你喜欢
    • 2020-09-06
    • 2016-12-27
    • 2016-07-24
    • 1970-01-01
    • 1970-01-01
    • 2012-08-14
    • 2016-05-17
    • 2012-12-22
    • 2015-03-04
    相关资源
    最近更新 更多