Java笔记之hibernate(十三):Criteria分页

 

0.说在前面

  基于Hibernate(十二):一级缓存和二级缓存项目

1.新建CriteriaPagingTest类

package com.hibernate.demo.test;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

import com.hibernate.demo.bean.Employee;

public class CriteriaPagingTest {

    public static void main(String[] args) {
        //加载配置文件,创建会话工厂类
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        //创建会话对象
        Session session = sessionFactory.openSession();
        
        System.out.println("分页之前查询所有,便于查看效果");
        Criteria criteria = session.createCriteria(Employee.class);
        List<Employee> employees = criteria.list();
        for (Employee employee : employees) {
            System.out.println(employee.getEmpName());
        }
        
        System.out.println("分页之后......");
        //设置起始位置,从0开始
        criteria.setFirstResult(3);
        //设置每页大小
        criteria.setMaxResults(6);
        List<Employee> employees2 = criteria.list();
        for (Employee employee : employees2) {
            System.out.println(employee.getEmpName());
        }
        
        //关闭会话对象
        session.close();
        //关闭会话工厂对象
        sessionFactory.close();
    }

}

2.运行CriteriaPagingTest类

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
分页之前查询所有,便于查看效果
Hibernate: select this_.emp_id as emp1_0_0_, this_.emp_name as emp2_0_0_, this_.dept_id as dept3_0_0_ from t_employee this_
李四
王五
赵六
韩七
小明
小红
小兰
小绿
李磊
韩梅梅
简
张三
emp
分页之后......
Hibernate: select this_.emp_id as emp1_0_0_, this_.emp_name as emp2_0_0_, this_.dept_id as dept3_0_0_ from t_employee this_ limit ?, ?
韩七
小明
小红
小兰
小绿
李磊

3.总结

  (1)分页之后打印的数据第一条韩七在分页之前的数据中的索引是3;

  (2)分页之后打印的数据个数为6;

  由上可知,分页查询的设置和结果都是正确的.

posted @ 2020-04-28 11:04  安徒生敲代码  阅读(734)  评论(0编辑  收藏  举报