I have a class AppUser
;
class AppUser {
private String firstName;
private String lastName;
//-- getters and setters
}
I also have another class Student
;
class Student {
private AppUser appUser;
private Date dateOfBirth;
//-- getters and setters
}
How would i search for Student John Doe
, firstName John, lastName Doe?
Had it been the date of birth property, i would create a Criteria
and add an equality Restriction (Restristions.eq
) on the date. How would i do it for lastName and firstName in the AppUser object?
The Hibernate Session interface provides createCriteria() method, which can be used to create a Criteria object that returns instances of the persistence object's class when your application executes a criteria query.
The Hibernate Criteria Query Language (HCQL) is used to fetch the records based on the specific criteria. The Criteria interface provides methods to apply criteria such as retreiving all the records of table whose salary is greater than 50000 etc.
HQL is suitable for executing Static Queries, where as Criteria is suitable for executing Dynamic Queries. HQL is to perform both select and non-select operations on the data, Criteria is only for selecting the data, we cannot perform non-select operations using criteria.
The Criteria API allows us to build up a criteria query object programmatically, where we can apply different kinds of filtration rules and logical conditions. Since Hibernate 5.2, the Hibernate Criteria API is deprecated, and new development is focused on the JPA Criteria API.
You might need to add an alias...something like:
List students = session.createCriteria(Student.class).createAlias("appUser", "user").add(Restrictions.eq("user.firstName", firstName)).list();
Without an alias:
List students = session.createCriteria(Student.class).add(Restrictions.eq("appUser.firstName", firstName)).list();
Query:
Query q = session.createQuery(
"SELECT s from Student s WHERE s.appUser.firstName=:firstName AND s.appUser.lastName=:lastName");
q.setParameter("firstName", "John");
q.setParameter("lastName", "Doe");
For using Criteria, check this thread
Also take a look at this page from hibernate docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With