淘先锋技术网

首页 1 2 3 4 5 6 7
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();
		}
	}