简体   繁体   English

如何在JPA中不编写Query的情况下实现分页?

[英]How to achieve pagination without writing Query in JPA?

I have a Question object which has List of Comment objects with @OneToMany mapping. 我有一个Question对象,其中包含带有@OneToMany映射的Comment对象List The Question object has a fetchComments(int offset, int pageSize) method to fetch comments for a given question. Question对象有一个fetchComments(int offset, int pageSize)方法来获取给定问题的注释。

I want to paginate the comments by fetching a limited amount of them at a time. 我想通过一次取出有限数量的评论来对评论进行分页。

If I write a Query object then I can set record offset and maximum records to fetch with Query.setFirstResult(int offset) and Query.setMaxResults(int numberOfResults) . 如果我编写一个Query对象,那么我可以使用Query.setFirstResult(int offset)Query.setMaxResults(int numberOfResults)设置记录偏移量和最大记录。 But my question is how(if possible) can I achieve the same result without having to write a Query ie with simple annotation or property. 但我的问题是如何(如果可能的话)我可以实现相同的结果而无需编写Query即使用简单的注释或属性。 More clearly, I need to know if there is something like 更清楚的是,我需要知道是否有类似的东西

@OneToMany(cascade = CascadeType.ALL)
@Paginate(offset = x,maxresult = y)//is this kind of annotation available?
private List<Comment> comments;

I have read that @Basic(fetch = FetchType.LAZY) only loads the records needed at runtime, but I won't have control to the number of records fetched there. 我已经读过@Basic(fetch = FetchType.LAZY)只加载运行时所需的记录,但我无法控制那里提取的记录数。 I'm new to JPA. 我是JPA的新手。 So please consider if I've missed something really simple. 所以请考虑我是否错过了非常简单的事情。

No, there is no such a functionality in JPA. 不,JPA中没有这样的功能。 Also concept itself is bit confusing. 概念本身也有点令人困惑。 With your example offset (and maxresult as well) is compile time constant and that does not serve pagination purpose too well. 您的示例偏移量(以及maxresult)也是编译时常量,并且不能很好地用于分页目的。 Also in general JPA annotations in entities define structure, not the context dependent result (for that need there is queries). 一般而言,实体中的JPA注释定义结构,而不是依赖于上下文的结果(对于需要存在查询)。

If fetching entities when they are accessed in list is enough and if you are using Hibernate, then closest you can get is extra @LazyCollection : 如果在列表中访问实体时获取实体就足够了,如果你正在使用Hibernate,那么最接近你可以获得额外的@LazyCollection

@org.hibernate.annotations.LazyCollection(LazyCollectionOption.EXTRA)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM