gpt4 book ai didi

java - Hibernate分页机制

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:04:58 25 4
gpt4 key购买 nike

我正在尝试为我的查询 (PostgreSQL) 使用 Hibernate 分页

我为我的 SQL 查询设置了 setFirstResult(0)setMaxResults(20)。我的代码如下:

Session session = getSessionFactory().getCurrentSession();
session.beginTransaction();
Query query = session.createQuery("FROM Customers");
query.setFirstResult(0);
query.setMaxResults(20);
List<T> entities = query.list();
session.getTransaction().commit();

但是当查看 SQL Hibernate 日志时,我仍然看到完整的 SQL 查询:

Hibernate: select customer0_.id as id9_, customer0_.customer_name as dst2_9_, customer0_.addres as dst3_9_ from tbl_customers customer0_  

为什么查询Hibernate分页SQL日志没有LIMIT OFFSET?

有人知道Hibernate的分页机制吗?

我猜Hibernate会选择所有数据,把数据放入Resultset,然后在Resultset中分页,对不对?

最佳答案

有很多方法可以分页。

HQL 和 setFirstResult、setMaxResults API

Session session = sessionFactory.openSession();
Query query = session.createQuery("From Foo");
query.setFirstResult(0);
query.setMaxResults(10);
List<Foo> fooList = query.list();
//Total count
String countQ = "Select count (f.id) from Foo f";
Query countQuery = session.createQuery(countQ);
Long countResults = (Long) countQuery.uniqueResult();
//Last Page
int pageSize = 10;
int lastPageNumber = (int) ((countResult / pageSize) + 1);

HQL 和 ScrollableResults API

String hql = "FROM Foo f order by f.name";
Query query = session.createQuery(hql);
int pageSize = 10;

ScrollableResults resultScroll = query.scroll(ScrollMode.FORWARD_ONLY);
resultScroll.first();
resultScroll.scroll(0);
List<Foo> fooPage = Lists.newArrayList();
int i = 0;
while (pageSize > i++) {
fooPage.add((Foo) resultScroll.get(0));
if (!resultScroll.next())
break;
}
//Total count
resultScroll.last();
int totalResults = resultScroll.getRowNumber() + 1;

简单的 Criteria API

Criteria criteria = session.createCriteria(Foo.class);
criteria.setFirstResult(0);
criteria.setMaxResults(pageSize);
List<Foo> firstPage = criteria.list();
//Total count
Criteria criteriaCount = session.createCriteria(Foo.class);
criteriaCount.setProjection(Projections.rowCount());
Long count = (Long) criteriaCount.uniqueResult();

baeldung列出所有示例。

关于java - Hibernate分页机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19649194/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com