1.在持久层Service中创建EntityManager对象;
@PersistenceContext
private EntityManager entityManager;
2.根据动态sql查询条目数
/*** get total.*/
public Object getResultTotalBySql(String sql) {Query query = entityManager.createNativeQuery(sql);return query.getSingleResult();
}
3.根据动态sql查询数据,T po代表映射的实体类对象
/*** get list.*/
public List<?> getResultListBySql(String sql, T po) {Query query = entityManager.createNativeQuery(sql, po.getClass());return query.getResultList();
}
//4.根据条目数,每页大小进行总页数
public Long getTotalPage(Long total, int pageSize) {return (total + pageSize - 1) / pageSize;
}
完整代码:
/*** -----------------* Custom sql queries* -----------------*/@PersistenceContextprivate EntityManager entityManager;/*** get total.*/public Object getResultTotalBySql(String sql) {Query query = entityManager.createNativeQuery(sql);return query.getSingleResult();}/*** get list.*/public List<?> getResultListBySql(String sql, T po) {Query query = entityManager.createNativeQuery(sql, po.getClass());return query.getResultList();}public Long getTotalPage(Long total, int pageSize) {return (total + pageSize - 1) / pageSize;}