After sending the Hibernate query standard (Criteria) query page, a single record, and sorting, some netizens replied that the total number of data queries was reached. Today I will add the aggregation and grouping in the standard query.
Querying the number of records is simple:
Java code
Criteria crit = session. createCriteria (User. class );
Crit. setProjection (Projections. rowCount ());
Int v = (Integer) crit. uniqueResult ();
Note that the setProjection method is only valid for the last time. That is to say, you can use this method multiple times, but the next operation will overwrite the previous aggregation operation.
Java code
Criteria crit = session. createCriteria (User. class );
Crit. setProjection (Projections. rowCount ());
Int value = (Integer) crit. uniqueResult ();
System. out. println (value );
Crit. setProjection (Projections. max ("id "));
Value = (Integer) crit. uniqueResult ();
System. out. println (value );
Crit. setProjection (Projections. sum ("id "));
Value = (Integer) crit. uniqueResult ();
System. out. println (value );
The preceding three query operations are performed:
SQL code
Select count (*) from user
Select max (id) from user
Select sum (id) from user
To set multiple aggregation operations, see the following example:
Java code
ProjectionList proList = Projections. projectionList ();
ProList. add (Projections. rowCount ());
ProList. add (Projections. max ("id "));
ProList. add (Projections. sum ("id "));
Crit. setProjection (proList );
List results = crit. list ();
Object [] arr = (Object []) results. get (0 );
For (Object ob: arr ){
System. out. println (ob. toString ());
}
Run the following SQL statement:
SQL code
Select count (*), max (id), sum (id) from user
If you look at the Projections class, you can also see the grouping method:
Java code
Criteria crit = session. createCriteria (User. class );
Crit. setProjection (Projections. rowCount ());
Crit. setProjection (Projections. groupProperty ("name "));
List results = crit. list ();
Object [] arr = null;
For (int I = 0; I <results. size (); I ++ ){
Arr = (Object []) results. get (I );
For (Object ob: arr ){
System. out. print (ob. toString ());
}
System. out. println ();
}
The preceding SQL statement is executed:
SQL code
Select count (*) from user group by name
You can try it yourself!
Author: dylove98