最近笔者在研究一套系统(jeeCMS)的源码,看到他对于hibernate的封装,顿时生出一种惊为天人的感觉,特与诸君分享。
这里面用到了两个基础知识,笔者在这里列一下,对于hibernate不熟悉读者可以先看下面两几篇博客:
hibernate基本操作:https://www.cnblogs.com/jack1995/p/6952704.html
hibernate Criteria查询操作:https://www.cnblogs.com/liujiayun/p/5796288.html
废话不多说,上代码了。
hibernate封装基类,HibernateSimpleDao ,提供hql分页查询,不带泛型,与具体实体类无关。
package com.jeecms.common.hibernate4;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.internal.CriteriaImpl;
import org.hibernate.transform.ResultTransformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import com.jeecms.common.page.Pagination;
import com.jeecms.common.util.MyBeanUtils;
/**
* hibernate DAO基类
*
* 提供hql分页查询,不带泛型,与具体实体类无关。
*/
public abstract class HibernateSimpleDao {
/**
* 日志,可用于子类
*/
protected Logger log = LoggerFactory.getLogger(getClass());
/**
* HIBERNATE 的 order 属性
*/
protected static final String ORDER_ENTRIES = "orderEntries";
/**
* 通过HQL查询对象列表
*
* @param hql
* hql语句
* @param values
* 数量可变的参数
*/
@SuppressWarnings("unchecked")
protected List find(String hql, Object... values) {
return createQuery(hql, values).list();
}
/**
* 通过HQL查询唯一对象
*/
protected Object findUnique(String hql, Object... values) {
return createQuery(hql, values).uniqueResult();
}
/**
* 通过Finder获得分页数据
*
* @param finder
* Finder对象
* @param pageNo
* 页码
* @param pageSize
* 每页条数
* @return
*/
protected Pagination find(Finder finder, int pageNo, int pageSize) {
int totalCount = countQueryResult(finder);
Pagination p = new Pagination(pageNo, pageSize, totalCount);
if (totalCount < 1) {
p.setList(new ArrayList());
return p;
}
Query query = getSession().createQuery(finder.getOrigHql());
finder.setParamsToQuery(query);
query.setFirstResult(p.getFirstResult());//分页参数
query.setMaxResults(p.getPageSize());//分页参数
if (finder.isCacheable()) {
query.setCacheable(true);
}
List list = query.list();
p.setList(list);
return p;
}
protected Pagination findBigData(Finder finder, int pageNo, int pageSize) {
int totalCount = pageNo*pageSize;
Pagination p = new Pagination(pageNo, pageSize, totalCount);
Query query = getSession().createQuery(finder.getOrigHql());
finder.setParamsToQuery(query);
query.setFirstResult(p.getFirstResult());
query.setMaxResults(p.getPageSize());
if (finder.isCacheable()) {
query.setCacheable(true);
}
List list = query.list();
p.setList(list);
return p;
}
protected Pagination findBigDataPage(Finder finder, int pageNo, int pageSize) {
int totalCount = countQueryResult(finder);
Pagination p = new Pagination(pageNo, pageSize, totalCount);
if (totalCount < 1) {
p.setList(new ArrayList());
return p;
}
Query query = getSession().createQuery(finder.getOrigHql());
finder.setParamsToQuery(query);
query.setFirstResult(p.getFirstResult());
query.setMaxResults(p.getPageSize());
if (finder.isCacheable()) {
query.setCacheable(true);
}
return p;
}
protected Pagination findByGroup(Finder finder,String selectSql, int pageNo, int pageSize) {
return findByTotalCount(finder, pageNo, pageSize, countQueryResultByGroup(finder,selectSql));
}
/**
* 通过Finder获得列表数据
*
* @param finder
* @return
*/
@SuppressWarnings("unchecked")
protected List find(Finder finder) {
Query query = finder.createQuery(getSession());
List list = query.list();
return list;
}
/**
* 根据查询函数与参数列表创建Query对象,后续可进行更多处理,辅助函数.
*/
protected Query createQuery(String queryString, Object... values) {
Assert.hasText(queryString);//这是个好东西
Query queryObject = getSession().createQuery(queryString);
if (values != null) {
for (int i = 0; i < values.length; i++) {
queryObject.setParameter(i, values[i]);
}
}
return queryObject;
}
/**
* 通过Criteria获得分页数据
*
* @param crit
* @param pageNo
* @param pageSize
* @param projection
* @param orders
* @return
*/
@SuppressWarnings("unchecked")
protected Pagination findByCriteria(Criteria crit, int pageNo, int pageSize) {
CriteriaImpl impl = (CriteriaImpl) crit;
// 先把Projection、ResultTransformer、OrderBy取出来,清空三者后再执行Count操作
Projection projection = impl.getProjection();
ResultTransformer transformer = impl.getResultTransformer();
List<CriteriaImpl.OrderEntry> orderEntries;
try {
orderEntries = (List) MyBeanUtils
.getFieldValue(impl, ORDER_ENTRIES);
MyBeanUtils.setFieldValue(impl, ORDER_ENTRIES, new ArrayList());
} catch (Exception e) {
throw new RuntimeException(
"cannot read/write 'orderEntries' from CriteriaImpl", e);
}
int totalCount = ((Number) crit.setProjection(Projections.rowCount())
.uniqueResult()).intValue();
Pagination p = new Pagination(pageNo, pageSize, totalCount);
if (totalCount < 1) {
p.setList(new ArrayList());
return p;
}
// 将之前的Projection,ResultTransformer和OrderBy条件重新设回去
crit.setProjection(projection);
if (projection == null) {
crit.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
}
if (transformer != null) {
crit.setResultTransformer(transformer);
}
try {
MyBeanUtils.setFieldValue(impl, ORDER_ENTRIES, orderEntries);
} catch (Exception e) {
throw new RuntimeException(
"set 'orderEntries' to CriteriaImpl faild", e);
}
crit.setFirstResult(p.getFirstResult());
crit.setMaxResults(p.getPageSize());
p.setList(crit.list());
return p;
}
/**
* 获得Finder的记录总数
*
* @param finder
* @return
*/
protected int countQueryResult(Finder finder) {
Query query = getSession().createQuery(finder.getRowCountHql());
finder.setParamsToQuery(query);
if (finder.isCacheable()) {
query.setCacheable(true);
}
return ((Number) query.iterate().next()).intValue();
}
protected int countQueryResultByGroup(Finder finder,String selectSql) {
Query query = getSession().createQuery(finder.getRowCountTotalHql(selectSql));
setParamsToQuery(finder, query);
return ((Number) query.iterate().next()).intValue();
}
private Pagination findByTotalCount(Finder finder, int pageNo, int pageSize,int totalCount) {
Pagination p = new Pagination(pageNo, pageSize, totalCount);
if (totalCount < 1) {
p.setList(new ArrayList());
return p;
}
Query query = getSession().createQuery(finder.getOrigHql());
finder.setParamsToQuery(query);
query.setFirstResult(p.getFirstResult());
query.setMaxResults(p.getPageSize());
if (finder.isCacheable()) {
query.setCacheable(true);
}
List list = query.list();
p.setList(list);
return p;
}
private Query setParamsToQuery(Finder finder,Query query){
finder.setParamsToQuery(query);
if (finder.isCacheable()) {
query.setCacheable(true);
}
return query;
}
protected SessionFactory sessionFactory;
@Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
protected Session getSession() {
return sessionFactory.getCurrentSession();
}
}
基于HibernateSimpleDao的拓展,HibernateBaseDao,提供hql分页查询,拷贝更新等一些常用功能。
package com.jeecms.common.hibernate4;
import java.io.Serializable;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.metadata.ClassMetadata;
import org.springframework.util.Assert;
import com.jeecms.common.util.MyBeanUtils;
/**
* hibernate DAO基类
*
* 提供hql分页查询,拷贝更新等一些常用功能。
* @param <T>
* entity class
* @param <ID>
* entity id
*/
public abstract class HibernateBaseDao<T, ID extends Serializable> extends
HibernateSimpleDao {
/**
* @see Session.get(Class,Serializable)
* @param id
* @return 持久化对象
*/
protected T get(ID id) {
return get(id, false);
}
/**
* @see Session.get(Class,Serializable,LockMode)
* @param id
* 对象ID
* @param lock
* 是否锁定,使用LockMode.UPGRADE
* @return 持久化对象
*/
@SuppressWarnings("unchecked")
protected T get(ID id, boolean lock) {
T entity;
if (lock) {
//entity = (T) getSession().get(getEntityClass(), id,LockMode.UPGRADE);
entity = (T) getSession().get(getEntityClass(), id, LockMode.PESSIMISTIC_WRITE);
} else {
entity = (T) getSession().get(getEntityClass(), id);
}
return entity;
}
/**
* 按属性查找对象列表
*/
@SuppressWarnings("unchecked")
protected List<T> findByProperty(String property, Object value) {
Assert.hasText(property);
return createCriteria(Restrictions.eq(property, value)).list();
}
/**
* 按属性查找唯一对象
*/
@SuppressWarnings("unchecked")
protected T findUniqueByProperty(String property, Object value) {
Assert.hasText(property);
Assert.notNull(value);
return (T) createCriteria(Restrictions.eq(property, value))
.uniqueResult();
}
/**
* 按属性统计记录数
*
* @param property
* @param value
* @return
*/
protected int countByProperty(String property, Object value) {
Assert.hasText(property);
Assert.notNull(value);
return ((Number) (createCriteria(Restrictions.eq(property, value))
.setProjection(Projections.rowCount()).uniqueResult()))
.intValue();
}
/**
* 按Criterion查询列表数据.
*
* @param criterion
* 数量可变的Criterion.
*/
protected List findByCriteria(Criterion... criterion) {
return createCriteria(criterion).list();
}
/**
* 通过Updater更新对象
*
* @param updater
* @return
*/
@SuppressWarnings("unchecked")
public T updateByUpdater(Updater<T> updater) {
ClassMetadata cm = sessionFactory.getClassMetadata(getEntityClass());
T bean = updater.getBean();
//T po = (T) getSession().get(getEntityClass(),cm.getIdentifier(bean, POJO));
T po = (T) getSession().get(getEntityClass(),cm.getIdentifier(bean,(SessionImplementor) sessionFactory.getCurrentSession()));
updaterCopyToPersistentObject(updater, po, cm);
return po;
}
/**
* 将更新对象拷贝至实体对象,并处理many-to-one的更新。
*
* @param updater
* @param po
*/
private void updaterCopyToPersistentObject(Updater<T> updater, T po,
ClassMetadata cm) {
String[] propNames = cm.getPropertyNames();
String identifierName = cm.getIdentifierPropertyName();
T bean = updater.getBean();
Object value;
for (String propName : propNames) {
if (propName.equals(identifierName)) {
continue;
}
try {
value = MyBeanUtils.getSimpleProperty(bean, propName);
if (!updater.isUpdate(propName, value)) {
continue;
}
//cm.setPropertyValue(po, propName, value, POJO);
cm.setPropertyValue(po, propName, value);
} catch (Exception e) {
throw new RuntimeException(
"copy property to persistent object failed: '"
+ propName + "'", e);
}
}
}
/**
* 根据Criterion条件创建Criteria,后续可进行更多处理,辅助函数.
*/
protected Criteria createCriteria(Criterion... criterions) {
Criteria criteria = getSession().createCriteria(getEntityClass());
for (Criterion c : criterions) {
criteria.add(c);
}
//设置可查询缓存
criteria.setCacheable(true);
return criteria;
}
/**
* 获得Dao对于的实体类
*
* @return
*/
abstract protected Class<T> getEntityClass();
}
这里面用到了一个工具类MyBeanUtils,在这里也一并分享给大家,
package com.jeecms.common.util;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.Locale;
import org.springframework.util.Assert;
public class MyBeanUtils {
/**
* 直接读取对象属性值,无视private/protected修饰符,不经过getter函数.
*/
public static Object getFieldValue(final Object object,
final String fieldName) {
Field field = getDeclaredField(object, fieldName);
if (field == null) {
throw new IllegalArgumentException("Could not find field ["
+ fieldName + "] on target [" + object + "]");
}
makeAccessible(field);
Object result = null;
try {
result = field.get(object);
} catch (IllegalAccessException e) {
throw new RuntimeException("never happend exception!", e);
}
return result;
}
/**
* 直接设置对象属性值,无视private/protected修饰符,不经过setter函数.
*/
public static void setFieldValue(final Object object,
final String fieldName, final Object value) {
Field field = getDeclaredField(object, fieldName);
if (field == null) {
throw new IllegalArgumentException("Could not find field ["
+ fieldName + "] on target [" + object + "]");
}
makeAccessible(field);
try {
field.set(object, value);
} catch (IllegalAccessException e) {
throw new RuntimeException("never happend exception!", e);
}
}
/**
* 循环向上转型,获取对象的DeclaredField.
*/
protected static Field getDeclaredField(final Object object,
final String fieldName) {
Assert.notNull(object);
return getDeclaredField(object.getClass(), fieldName);
}
/**
* 循环向上转型,获取类的DeclaredField.
*/
protected static Field getDeclaredField(final Class<?> clazz,
final String fieldName) {
Assert.notNull(clazz);
Assert.hasText(fieldName);
for (Class<?> superClass = clazz; superClass != Object.class; superClass = superClass
.getSuperclass()) {
try {
return superClass.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
// Field不在当前类定义,继续向上转型
}
}
return null;
}
/**
* 强制转换fileld可访问.
*/
protected static void makeAccessible(final Field field) {
if (!Modifier.isPublic(field.getModifiers())
|| !Modifier.isPublic(field.getDeclaringClass().getModifiers())) {
field.setAccessible(true);
}
}
public static Object getSimpleProperty(Object bean, String propName)
throws IllegalArgumentException, SecurityException,
IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
return bean.getClass().getMethod(getReadMethod(propName)).invoke(bean);
}
private static String getReadMethod(String name) {
return "get" + name.substring(0, 1).toUpperCase(Locale.ENGLISH)
+ name.substring(1);
}
}
分页查询工具类Finder:
package com.jeecms.common.hibernate4;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.type.Type;
/**
* HQL语句分页查询
*/
public class Finder {
protected Finder() {
hqlBuilder = new StringBuilder();
}
protected Finder(String hql) {
hqlBuilder = new StringBuilder(hql);
}
public static Finder create() {
return new Finder();
}
public static Finder create(String hql) {
return new Finder(hql);
}
public Finder append(String hql) {
hqlBuilder.append(hql);
return this;
}
/**
* 获得原始hql语句
*
* @return
*/
public String getOrigHql() {
return hqlBuilder.toString();
}
/**
* 获得查询数据库记录数的hql语句。
*
* @return
*/
public String getRowCountHql() {
return getRowCountBaseHql(ORDER_BY);
}
public String getRowCountTotalHql(String selectSql) {
return getRowCountTotalBaseHql(ORDER_BY,selectSql);
}
public String getRowCountHqlByGroup() {
return getRowCountBaseHql(GROUP_BY);
}
public int getFirstResult() {
return firstResult;
}
public void setFirstResult(int firstResult) {
this.firstResult = firstResult;
}
public int getMaxResults() {
return maxResults;
}
public void setMaxResults(int maxResults) {
this.maxResults = maxResults;
}
/**
* 是否使用查询缓存
*
* @return
*/
public boolean isCacheable() {
return cacheable;
}
/**
* 设置是否使用查询缓存
*
* @param cacheable
* @see Query#setCacheable(boolean)
*/
public void setCacheable(boolean cacheable) {
this.cacheable = cacheable;
}
/**
* 设置参数
*
* @param param
* @param value
* @return
* @see Query#setParameter(String, Object)
*/
public Finder setParam(String param, Object value) {
return setParam(param, value, null);
}
/**
* 设置参数。与hibernate的Query接口一致。
*
* @param param
* @param value
* @param type
* @return
* @see Query#setParameter(String, Object, Type)
*/
public Finder setParam(String param, Object value, Type type) {
getParams().add(param);
getValues().add(value);
getTypes().add(type);
return this;
}
/**
* 设置参数。与hibernate的Query接口一致。
*
* @param paramMap
* @return
* @see Query#setProperties(Map)
*/
public Finder setParams(Map<String, Object> paramMap) {
for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
setParam(entry.getKey(), entry.getValue());
}
return this;
}
/**
* 设置参数。与hibernate的Query接口一致。
*
* @param name
* @param vals
* @param type
* @return
* @see Query#setParameterList(String, Collection, Type))
*/
public Finder setParamList(String name, Collection<Object> vals, Type type) {
getParamsList().add(name);
getValuesList().add(vals);
getTypesList().add(type);
return this;
}
/**
* 设置参数。与hibernate的Query接口一致。
*
* @param name
* @param vals
* @return
* @see Query#setParameterList(String, Collection)
*/
public Finder setParamList(String name, Collection<Object> vals) {
return setParamList(name, vals, null);
}
/**
* 设置参数。与hibernate的Query接口一致。
*
* @param name
* @param vals
* @param type
* @return
* @see Query#setParameterList(String, Object[], Type)
*/
public Finder setParamList(String name, Object[] vals, Type type) {
getParamsArray().add(name);
getValuesArray().add(vals);
getTypesArray().add(type);
return this;
}
/**
* 设置参数。与hibernate的Query接口一致。
*
* @param name
* @param vals
* @return
* @see Query#setParameterList(String, Object[])
*/
public Finder setParamList(String name, Object[] vals) {
return setParamList(name, vals, null);
}
/**
* 将finder中的参数设置到query中。
*
* @param query
*/
public Query setParamsToQuery(Query query) {
if (params != null) {
for (int i = 0; i < params.size(); i++) {
if (types.get(i) == null) {
query.setParameter(params.get(i), values.get(i));
} else {
query.setParameter(params.get(i), values.get(i), types
.get(i));
}
}
}
if (paramsList != null) {
for (int i = 0; i < paramsList.size(); i++) {
if (typesList.get(i) == null) {
query
.setParameterList(paramsList.get(i), valuesList
.get(i));
} else {
query.setParameterList(paramsList.get(i),
valuesList.get(i), typesList.get(i));
}
}
}
if (paramsArray != null) {
for (int i = 0; i < paramsArray.size(); i++) {
if (typesArray.get(i) == null) {
query.setParameterList(paramsArray.get(i), valuesArray
.get(i));
} else {
query.setParameterList(paramsArray.get(i), valuesArray
.get(i), typesArray.get(i));
}
}
}
return query;
}
public Query createQuery(Session s) {
Query query = setParamsToQuery(s.createQuery(getOrigHql()));
if (getFirstResult() > 0) {
query.setFirstResult(getFirstResult());
}
if (getMaxResults() > 0) {
query.setMaxResults(getMaxResults());
}
if (isCacheable()) {
query.setCacheable(true);
}
return query;
}
private String getRowCountBaseHql(String indexKey) {
String hql = hqlBuilder.toString();
int fromIndex = hql.toLowerCase().indexOf(FROM);
String projectionHql = hql.substring(0, fromIndex);
hql = hql.substring(fromIndex);
String rowCountHql = hql.replace(HQL_FETCH, "");
int index = rowCountHql.indexOf(indexKey);
if (index > 0) {
rowCountHql = rowCountHql.substring(0, index);
}
return wrapProjection(projectionHql) + rowCountHql;
}
private String getRowCountTotalBaseHql(String indexKey,String selectSql) {
String hql = hqlBuilder.toString();
int fromIndex = hql.toLowerCase().indexOf(FROM);
String projectionHql = hql.substring(0, fromIndex);
hql = hql.substring(fromIndex);
String rowCountHql = hql.replace(HQL_FETCH, "");
int index = rowCountHql.indexOf(indexKey);
if (index > 0) {
rowCountHql = rowCountHql.substring(0, index);
}
//return selectSql+"( "+wrapProjectionBeanId(projectionHql)+rowCountHql+")";
return "select count(bean) from "+"( "+projectionHql+rowCountHql+") as a";
}
private String wrapProjection(String projection) {
if (projection.indexOf("select") == -1) {
return ROW_COUNT;
} else {
return projection.replace("select", "select count(") + ") ";
}
}
@SuppressWarnings("unused")
private String wrapProjectionBeanId(String projection) {
if (projection.indexOf("select") == -1) {
return "select bean.id ";
} else {
return projection.replace("select bean", "select bean.id") + " ";
}
}
private List<String> getParams() {
if (params == null) {
params = new ArrayList<String>();
}
return params;
}
private List<Object> getValues() {
if (values == null) {
values = new ArrayList<Object>();
}
return values;
}
private List<Type> getTypes() {
if (types == null) {
types = new ArrayList<Type>();
}
return types;
}
private List<String> getParamsList() {
if (paramsList == null) {
paramsList = new ArrayList<String>();
}
return paramsList;
}
private List<Collection<Object>> getValuesList() {
if (valuesList == null) {
valuesList = new ArrayList<Collection<Object>>();
}
return valuesList;
}
private List<Type> getTypesList() {
if (typesList == null) {
typesList = new ArrayList<Type>();
}
return typesList;
}
private List<String> getParamsArray() {
if (paramsArray == null) {
paramsArray = new ArrayList<String>();
}
return paramsArray;
}
private List<Object[]> getValuesArray() {
if (valuesArray == null) {
valuesArray = new ArrayList<Object[]>();
}
return valuesArray;
}
private List<Type> getTypesArray() {
if (typesArray == null) {
typesArray = new ArrayList<Type>();
}
return typesArray;
}
private StringBuilder hqlBuilder;
private List<String> params;
private List<Object> values;
private List<Type> types;
private List<String> paramsList;
private List<Collection<Object>> valuesList;
private List<Type> typesList;
private List<String> paramsArray;
private List<Object[]> valuesArray;
private List<Type> typesArray;
private int firstResult = 0;
private int maxResults = 0;
private boolean cacheable = false;
public static final String ROW_COUNT = "select count(*) ";
public static final String FROM = "from";
public static final String DISTINCT = "distinct";
public static final String HQL_FETCH = "fetch";
public static final String ORDER_BY = "order ";
public static final String GROUP_BY = "group";
public static void main(String[] args) {
Finder find = Finder
.create("select distinct p FROM BookType join fetch p");
System.out.println(find.getRowCountHql());
System.out.println(find.getOrigHql());
}
}
对于分页实体类的封装:
分页接口Paginable :
package com.jeecms.common.page;
/**
* 分页接口
*/
public interface Paginable {
/**
* 总记录数
*
* @return
*/
public int getTotalCount();
/**
* 总页数
*
* @return
*/
public int getTotalPage();
/**
* 每页记录数
*
* @return
*/
public int getPageSize();
/**
* 当前页号
*
* @return
*/
public int getPageNo();
/**
* 是否第一页
*
* @return
*/
public boolean isFirstPage();
/**
* 是否最后一页
*
* @return
*/
public boolean isLastPage();
/**
* 返回下页的页号
*/
public int getNextPage();
/**
* 返回上页的页号
*/
public int getPrePage();
}
对于Paginable的基本实现类SimplePage:
package com.jeecms.common.page;
/**
* 简单分页类
*/
public class SimplePage implements Paginable {
public static final int DEF_COUNT = 20;
/**
* 检查页码 checkPageNo
*
* @param pageNo
* @return if pageNo==null or pageNo<1 then return 1 else return pageNo
*/
public static int cpn(Integer pageNo) {
return (pageNo == null || pageNo < 1) ? 1 : pageNo;
}
public SimplePage() {
}
/**
* 构造器
*
* @param pageNo
* 页码
* @param pageSize
* 每页几条数据
* @param totalCount
* 总共几条数据
*/
public SimplePage(int pageNo, int pageSize, int totalCount) {
setTotalCount(totalCount);
setPageSize(pageSize);
setPageNo(pageNo);
adjustPageNo();
}
/**
* 调整页码,使不超过最大页数
*/
public void adjustPageNo() {
if (pageNo == 1) {
return;
}
int tp = getTotalPage();
if (pageNo > tp) {
pageNo = tp;
}
}
/**
* 获得页码
*/
public int getPageNo() {
return pageNo;
}
/**
* 每页几条数据
*/
public int getPageSize() {
return pageSize;
}
/**
* 总共几条数据
*/
public int getTotalCount() {
return totalCount;
}
/**
* 总共几页
*/
public int getTotalPage() {
int totalPage = totalCount / pageSize;
if (totalPage == 0 || totalCount % pageSize != 0) {
totalPage++;
}
return totalPage;
}
/**
* 是否第一页
*/
public boolean isFirstPage() {
return pageNo <= 1;
}
/**
* 是否最后一页
*/
public boolean isLastPage() {
return pageNo >= getTotalPage();
}
/**
* 下一页页码
*/
public int getNextPage() {
if (isLastPage()) {
return pageNo;
} else {
return pageNo + 1;
}
}
/**
* 上一页页码
*/
public int getPrePage() {
if (isFirstPage()) {
return pageNo;
} else {
return pageNo - 1;
}
}
protected int totalCount = 0;
protected int pageSize = 20;
protected int pageNo = 1;
/**
* if totalCount<0 then totalCount=0
*
* @param totalCount
*/
public void setTotalCount(int totalCount) {
if (totalCount < 0) {
this.totalCount = 0;
} else {
this.totalCount = totalCount;
}
}
/**
* if pageSize< 1 then pageSize=DEF_COUNT
*
* @param pageSize
*/
public void setPageSize(int pageSize) {
if (pageSize < 1) {
this.pageSize = DEF_COUNT;
} else {
this.pageSize = pageSize;
}
}
/**
* if pageNo < 1 then pageNo=1
*
* @param pageNo
*/
public void setPageNo(int pageNo) {
if (pageNo < 1) {
this.pageNo = 1;
} else {
this.pageNo = pageNo;
}
}
}
还有Pagination
package com.jeecms.common.page;
import java.util.List;
/**
* 列表分页。包含list属性。
*/
@SuppressWarnings("serial")
public class Pagination extends SimplePage implements java.io.Serializable,
Paginable {
public Pagination() {
}
/**
* 构造器
*
* @param pageNo
* 页码
* @param pageSize
* 每页几条数据
* @param totalCount
* 总共几条数据
*/
public Pagination(int pageNo, int pageSize, int totalCount) {
super(pageNo, pageSize, totalCount);
}
/**
* 构造器
*
* @param pageNo
* 页码
* @param pageSize
* 每页几条数据
* @param totalCount
* 总共几条数据
* @param list
* 分页内容
*/
public Pagination(int pageNo, int pageSize, int totalCount, List<?> list) {
super(pageNo, pageSize, totalCount);
this.list = list;
}
/**
* 第一条数据位置
*
* @return
*/
public int getFirstResult() {
return (pageNo - 1) * pageSize;
}
/**
* 当前页的数据
*/
private List<?> list;
/**
* 获得分页内容
*
* @return
*/
public List<?> getList() {
return list;
}
/**
* 设置分页内容
*
* @param list
*/
public void setList(List list) {
this.list = list;
}
}
就此hibernate的封装与基本的分页封装就到此结束了,愿诸君喜欢。