Working with Hibernate Queries
- by jschoen
I am new to hibernate queries, and trying to get a grasp on how everything works. I am using Hibernate 3 with Netbeans 6.5.
I have a basic project set up and have been playing around with how to do everything. I started with essentially a search query. Where the user can enter values into one or more fields.
The table would be Person with the columns first_name, middle_name, last_name for the sake of the example.
The first way I found was to have a method that took firstName, middleName, and lastName as parameters:
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = session.beginTransaction();
String query = "from Person where (first_name = :firstName or :firstName is null) "+
"and (middle_name = :middleName or :middleName is null) "
"and (last_name = :lastname or :lastName is null)";
Query q = session.createQuery(query);
q.setString("firstName", firstName);
q.setString("middleName", middleName);
q.setString("lastName", lastName);
List<Person> results = (List<Person>) q.list();
This did not sit well with me, since it seemed like I should not have to write that much, and well, that I was doing it wrong. So I kept digging and found another way:
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = session.beginTransaction();
Criteria crit = session.createCriteria(Person.class);
if (firstName != null) {
crit.add(Expression.ge("firstName", firstName);
}
if (middleName != null) {
crit.add(Expression.ge("middleName", middleName);
}
if (lastName != null) {
crit.add(Expression.ge("lastName", lastName);
}
List<Person> results = (List<Person>) crit.list();
So what I am trying to figure out is which way is the preferred way for this type of query? Criteria or Query? Why?
I am guessing that Criteria is the preferred way and you should only use Query when you need to write it by hand for performance type reasons. Am I close?