欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Hibernate分页查询通用方法

程序员文章站 2022-04-15 22:12:10
...
public void QueryByPage(int pageSize) {
		SessionFactory sf = null;
		Session session = null;
		Transaction ts = null;

		try {
			sf = HibernateUtil.getSessionFactory();// SessionFactory单态模式
			session = sf.getCurrentSession(); // 保证每个读写线程有唯一的session实例
			ts = session.beginTransaction();
			Query query = session.createQuery("select count(*) from User u ");
			Number cnts = (Number) query.uniqueResult();

			int UserCount = cnts.intValue();
			int pageCount = 0;
			pageCount = UserCount / pageSize;
			if (UserCount % pageSize != 0) {
				pageCount++;
			}
			Query query1 = session.createQuery("from User u");
			for (int i = 0; i < pageCount; i++) {
				System.out.println("第" + i + "页");
				query1.setFirstResult(i * pageSize);
				query1.setMaxResults(pageSize);
				List<User> us = query1.list();
				for (User u : us) {
					System.out.println(u.toString());
				}
			}

			ts.commit();
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			if (ts != null) {
				ts.rollback();
			}
		} finally {
			// 关闭session
			// session.close();
			// sf.close();
		}
	}
相关标签: java hibernate