lovespring
lovespring

Reputation: 19589

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

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 first 10 records of bids about this "item".

so, I do this query:

from item
left join fetch item.bids
where item.id=3
...

but this will fetch all bids about an item, so, how to limit the bids about an item ?

Upvotes: 2

Views: 4356

Answers (3)

Vlad Mihalcea
Vlad Mihalcea

Reputation: 153970

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.

Upvotes: 6

Ker p pag
Ker p pag

Reputation: 1588

you can use criteria's setFirstResult() and setMaxResult(). or this post would be helpful for your question

example:

sessionFactory.getCurrentSession().createQuery("your query here").setFirstResult(0).setMaxResult(10);

this will generate 10 rows of data from database

you have use annotation driven. simply add the annotation Size to your bid object

    @OneToMany( mappedBy = "object", cascade = CascadeType.ALL)
    @Size(min=1, max=10)
    private Set<Bid>    bid;

Upvotes: 2

Sandeep B
Sandeep B

Reputation: 775

For plain SQL, do the following:

Select B.*
From item I, bid B,
Where T.itemId = B.itemId
Limit 10;

Same can be done in case you are using hibernate, using criteria API or HQL HQL example:

Query query = session.createQuery("from MyTable");
query.setMaxResults(10);

Criteria example: 
session.createCriteria(Abc.class)
                    .addOrder(Order.desc("id"))
                    .setMaxResults(10)
                    .list();

Upvotes: 0

Related Questions