What is the best way to limit results using DetachedCriteria Hibernate in Java?

I am using Hibernate 3.5.6-Final in Java. Since I do not have access to the Hibernate Session , I am using DetachedCriteria . So, I would like to know what is the best way to limit the results for DetachedCriteria (in my case, I would like to get only the first row).

Additional Information:

There are some ways to achieve this in the Criteria class, such as setMaxResults (int maxResults) or setFirstResult (int firstResult) , but DetachedCriteria do not. Again, I cannot use the criteria because I do not have access to the Hibernate session.

+3
source share
6 answers

This is how I do it, you need to wrap your result in a run block. EntityMAnager in the example org.springframework.orm.hibernate3.HibernateOperations object example:

 final DetachedCriteria criteria = DetachedCriteria.forClass(ActivePropertyView.class); criteria.add(Restrictions.eq("featured", true)); List<ActivePropertyView> result = entityManager.execute( new HibernateCallback<List<ActivePropertyView>>() { @Override public List<ActivePropertyView> doInHibernate(Session session) throws HibernateException,SQLException { return criteria.getExecutableCriteria(session).setMaxResults(5).list(); } }); return result; 
+10
source

You can use Restrictions.sqlRestriction () to add a simple SQL expression to DetachedCriteria. Try the following:

 DetachedCriteria criteria = DetachedCriteria.forClass(Domain.class) .add(Restrictions.sqlRestriction("LIMIT 1")); 
+6
source

If I read javadoc correctly, you cannot limit it until you finally reinstall DetachedCriteria into real criteria (if you have a session)

+2
source

If you use hibernation patterns, there is findByCriteria(criteria, firstResult, maxResults) . Templates are discouraged, but for those who have outdated code, this is available.

+1
source

Extending the answer to yorkw, the equivalent of Oracle:

 DetachedCriteria criteria = DetachedCriteria.forClass(Domain.class) .add(Restrictions.sqlRestriction("rownum < 1")); 

It will add a line constraint to the where clause in the subquery.

0
source
 detachedCriteria.getExecutableCriteria(getSession()).setMaxResults(1); 
-1
source

All Articles