【问题标题】:Hibernate-Criteria: Use multiple conditions in 'ON Clause'Hibernate-Criteria:在“ON 子句”中使用多个条件
【发布时间】:2012-09-15 15:49:37
【问题描述】:

在使用 Hibernate Criteria 时,我需要在 ON 子句中应用另一个 Condition。

我正在编写我的 MySQL,但我无法找到任何合理的方式在 Hibernate Criteria 中转换它。

SELECT s.StudentID AS StudentID, sc.CourseID AS CourseID
FROM Student s 
     LEFT JOIN StudentCourse sc ON 
          (sc.StudentID = s.StudentID AND sc.CourseID = 'XXX')

我在这个查询中做什么

我希望所有学生列表都注册或不注册指定课程。

如果我有四个学生,并且只有一个学生注册了一门课程,结果应该是这样的

StudentID, CourseID
1          NULL
2          XXX
3          NULL
4          NULL

到目前为止我所做的

Criteria cr = getSession().createCriteria(Student.class);
cr.createAlias("studentCourse", "sc", CriteriaSpecification.LEFT_JOIN)
    .add(Restrictions.eq("sc.CourseID", 'XXX'));

通过运行此语句,我得到的查询等同于以下查询

SELECT *
FROM Student s
     LEFT JOIN StudentCourse sc ON (sc.StudentID = s.StudentID)
WHERE sc.CourseID = 'XXX'

现在这个查询不符合查询的目的。它只返回 CourseID 不为空的一行。

编辑

休眠版本 3.4.0GA

【问题讨论】:

    标签: java sql hibernate hibernate-criteria


    【解决方案1】:

    您可以将您的第二个标准移动到一般 WHERE 子句中,例如

    WHERE (sc.CourseID = 'XXX' or sc.CourseID is null)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-17
      • 2012-03-24
      • 2017-01-20
      • 2014-10-03
      • 2011-12-01
      • 2019-04-01
      • 2017-02-16
      • 1970-01-01
      相关资源
      最近更新 更多