Question

I am using following query to fetch comments for user with id 1. In this query I am getting all comments of perticulate message. Here I want to fetch only 5 latest comments sorted by commentDate(Date) field

from PostMessageUsers as pmu
    left join fetch pmu.postMessages as pm
    left join fetch pm.comments as cmts
    where pmu.atomByReceivedBy.id=1

How to do this

EDIT : I want all messages of user. Suppose user have 100 messages it will show his 100 messages along with 5 comments of each

No correct solution

OTHER TIPS

You can limit the results rows returned by a query by calling the setFirstResult() and setMaxResults() functions on the query object before getting data list. You can user below code :

Query query = session.createQuery("from PostMessageUsers as pmu left join fetch pmu.postMessages as pm left join fetch pm.comments as cmts where pmu.atomByReceivedBy.id=1 oder by commentDate desc");  
query.setFirstResult(0);
query.setMaxResults(5); 
List result = query.list();  

If you are using criteria query than you can use Criteria.setMaxResults(MAXIMUM_RESULT)

from PostMessageUsers as pmu
    left join fetch pmu.postMessages as pm
    left join fetch pm.comments as cmts
    where pmu.atomByReceivedBy.id=1
and ROWNUM  <6
order by commentDate desc

You can set the limit for get the result which is returned by the query by calling the function query.setMaxResults()

and toy can set the start position for your query result.

Query query = session.createQuery("from PostMessageUsers as pmu left join fetch pmu.postMessages as pm left join fetch pm.comments as cmts 
where pmu.atomByReceivedBy.id=1 oder by commentDate desc");  
query.setFirstResult(0);
query.setMaxResults(5); 
List result = query.list();

It will return the result of the query with 5th results starting from 1 record. i.e. 1 to 5 records.

Or

Query query = session.createQuery("from PostMessageUsers as pmu left join fetch pmu.postMessages as pm left join fetch pm.comments as cmts 
where pmu.atomByReceivedBy.id=1 oder by commentDate desc");  
query.setFirstResult(5);
query.setMaxResults(5); 
List result = query.list();

It will return the result of the query with 5 results starting from 6th record. i.e. 6 to 10 records.

and if you want to details example with details follow this link Hibernate Pagination Example

and if you are using Criteria Queries then follwo the this link Criteria Queries In Hibernate

Thanks...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top