I am using inner joins via HQL as well as Criteria API to understand the difference in execution between the two and found an interesting one:
I have two classes School and Student having a one-to-many association. On executing the 2 different code snippets given below and calling the list() method, SQL queries generated by both are same but:
- in 1st case (HQL), it returns Object ( for Student and  for School)
- in 2nd case (Criteria API), it returns Student object only
Tatiana Vorobeva wrote:I'm not a specialist on this theme, just one question (sorry, if it's stupid):
Why do you use "Student.class" for the first criteria and simple String "school" in the second?
No question is stupid.
It is because we are creating a main criteria on Student class and the sub criteria (note that it is not session.createCriteria()) is on a property of that class. Hibernate internally creates a join as it knows that it is associated to the School class. The mapping is:
So, try to use "com.test.Student.school" (where "com.test" = Student's class package) instead of "school"?
P.S.: maybe you know some good docs for learning how to use Criteria? I've started to learn Hibernate and want to read about Criteria.
There wasn't any execution errors in my code, just wanted to know the logic behind this dissimilarity. I found the answer to my original question. It (The Criteria API) returns only the main criteria class until we explicitly tell it to include all entities in the result (unlike HQL). The following line, if added to the criteria, would include other entities as well:
P.S.: You can start with the book "Java Persistence with Hibernate" by Cristian Bauer and Gavin King