What is the best way to limit results using a DetachedCriteria of Hibernate in Java?
-
21-06-2021 - |
Pergunta
I'm using Hibernate 3.5.6-Final in Java. Since I don't have access to the Hibernate Session, I'm using a DetachedCriteria. So, I would like to know what is the best way to limit the results for a DetachedCriteria (in my case I would like to get only the first row).
Additional info:
The Criteria class has some methods to achieve this, like setMaxResults(int maxResults) or setFirstResult(int firstResult), but the DetachedCriteria doesn't have neither. Again, I can't use the Criteria because I don't have access to the Hibernate's Session.
Solução
This is how i am doing it, you have to wrap your result into execute block.
EntityMAnager in the example below is org.springframework.orm.hibernate3.HibernateOperations
object :
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;
Outras dicas
You can use Restrictions.sqlRestriction() add plain SQL expression to DetachedCriteria. Try this:
DetachedCriteria criteria = DetachedCriteria.forClass(Domain.class)
.add(Restrictions.sqlRestriction("LIMIT 1"));
If you are using hibernate templates, there is a findByCriteria(criteria, firstResult, maxResults)
. Templates are discouraged, but for those with legacy code this is available.
If I'm reading the javadoc right, you cannot limit until you finally convert the DetachedCriteria to a real Criteria (when you do have a Session)
Expanding on yorkw's answer, the Oracle equivalent is:
DetachedCriteria criteria = DetachedCriteria.forClass(Domain.class)
.add(Restrictions.sqlRestriction("rownum < 1"));
It will add the row limit to the "where" clause in the subquery.
detachedCriteria.getExecutableCriteria(getSession()).setMaxResults(1);