Hibernate中用普通的sql语句实现分页查询

1.特征:就是普通的sql语句


QueryResult q = devicecalibratecurveManager.getScrollDateByNativeSQL(startIndex, maxIndex, fieldSQL, tableSQL, whereSB.toString(), params.toArray(), orderby);


2.实现类


/*
 * 原生SQL分页查询或实体SQL分页查询
 * 
 * @param startIndex 分页的起始位置
 * 
 * @param maxResult 每页显示的记录数
 * 
 * @param searchField 所查询的字段
 * 
 * @param fromSQL 查询的表
 * 
 * @param whereSQL 查询条件
 * 
 * @param params 参数值
 * 
 * @param orderby 排序字段
 * 
 * @return QueryResult
 */
@SuppressWarnings("unchecked")
// @Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
public QueryResult getScrollDateByNativeSQL(int startIndex,
int maxResult, String searchField, String fromSQL, String whereSQL,
Object[] params, LinkedHashMap orderby)
throws Exception {


QueryResult qr = new QueryResult();


SQLQuery query = null;
String where = (whereSQL != null && !"".equals(whereSQL.trim())) ? " where "
+ whereSQL
: "";
String nativeSQl = "select " + searchField + " from " + fromSQL + where
+ buildSqlOrderBy(orderby);


query = createSQLQuery(nativeSQl, params);
if (startIndex != -1 && maxResult != -1)
query.setFirstResult(startIndex).setMaxResults(maxResult);
qr.setResultlist(query.list());


String countString = "";
if (searchField.indexOf("distinct") != -1) {

countString = "select " + searchField + " from " + fromSQL + where
+ "  ";
query = createSQLQuery(countString, params);
qr.setTotalrecord(query.list().size());
} else {
countString = "select count(*) from " + fromSQL + where;
query = createSQLQuery(countString, params);
qr.setTotalrecord(new Long(query.uniqueResult().toString()));
}

return qr;
}

/**
 * 生成排序SQL(原生)
 * 
 * @param orderby
 *            排序属性
 */
private static String buildSqlOrderBy(LinkedHashMap orderby) {
StringBuilder sb = new StringBuilder();
if (orderby != null && orderby.size() > 0) {
sb.append(" order by ");
for (String key : orderby.keySet()) {
sb.append(key).append(" ").append(orderby.get(key)).append(",");
}
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
/**
 * SQL方式查询
 * 
 * @param sql
 *            符合SQL语法的查询语句
 * @param values
 *            数量可变的条件值,按顺序绑定
 */
public SQLQuery createSQLQuery(final String sql, final Object... values) {
SQLQuery query = getSession().createSQLQuery(sql);


if (values != null) {
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);
}
}
return query;
}

你可能感兴趣的:(Hibernate中用普通的sql语句实现分页查询)