hibernate's Criteria Query (transfer)

When querying data, people often need to set query conditions. In SQL or HQL statements, query conditions are often placed in the where clause. In addition, Hibernate also supports Criteria query (Criteria Query), which encapsulates the query conditions as a Criteria object. In practical applications, use the createCriteria() method of Session to build an org.hibernate.Criteria instance, and then add specific query conditions to the Criteria instance through the Criteria add() method. In this way, programmers can query data without using SQL or even HQL, as shown in Routine 9-1.

Routine 9-1 Criteria application example 
code
Criteria cr = session.createCriteria(Student.class); //Generate a Criteria object
cr.add(Restrictions.eq("name", "Bill"));//Equivalent to where name='Bill'
List list = cr.list();
Student stu = (Student)list.get(0);
System.out.println(stu.getName());



1.Common Query Restriction Methods

In Routine 9-1, the Restrictions.eq() method represents equal, the case of equals. The Restrictions class provides a query restriction mechanism. It provides many methods to implement query limits. These methods and some other common query restriction methods for criteria are listed in Table 9-1.

Table 9-1 Commonly used query restriction methods

in Method


Description

Restrictions.eq()


equal, =

Restrictions.allEq()


parameter is a Map object, use key/value to compare multiple equals, which is equivalent to the effect of multiple Restrictions.eq()

Restrictions.gt()


greater-than, >

Restrictions.lt()


less-than, <

Restrictions.le()


less-equal, <=

Restrictions.between()


corresponds to the between clause of SQL

Restrictions.like()


corresponds to the like clause of SQL

Restrictions.in()


corresponds to SQL in clause

Restrictions.and()


and relation

Restrictions.or()


or relation

Restrictions.isNull()


determines whether the attribute is empty, returns true if it is empty, otherwise returns false

Restrictions.isNotNull(


) is the opposite of Restrictions.isNull()

Order.asc()


Sort ascending order according to the incoming field

Order.desc()


Sort descending order according to the incoming field

MatchMode.EXACT


String exact match, equivalent to "like 'value'"

MatchMode.ANYWHERE


string in the middle, equivalent to "like '%value%'"

MatchMode.START


string is in the first position, which is equivalent to "like 'value%'"

MatchMode.END


string is in the last position, which is equivalent to "like '%value'"

Example 1: Query All Student objects with student names starting with t.

Criteria cr = session.createCriteria(Student.class);
cr.add(Restrictions.like("name", "t%"))
List list = cr.list();
Student stu = (Student)list.get(0 );

or use another way:

Criteria cr = session.createCriteria(Student.class);
cr.add(Restrictions.like("name", "t", MatchMode.START))
List list = cr.list() ;
Student stu = (Student)list.get(0);

Example 2: Query all Student objects with student names between Bill, Jack and Tom.

String[] names = {"Bill", "Jack", "Tom"}
Criteria cr = session.createCriteria(Student.class);
cr.add(Restrictions.in("name", names))
List list = cr. list();
Student stu = (Student)list.get(0);

Example 3: Query all Student objects whose age is equal to 22 or whose age is null (null).

Criteria cr = session.createCriteria(Student.class);
cr.add(Restrictions.eq("age", new Integer(22));
cr.add(Restrictions.isNull("age"));
List list = cr. list();
Student stu = (Student)list.get(0);

Example 4: Query all Student objects whose names begin with the letter F, and sort them in ascending order by name.

Criteria cr = session.createCriteria(Student.class);
cr.add(Restrictions.like(“name”, “F%”);
cr.addOrder(Order.asc(“name”));
List list = cr.list();
Student stu = (Student)list.get (0);

The method of calling Order.asc should be the addOrder() method of Criteria.





When using the add() method to add conditions, the default is to use and to combine conditions. If you want to combine conditions by or, you can use The Restrictions.or() method, for example in conjunction with the condition that age is equal to (eq) 20 or (or) age is Null (isNull):

    Criteria criteria = session.createCriteria(User.class); 
    criteria.add(Restrictions.or( 
                       Restrictions. eq("age", new Integer(20)), 
                       Restrictions.isNull("age") 
                   )); 
    List users = criteria.list();



Observe the generated SQL statement, where and or clauses will be used to complete the SQL Conditional query:

Hibernate: select this_.id as id0_0_, this_.name as name0_0_, this_.age as age0_0_ from T_USER this_ where (this_.age=? or this_.age is null)





When querying using Criteria, it can not only be combined in SQL The function of the where clause can also be combined with query functions such as sorting, statistics, and grouping. This is the Criteria advanced query.

Ordering
You can use Criteria to query, and use org.hibernate.criterion.Order to order the results, for example, use Oder.asc(), specify the order according to "age" from small to large (use desc() otherwise):

    Criteria criteria = session.createCriteria(User.class); 
    criteria.addOrder(Order.asc("age")); 
    List users = criteria.list();

Note that when adding Order conditions, the addOrder() method is used, and It is not the add() method. When generating SQL statements, order by and asc (desc) will be used to sort and specify:

Hibernate: select this_.id as id0_0_, this_.name as name0_0_, this_.age as age0_0_ from T_USER this_ order

Limit the number of queries by this_.age asc
Criteria's setMaxResults() method can limit the number of queries returned. If you cooperate with setFirstResult() to set the position of the first data returned in the query result, you can achieve simple paging, such as returning 50 data after the 51st. (if any):

    Criteria criteria = session.createCriteria(User.class); 
    criteria.setFirstResult(51); 
    criteria.setMaxResults(50); 
    List users = criteria.list()

; Hibernate will automatically generate database-dependent limited number of query clauses. For example, in MySQL, use limit to generate the following SQL statements:

Hibernate: select this_.id as id0_0_, this_.name as name0_0_, this_.age as age0_0_ from T_USER this_ limit ?, ?

Statistical actions
You can perform statistical actions on query results, using avg(), rowCount(), count(), max(), min(), countDistinct() of org.hibernate.criterion.Projections and other methods, and then use the setProjection() method of Criteria to add condition settings, such as averaging the "age" of the query results:

    Criteria criteria = session.createCriteria(User.class); 
    criteria.setProjection(Projections.avg("age")); 
    List users = criteria.list();

The above program will be averaged by Hibernate's automatically generated SQL avg function:

Hibernate: select avg(this_.age) as y0_ from T_USER this_grouping can also

cooperate with the groupProperty() of Projections to group the results, such as grouping by "age", that is, if "age" in the data has 20, 20, 25, 30, the following will display 20, 25
, 30:

    Criteria criteria = session.createCriteria(User.class); 
    criteria.setProjection(Projections.groupProperty("age")); 
    List users = criteria.list();

The above program will automatically generate the group by child of SQL by Hibernate For grouping calculation:

Hibernate: select this_.age as y0_ from T_USER this_ group by this_.age

If you want to combine statistics and grouping functions at the same time, you can use org.hibernate.criterion.ProjectionList, for example, the following program will calculate each age How many people are there:

    ProjectionList projectionList = Projections.projectionList(); 
    projectionList.add(Projections.groupProperty("age")); 
    projectionList.add(Projections.rowCount()); 
    
    
    Criteria criteria = session.createCriteria(User.class); 
    criteria.setProjection( projectionList); 
    List users = criteria.list(); 

Observe the generated SQL statement, use group by to group first, and then count the count function for each group,

Hibernate: select this_.age as y0_, count(* ) as y1_ from T_USER this_ group by this_.age Query

based on known objects. It is not necessary to use Restrictions to
set query conditions. If there are many attribute conditions, it is inconvenient to use Restrictions. If there is a known object, you can use this The object is used as the basis for the query to see if there is an object with similar properties, for example:

    User user = new User(); 
    user.setAge(new Integer(30)); 
    
    Criteria criteria = session.createCriteria(User.class); 
    criteria.add(Example.create(user)); 
    
    List users = criteria.list(); 

Criteria advanced query, you can pass org.hibernate.criterion.Example The create() method is used to create an Example instance. Example implements the Criteria interface, so you can use the add() method to add it to the Criteria condition setting. Hibernate will automatically filter out the empty attributes. Attribute to determine whether it is generated in the where clause:

Hibernate: select this_.id as id0_0_, this_.name as name0_0_, this_.age as age0_0_ from T_USER this_ where (this_.age=?)

Set the SQL template
If you understand How to write SQL statements. If you want to set some templates for Hibernate to generate SQL, you can also use the sqlRestriction() method of Restrictions to provide SQL syntax templates for qualified queries, such as querying data whose name starts with cater:

    Criteria criteria = session. createCriteria(User.class); 
    criteria.add(Restrictions.sqlRestriction( 
    "{alias}.name LIKE (?)", "cater%", Hibernate.STRING)); 
    List users = criteria.list();

where alias will be replaced with the name associated with the User category and ? Cater%, that is, the value provided by the second parameter, the first parameter of the sqlRestriction() method is set to the part of the where clause, so when writing SQL, it is not necessary to write where, and observe the generated The SQL statement will use the SQL template you set as the basis to complete the SQL conditional query:

Hibernate: select this_.id as id0_0_, this_.name as name0_0_, this_.age as age0_0_ from T_USER this_ where this_.name LIKE (?)

If there are multiple query conditions, such as the query of the between clause, it can be as follows:

    Criteria criteria = session.createCriteria(User.class); 
    Integer[] ages = {new Integer(20), new Integer(40) }; 
    Type[] types = {Hibernate.INTEGER, Hibernate.INTEGER}; 
    criteria.add(Restrictions.sqlRestriction( 
    "{alias}.age BETWEEN (?) AND (?)", ages, types)); 
    List users = criteria.list();

Observe the resulting SQL statement as follows:

Hibernate: select this_.id as id0_0_, this_.name as name0_0_, this_.age as age0_0_ from T_USER this_ where this_.age BETWEEN (?) AND ( ?)





2. Connection Limits Use FetchMode

in Criteria queries to implement connection limits. In the HQL statement, the fetch keyword can be used to indicate early fetching (Eager fetching), as follows:

from Group g
left join fetch g.students s
where g.name like '%2005'

The same can be done using Criteria's API function as follows:

Criteria cr = session.createCriteria(Group.class);
cr.setFetchMode("students", FetchMode.EAGER);
cr.add(Restrictions.like("name", "2005", MatchMode. END))
List list = cr.list();

The code written in the above two ways uses the same SQL statement to complete their functions, as follows:

select g.*, s.* from Group g
left outer join Student s
on g.id = s.group_id
where g.name like '%2005'

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326679391&siteId=291194637