1、分页逻辑
需要手动去拼装 数据总量统计sql,数据查询sql
需要将分页信息进行封装。
public static Page getPageDate(String selectSql, String countSql, String whereSql, int page, int size,Class clazz){
//1、校验参数
if (StringUtils.isBlank(selectSql) || StringUtils.isBlank(countSql)) {
log.info("参数校验失败,参数{}{}为必填项", "selectSql", "countSql");
return null;
}
if (StringUtils.isNotBlank(whereSql)) {
countSql = countSql + whereSql;
log.info("执行sql >>>>>> {},获取数据总数", countSql);
selectSql = selectSql + whereSql;
log.info("执行sql >>>>>> {},获取数据", selectSql);
log.info(selectSql);
}
//2、数据查询逻辑
try{
//从IOC容器中获取EntityManager
EntityManager entityManagerPrimary = (EntityManager) SpringUtil.getBean("entityManagerPrimary");
//清除缓存,防止缓存与数据库数据不一致问题
entityManagerPrimary.clear();
//获取数据总数
Query countQuery = entityManagerPrimary.createNativeQuery(countSql);
BigInteger totalCount = (BigInteger)countQuery.getSingleResult();
//查询数据
Query query = entityManagerPrimary.createNativeQuery(selectSql, clazz);
//设置分页信息
Pageable pageable = new PageRequest(page - 1, size);
query.setFirstResult(pageable.getOffset());
query.setMaxResults(pageable.getPageSize());
List resultList = query.getResultList();
//查询结果封装
Page data = new PageImpl<>(resultList, pageable, totalCount.longValue());
return data;
}catch (Exception e){
e.printStackTrace();
}
return null;
}