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

。_饼干妹妹 提交于 2019-12-12 16:00:43

问题


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.


回答1:


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;



回答2:


You can use Restrictions.sqlRestriction() add plain SQL expression to DetachedCriteria. Try this:

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



回答3:


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.




回答4:


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)




回答5:


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.




回答6:


detachedCriteria.getExecutableCriteria(getSession()).setMaxResults(1);


来源:https://stackoverflow.com/questions/11507868/what-is-the-best-way-to-limit-results-using-a-detachedcriteria-of-hibernate-in-j

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!