views:

70

answers:

2

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?

+2  A: 

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

Bozho
thanks for the answer, but is it possible to achieve this without a `Query`, rather using `Criteria` and `Restriction`?
n002213f
i have tried `appUser.firstName` but i get an error, unknown property
n002213f
I updated my answer pointing it to the hibernate forums where a similar question was asked.
Bozho
+1 for the forum thread, quite helpful
n002213f
A: 

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();
Droo
the second one (at least) wouldn't work. ;)
Bozho