Talha Ahmed Khan
Talha Ahmed Khan

Reputation: 15433

Hibernate-Criteria: Use multiple conditions in 'ON Clause'

I have a situation that I need to apply another Condition inside ON clause while using Hibernate Criteria.

I am writing my MySQL and I am unable to find any reasonable way of converting it in 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')

What I am doing in this Query

I want all the student List either enrolled in specified course or not.

IF I have four Students the and only one student is enrolled in a course the result should be like

StudentID, CourseID
1          NULL
2          XXX
3          NULL
4          NULL

So far I what I have done is

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

By running this statement I get the query equivalent to the following query

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

Now this query does not serve the purpose of the query. It returns only one row where CourseID is not null.

EDIT

Hibernate Version 3.4.0GA

Upvotes: 0

Views: 1457

Answers (1)

pap
pap

Reputation: 27614

You can move your second criteria into the general WHERE clause like

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

Upvotes: 1

Related Questions