Hibernate filtering query collections
Solution 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
Solution 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.
![Quincy](https://i.stack.imgur.com/I5tTj.gif?s=256&g=1)
Quincy
Updated on June 04, 2022Comments
-
Quincy about 2 years
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
-
Quincy over 13 yearsI have to use HQL instead of Criteria due to the complexity of the HQL_SOMEDEFAULTQUERY
-
Quincy over 13 yearsI have tried to use the session.enableFilter() method but seems it's not working. Probably because I am retrieving a collection. Correct me if I am wrong.
-
Daniel Bleisteiner over 13 yearsThe link mentioned by @partenon describes the usage of filters in detail. And no - it's not broken because you retrieve a collection. You most probably miss another part of the configuration.
-
Quincy over 13 yearsI mean a header collection was retrieved but not a filtered collection. I was setting the filter in the header class but somehow it's not triggered using the HQL above. Should I place the filter in the item's header collection instead?
-
Quincy over 13 yearsSeems like Hibernate does not allow me to place the filter in the many to one relation. Any workaround? I just want to filter out some result that do not fulfill some extra conditions.