Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Criteria / Query on object properties

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?

like image 599
n002213f Avatar asked Dec 28 '09 12:12

n002213f


People also ask

How do I create a criteria query in Hibernate?

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.

Can you explain criteria in Hibernate?

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.

What is the difference between query and criteria in Hibernate?

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.

Is Criteria API deprecated?

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.


2 Answers

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();
like image 132
Droo Avatar answered Oct 31 '22 16:10

Droo


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

like image 29
Bozho Avatar answered Oct 31 '22 14:10

Bozho