Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

java - JPA 2 CriteriaQuery, using a limit

I am using JPA 2. For safety reasons, I am working type safe with CriteriaQuery's (and thus, I am not searching for any solutions to typed queries and so on).

I recently came across an issue in which I needed to set a SQL-LIMIT.

After a lot of searching, I was still not successful in finding a solution.

CriteriaQuery<Product> query = getEntityManager().getCriteriaBuilder().createQuery(Product.class);
Root<Product> product = query.from(Product.class);
query.select(product);

return em.createQuery(query).getResultList();

Can anyone help me?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Define limit and offset on the Query:

return em.createQuery(query)
         .setFirstResult(offset) // offset
         .setMaxResults(limit) // limit
         .getResultList();

From the documentation:

TypedQuery setFirstResult(int startPosition)

Set the position of the first result to retrieve. Parameters: startPosition - position of the first result, numbered from 0

TypedQuery setMaxResults(int maxResult)

Set the maximum number of results to retrieve.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...