Hibernate filtering query collections

。_饼干妹妹 提交于 2019-12-18 09:17:20

问题


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?

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

Sample code

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

Stripped down 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

回答1:


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.

That said, it is possible to filter the results in the 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 where clauses to further filter the results. See this:

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




回答2:


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

Criteria would be used before you call list method.

Hope that helps.



来源:https://stackoverflow.com/questions/5307366/hibernate-filtering-query-collections

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