How can I do paging with @OneToMany collections

后端 未结 2 1055
清酒与你
清酒与你 2021-02-19 01:53

Suppose I have a Post entity and a Comment entity and a one to many relationship:

@Entity class Post {
    ...
    @OneToMany
    List comments;
          


        
相关标签:
2条回答
  • 2021-02-19 02:23

    Is it possible to emulate dynamic paging with @OneToMany collections on top of JPA (...)

    Not supported. The standard approach would be to use a JPQL query to retrieve the comments for a given post and and to use Query#setFirstResult(int) and Query#setMaxResults(int).

    On my first thought, we could create a subclass of List, (...). But I don't know whether Hibernate/JPA will recognize this, or interfere with it.

    It obviously won't without an heavy patch to drastically change the default behavior.

    0 讨论(0)
  • 2021-02-19 02:41

    I think the "right" way might be more like:

    @Entity
    class Post {
        ...
    
        public GenericModel.JPAQuery getComments() {
            return Comment.find("post_id = ?", post_id);
        }
    }
    

    and then use one of the fetch methods in JPAQuery:

    // fetch first page of results, 25 results per page
    post.getComments().fetch(1,25);
    
    0 讨论(0)
提交回复
热议问题