java Hibernate 过滤查询集合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5307366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:32:06  来源:igfitidea点击:

Hibernate filtering query collections

javahibernatehql

提问by Quincy

I would like to ask if it's possible to do this using hibernate. Let say I have already run a HQL and retrieved a collection. Is it possible to further filter it using hibernate?

我想问一下是否可以使用休眠来做到这一点。假设我已经运行了一个 HQL 并检索了一个集合。是否可以使用休眠进一步过滤它?

I tried to use the <filter>to the header class and add session.enable() before the query, but seems it's not working.

我尝试使用<filter>头类并在查询之前添加 session.enable() ,但似乎不起作用。

Sample code

示例代码

Query search = session.getNamedQuery(HQL_SOMEDEFAULTQUERY);
List results = search.list();
//further filtering ...

Stripped down HQL

精简 HQL

select h
    from flow as f
    join f.item as i
    join i.header as h
    where i.status = :status
    and f.staff = :staff
    order by i.prId desc

采纳答案by jpkrohling

No. At least, not the way you asked. Once you ask Hibernate to hit the database (with the list()method), Hibernate did its part and the results are now in your hands. You can implement a filtering logic in your code to post-process the results.

不。至少,不是你问的那样。一旦您要求 Hibernate 访问数据库(使用该list()方法),Hibernate 就完成了它的职责,结果现在掌握在您手中。您可以在代码中实现过滤逻辑来对结果进行后处理。

That said, it is possible to filter the results inthe query itself. If you define a Hibernate filter and enable it for a specific model/query, you'd be able to keep your original HQL query and Hibernate will append it with extra whereclauses to further filter the results. See this:

也就是说,可以查询本身中过滤结果。如果您定义一个 Hibernate 过滤器并为特定模型/查询启用它,您将能够保留原始 HQL 查询,并且 Hibernate 将附加额外的where子句以进一步过滤结果。看到这个:

http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/filters.html

http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/filters.html

回答by Nilesh

The better way would be to use Criteria. Here is an example from Hibernate Documentation that explains usage of Criteria.

更好的方法是使用Criteria。这是Hibernate 文档中的一个示例,它解释了 Criteria 的用法

Criteria would be used before you call list method.

在调用列表方法之前将使用标准。

Hope that helps.

希望有帮助。