Hibernate Criteria / Query on object properties

n002213f picture n002213f · Dec 28, 2009 · Viewed 9.3k times · Source

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?

Answer

Droo picture Droo · Dec 28, 2009

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();