How to limit a collection in an Object's property in hibernate?

后端 未结 3 811
离开以前
离开以前 2021-01-25 19:24

I have two entities: item, and bid, each item have many bids for it, so bid is a collection property of item.

in the page that show an item, I just want to show the firs

3条回答
  •  忘掉有多难
    2021-01-25 19:40

    This works so much better if you also have an association from Bid to Item.

    Then you can select the items and apply the limit restriction:

    session
        .createQuery(
        "select b
        from bid b
        join fetch b.item i
        where 
            i.id=3")
        .setMaxResult(10)
        .list();
    

    Your previous query, the one selecting Item and fetching Bids will always select all items with all their bids and apply the max result limit in-memory. This is because Hibernate must always fetch all children, it can't give you partial collection results.

    Selecting the child and joining the parent is a better alternative. The restriction applies to the selected children with no restriction whatsoever.

提交回复
热议问题