Criteria -- object-oriented query of Hibernate

Source: Internet
Author: User
Tags alphanumeric characters

Criteria -- object-oriented query of Hibernate

When talking about Hibernate queries, we often think of HQL, which makes our SQL statements object-oriented. In fact, it is similar to replacing the tables and fields in SQL statements with the corresponding entities and attributes. In fact, there is another Query method in Hibernate. We cannot see the shadow of the task SQL, that is, Criteria Query.

Criteria is a more Object-Oriented Query Method than hql. -- Baidu encyclopedia


1. Brief Introduction

Criteria Query uses an object-oriented design to encapsulate data Query conditions as an object. In short, Criteria Query can be seen as an object representation of traditional SQL statements, such:


Criteria criteria=session.createCriteria(TUser.class);criteria.add(Expression.eq("name","zhanglianhai"));criteria.add(Expression.eq("sex",new Integer(1));
The criteria instance here is essentially an encapsulation of SQL "select * from t_user where name = 'erica 'and sex = 1. At runtime, Hibernate generates corresponding SQL statements based on the query conditions specified in Criteria. Of course, to use Criteria, you need to know its alphanumeric characters, such as eq, qt, and le "......


Ii. Common related classes

1. Example Class

The Example class implements the Criteria interface. Similarly, it can be used as a query condition for Criteria. Example is used to search for other objects whose attributes match the existing objects.


Criteria criteria=session.CreateCriteria(TUser.class);TUser exampleUser=new TUser();exapleUser.getName("Erica");criteria.add(Example.create(exampleUser));List
   list=criteria.list();for(TUser user:list){    System.out.println(user.getName());}
Creates a TUser object exampleUser and serves as a template to query all records with the same name attribute.


2. DetachedCriteria

In Hibernate2, the Criteria life cycle is in the life cycle of its host Session. That is to say, once the session is destroyed, the Criteria instance also becomes invalid. Hibernate3 introduces DetachedCriteria. DetachedCriteria exists independently from the session instance. In this way, we can detach some common Criteria query conditions, it is bound to the current session instance each time it is used for better code reuse.

DetachedCriteria deCriteria=DetachedCriteria.forClass(TUser.class);deCriteria.add(Expression.eq("name","Erica"));deCriteria.add(Expression.eq("sex",new Integer(1)));Criteria criteria=deCriteria.getExecutableCriteria(session);List
   list=criteria.list();for(TUser user:list){    System.out.println(user.getName());}
The lifecycle of DetachedCriteria is irrelevant to the session instance. We can independently create a DetachedCriteria instance and bind it to the session to obtain the Criteria instance at runtime. In this way, we can separate the query logic from the Criteria instance to maximize code reuse.

DetachedCriteria can also be used for subquery expressions:

DetachedCriteria aveAge=DetachedCriteria.forClass(TUser.class);avgAge.setProjection(Projections.avg("age"));Criteria criteria=session.createCriteria(TUser.class);criteria.add(Subqueries.propertyGT("age",avgAge));
Through Subqueries, we can include DetachedCriteria into the query expression, which is a typical subquery statement in SQL. The SQL statements generated in the preceding example are roughly as follows: select... from T_User where age> (select avg (age) from T_User)

Iii. Advanced features
1. limit the range of returned records

You can use the criteria. setFirstResult/setMaxResults method to limit the range of records returned by one query:

Criteria criteria = session. createCriteria (TUser. class); // limit the criteria of 20 records starting from the first 100 results returned by the query. setFirstResult (100); criteria. setMaxResults (20 );
2. Record sorting
Criteria criteria=session.createCriteria(TUser.class);criteria.add(Expression.eq("groupId",new Integer(2)));criteria.addOrder(Order.asc("name"));criteria.addOrder(Order.desc("groupId"))
3. Grouping and statistics

In Hibernate3, we can also use Criteria to complete grouping and statistics. Grouping and statistical expressions are encapsulated by the Projections Class introduced by Hibernate3.

Criteria criteria=session.createCriteria(TUser.class);criteria.setProjection(Projections.groupProperty("age"));List
   list=criteria.list();for(TUser user:list){    System.out.println(user);}
In the preceding example, the current TUser records are grouped by age. Using the Projections. groupProperty method, we specify the target attribute "age" for grouping ". The generated SQL statement: select this. age as y0 _ from T_User this_group by this _. age.
In addition, for the statistics and grouping functions of Multi-condition combinations, we can use ProjectionList. In the following example, we calculate the number of users at each age level:
ProjectionList projectionlist=Projections.ProjectionList();projectionList.add(Projections.groupProperty("age"));projectionList.add9Projections.rowCount());Criteria criteria=session.createCriteria(TUser.class);criteria.setProjection(projectionList);

Iv. Summary

The query method is more object-oriented, and I also prefer this method, because it does not need to write any SQL or hql statements. Currently, the query conditions provided by criteria can meet the basic query requirements, but complex queries still do not work very well.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.