How can I retrieve last N entries from database with Hibernate Criteria Interface?
Criteria crit = hiberSession.createCriteria(UserTable.class);
Or even would be better to retrieve random N entries...
How can I retrieve last N entries from database with Hibernate Criteria Interface?
Criteria crit = hiberSession.createCriteria(UserTable.class);
Or even would be better to retrieve random N entries...
You have to take the total count and then fetch the last N records.
Criteria count = session.createCriteria(UserTable.class);
count.setProjection(Projections.rowCount());
Long total = count.uniqueResult();
int n;
Criteria criteria = session.createCriteria(UserTable.class);
criteria.setFirstResult(total-n);
criteria.setMaxResults(n);
List<UserTable> list = criteria.list();
If you maintain the entry timestamp then you can add order and fetch the last n results
Criteria criteria = session.createCriteria(UserTable.class);
criteria.addOrder(Order.desc("timestamp"));
criteria.setMaxResults(n);
List<UserTable> list = criteria.list();
To get any random entries set your first result to any random value, which must be less than total count.
The Last is always dependent on the ORDER BY. So we should firstly sort the list to be sure what is the last. Reversed order then (e.g. desc) would move the first to top
crit.addOrder( Order.desc("name") )
Once order is defined we can use paging
If you need to specify bounds upon your result set, that is, the maximum number of rows you want to retrieve and/or the first row you want to retrieve, you can use methods of the Query interface:
Query q = sess.createQuery("from DomesticCat cat");
q.setFirstResult(20);
q.setMaxResults(10);
List cats = q.list();
in this case, we would have it similar
...
crit.setFirstResult(20);
crit.setMaxResults(10);
...