在Java中使用Hibernate的DetachedCriteria限制结果的最佳方法是什么? [英] What is the best way to limit results using a DetachedCriteria of Hibernate in Java?

查看:187
本文介绍了在Java中使用Hibernate的DetachedCriteria限制结果的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中使用Hibernate 3.5.6-Final。由于我无法访问Hibernate Session a>,我正在使用 DetachedCriteria 。所以,我想知道限制DetachedCriteria结果的最佳方法(在我的情况下,我只想获得第一行)。

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).

其他信息:

Criteria 类有一些方法来实现这一点,比如 setMaxResults(int maxResults) setFirstResult(int firstResult),但DetachedCriteria中都没有。再次,我不能使用Criteria,因为我没有访问Hibernate的Session。

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.

推荐答案

我正在做它,你必须把你的结果包装到执行块中。
下面例子中的EntityMAnager是 org.springframework.orm.hibernate3.HibernateOperations object:

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;

这篇关于在Java中使用Hibernate的DetachedCriteria限制结果的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆