问题
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?
回答1:
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
回答2:
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();
来源:https://stackoverflow.com/questions/1969319/hibernate-criteria-query-on-object-properties