Skip to main content

Use Criteria in Hibernate to implement background paging method

Mr.ChenLess than 1 minutearticleJava

In hibernate, use criteria to implement the background paging method, let's not talk about it and just look at the program.

The following first obtains the list of records according to the query conditions and the number of records per page:

/**
   * Get the log list according to different conditions
   * @param inter interface name
   * @param firstResult start record
   * @param maxResult The maximum number of records displayed per page
   * @return
*/
public List<UipInterfaceLog> getUipInterfaceLogsByCondition (String inter, int firstResult, int maxResult) {
   List<UipInterfaceLog> result = null;
   Criteria criteria = this.getSession().createCriteria(UipInterfaceLog.class);
   criteria.add(Restrictions.like("inter", inter));
   criteria. setFirstResult(firstResult);
   criteria. setMaxResults(maxResult);
   result = criteria. list();
   return result;
}

Here, for the sake of brevity, I removed the other conditions of the query, you can add it yourself when you use it, and you can replace Object.class with the corresponding entity when you use it.

The following is the total number of records that meet the conditions

/**
   * Get the total number of records according to the condition
   * @param inter
*/
public int getUipInterfaceLogsByCondition (String inter) {
   List<UipInterfaceLog> result = null;
   Criteria criteria = this. getSession(). createCriteria(Object. class);
   criteria.add(Restrictions.like("inter", inter));
// return criteria.list().size; must not be written like this, if written like this, as the number of records in the database increases, more and more objects will be created each time, and the execution speed of this method will become slower and slower, eventually It will cause memory overflow and cause the system to crash.
   return ((Integer) criteria. setProjection(Projections. rowCount()). uniqueResult()). intValue();
}

There are so many codes, it is easy to understand.

This article is transferred from: http://jiaxy917.javaeye.com/blog/452157open in new window