Hibernate paging Query

Source: Internet
Author: User
Tags rowcount
Package Org. heardy. dao. impl; import Java. util. list; import javax. annotation. resource; import Org. heardy. dao. genericdao; import Org. hibernate. criteria; import Org. hibernate. sessionfactory; import Org. hibernate. criterion. criteriaspecification; import Org. hibernate. criterion. detachedcriteria; import Org. hibernate. criterion. projections; import Org. springframework. stereotype. repository; import Org. springframework. Transaction. annotation. transactional; @ repository ("genericdao")/** use only unit test */@ transactionalpublic class implements genericdao {@ resourcesessionfactory sessionfactory; public object uniqueresult (detachedcriteria DC) {Criteria = dc. getexecutablecriteria (sessionfactory. getcurrentsession (); return criteria. uniqueresult ();} public list <?> Dynamicquery (detachedcriteria DC) {Criteria = dc. getexecutablecriteria (sessionfactory. getcurrentsession (); return criteria. list ();} // criteria. setprojection (projections. projectionlist (). add (projections. rowcount (); // query the total number of rows // criteria. add (projections. AVG (propertyname); // evaluate the flat value // criteria. add (projections. min (propertyname); // minimum // criteria. add (projections. max (propertyname); // maximum // CRI Teria. add (projections. sum (propertyname); // sum // criteria. add (projections. groupproperty (propertyname); // Group Public integer sum (detachedcriteria DC, string propertyname) {Criteria = dc. getexecutablecriteria (sessionfactory. getcurrentsession (); integer sum = (integer) criteria. setprojection (projections. sum (propertyname )). uniqueresult (); criteria. setprojection (null); criteria. setresulttransform Er (criteriaspecification. root_entity); // If the queried object has a foreign key, you need to add this statement return sum;} public integer count (detachedcriteria DC) {Criteria = dc. getexecutablecriteria (sessionfactory. getcurrentsession (); integer totalcount = (integer) criteria. setprojection (projections. rowcount ()). uniqueresult (); criteria. setprojection (null); criteria. setresulttransformer (criteriaspecification. root_entity); // If the queried object has a foreign key, you need to add Return totalcount;} public list <?> Pagequery (detachedcriteria DC, int limit, int start) {Criteria = dc. getexecutablecriteria (sessionfactory. getcurrentsession (); criteria. setfirstresult (start); criteria. setmaxresults (Limit); return criteria. list ();}}

package org.heardy.service.impl;import java.util.ArrayList;import java.util.List;import javax.annotation.Resource;import org.heardy.bean.PageBean;import org.heardy.dao.GenericDao;import org.heardy.service.GenericService;import org.heardy.tool.TypeChange;import org.hibernate.criterion.DetachedCriteria;import org.springframework.transaction.annotation.Propagation;import org.springframework.transaction.annotation.Transactional;@Transactionalpublic abstract class GenericServiceImpl implements GenericService {@ResourceGenericDao genericDao;@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)public PageBean findPageList(DetachedCriteria dc, PageBean page) {int count = TypeChange.objectToInt(genericDao.count(dc));@SuppressWarnings("rawtypes")List<?> purchases = new ArrayList();if (page.getLimit() != 0) {purchases = genericDao.pageQuery(dc, page.getLimit(),page.getStart());}page.setResult(count, purchases);return page;}public Integer getCount(DetachedCriteria dc) {return TypeChange.objectToInt(genericDao.count(dc));}public List<?> findAllList(DetachedCriteria dc) {return genericDao.dynamicQuery(dc);}public Object findBean(DetachedCriteria dc) {return genericDao.uniqueResult(dc);}}

In hibernate, the following method is used to query the total number;
Public integer getcount (final detachedcriteria ){
Return (integer) gethibernatetemplate(cmd.exe cute (New hibernatecallback (){

@ Override
Public object doinhibernate (session)
Throws hibernateexception, sqlexception {
Criteria = detachedcriteria. getexecutablecriteria (session );

Int totalcount = (integer) criteria. setprojection (
Projections. rowcount (). uniqueresult ();

Criteria. setprojection (null );
//
Criteria. setresulttransformer (criteriaspecification. root_entity );
Return totalcount;
}
}, True );
}

Sometimes in int totalcount = (integer) criteria. setprojection (
Projections. rowcount (). uniqueresult (); this statement reports nullpointexception.

The reason is that the sorting statement such as criteria. addorder (order. DESC ("SC. createtime") appears before this code.

Put the sorting statement behind the total number query. Sometimes when you comment out the cache, it will still be affected. You need to delete the comment statement.

 

------------------------------ Total number of general record queries -------------------------------------------
Protected <t> int countqueryresult (criteria c ){
Criteriaimpl impl = (criteriaimpl) C;

// Obtain projection, orderby, and resulttransformer first, and clear the three before performing the Count operation.
Projection projection = impl. getprojection ();

Resulttransformer transformer = impl. getresulttransformer ();
List <criteriaimpl. orderentry> orderentries;
Try {
Orderentries = (list) beanutils. forcegetproperty (impl, "orderentries ");
Beanutils. forcesetproperty (impl, "orderentries", new arraylist ());
} Catch (exception e ){
Throw new internalerror ("RunTime exception impossibility throw ");
}

// Execute count Query
Long totalcount = (long) C. setprojection (projections. rowcount (). uniqueresult ();

// Reset the previous projection and orderby conditions.
C. setprojection (projection );

If (projection = NULL ){
C. setresulttransformer (criteriaspecification. root_entity );
}

If (transformer! = NULL ){
C. setresulttransformer (transformer );
}

Try {
Beanutils. forcesetproperty (impl, "orderentries", orderentries );
} Catch (exception e ){
Throw new internalerror ("RunTime exception impossibility throw ");
}

Return integer. valueof (string. valueof (totalcount ));
}

Criteriaimpl impl = (criteriaimpl) C;

// Obtain projection, resulttransformer, and orderby first, and clear the three before performing the Count operation.
Projection projection = impl. getprojection ();
Resulttransformer transformer = impl. getresulttransformer ();

List <criteriaimpl. orderentry> orderentries = NULL;
Try {
Orderentries = (list) reflectionutils. getfieldvalue (impl, "orderentries ");
Reflectionutils. setfieldvalue (impl, "orderentries", new arraylist ());
} Catch (exception e ){
Logger. Error ("impossible thrown exception: {}", E. getmessage ());
}

// Execute count Query
Int totalcount = (integer) C. setprojection (projections. rowcount (). uniqueresult ();

// Reset the previous projection, resulttransformer, and orderby conditions.
C. setprojection (projection );

If (projection = NULL ){
C. setresulttransformer (criteriaspecification. root_entity );
}
If (transformer! = NULL ){
C. setresulttransformer (transformer );
}
Try {
Reflectionutils. setfieldvalue (impl, "orderentries", orderentries );
} Catch (exception e ){
Logger. Error ("impossible thrown exception: {}", E. getmessage ());
}

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: info-contact@alibabacloud.com 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.