方法一:/**
* 分页1
*/
/**
* @param sql
* mysql原生sql语句
* @param pageNo
* 第几页
* @param pageSize
* 一页显示多少条
* @param c
* 返回的对象类型
* @return
*/
protected <K> Map<String, Object> getMapDataBySQl(String sql, Integer pageNo, int pageSize, Class<K> c) {
if (pageNo == null || pageNo < 1)
pageNo = 1;
int index = getSQLSubIndex(sql);
if (index == 0)
return new HashMap<String, Object>();
String countStr = sql.substring(index);
countStr = "select count(*) " + countStr;
// 获取总数
long count = 0;
try {
count = Long.parseLong(getCurrentSession().createSQLQuery(countStr).list().get(0).toString());
} catch (Exception e) {
count = 0;
}
long pageCount = (count % pageSize == 0 ? count / pageSize : count / pageSize + 1);
// 设置返回值
Map<String, Object> result = new HashMap<String, Object>();
sql += " limit " + (pageNo - 1) * pageSize + "," + pageSize;
@SuppressWarnings("unchecked")
List<K> dataProperty = getCurrentSession().createSQLQuery(sql).addEntity(c).list();
result.put("pageCount", pageCount);
result.put("totalSize", count);
result.put("data", dataProperty);
return result;
}
private int getSQLSubIndex(String sql) {
int upperIndex = sql.indexOf("FROM", 0) == -1 ? 0 : sql.indexOf("FROM", 0);
int lowerIndex = sql.indexOf("from", 0) == -1 ? 0 : sql.indexOf("from", 0);
int index = 0;
if (lowerIndex == 0)
index = upperIndex;
if (upperIndex == 0)
index = lowerIndex;
if (lowerIndex != 0 && upperIndex != 0)
index = Math.min(lowerIndex, upperIndex);
return index;
}
方法二:
protected Map<String, Object> getMapData(StringBuffer sql, Integer pageNo, int pageSize) {
if (pageNo == null || pageNo < 1)
pageNo = 1;
// 获取总数
long count = getRowsNew(sql.toString(), null, null);
int pageCount = (int) (count % pageSize == 0 ? count / pageSize : count / pageSize + 1);
// 设置返回值
Map<String, Object> result = new HashMap<String, Object>();
List<T> dataProperty = findListPage(sql.toString(), null, (pageNo - 1) * pageSize, pageSize);
if (dataProperty == null || dataProperty.size() == 0) {
result.put("pageCount", pageCount);
result.put("totalSize", count);
result.put("data", dataProperty);
return result;
}
result.put("pageCount", pageCount);
result.put("totalSize", count);
result.put("data", dataProperty);
return result;
}
//这是调用的底层的方法
public long getRowsNew(String query, Map<String, Object> params, Class<?> entityClass) {
String queryString = "select count(*) ";
if (query != null) {
queryString = queryString + " " + query;
}
Query q = this.sessionFactory.getCurrentSession().createQuery(queryString);
if (params != null) {
q.setProperties(params);
}
return (Long) q.list().get(0);
}
public List<T> findListPage(String hql, Map<String, Object> params, int first, int max) {
Query query = this.sessionFactory.getCurrentSession().createQuery(hql);
query.setProperties(params);
query.setFirstResult(first);
query.setMaxResults(max);
return query.list();
}