简体   繁体   中英

Working with Hibernate Queries

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.eq("firstName", firstName);
}
if (middleName != null) {
     crit.add(Expression.eq("middleName", middleName);
}
if (lastName != null) {
     crit.add(Expression.eq("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?

Criteria is the preferred way. It uses Prepared Statements in the background, so you don't need to worry about SQL injection.

Criteria is the newer way. It was introduced after the hql query layer. Underneath the Criteria api still generates hql. I tend to use the Criteria api because the code looks cleaner and its easier to maintain.

I believe its very common to write queries, specially when you want to make complex inquires, Hibernate has its own query language.

Check Hibernate Query Language HQL

Criteria is the best way to make dynamic queries. No need for null checks on a parameter, just don't add that criteria.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM