欢迎大家关注我的公众号【老周聊架构】,Java后端主流技术栈的原理、源码分析、架构以及各种互联网高并发、高性能、高可用的解决方案。
一、limit关键字
service层
@Service
@Transactional
public class ImplStudentService implements StudentService {
@Resource
private StudentDao studentDao;
@Override
public List<Student> selectAllStudent(String province, Integer offset, Integer limit) {
return studentDao.selectAll(province,offset,limit);
}
}
sql语句
select * from student where province = #{province} limit #{offset},#{limit}
二、hibernate分页
service层
@Override
public List getStudents(Integer pageNo,Integer pageSize) throws Exception {
// 分页数据
int[] startIdAndCount = new int[2];
startIdAndCount[0] = pageNo * pageSize;
startIdAndCount[1] = pageSize;
return studentDao.selectStudentsByPage(startIdAndCount);
}
dao层
@Override
public List findByHqlPage(int[] startIdAndCount) throws Exception {
String hql = "...";
try {
Query query = getSession().createQuery(hql);
// 设置分页
if (startIdAndCount != null && startIdAndCount.length > 0) {
int rowStartIdx = Math.max(0, startIdAndCount[0]);
if (rowStartIdx > 0) {
query.setFirstResult(rowStartIdx);// 设置开始取值的索引
}
if (startIdAndCount.length > 1) {
int rowCount = Math.max(0, startIdAndCount[1]);
if (rowCount > 0) {
query.setMaxResults(rowCount);// 设置结束取值的索引
}
}
}
return query.list();
} catch (RuntimeException re) {
log.error("分页查询失败!", re);
throw re;
}
}