Hibernate filtering query collections

16,068

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.

Share:
16,068
Quincy
Author by

Quincy

Updated on June 04, 2022

Comments

  • Quincy
    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
    Quincy over 13 years
    I have to use HQL instead of Criteria due to the complexity of the HQL_SOMEDEFAULTQUERY
  • Quincy
    Quincy over 13 years
    I 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
    Daniel Bleisteiner over 13 years
    The 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
    Quincy over 13 years
    I 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
    Quincy over 13 years
    Seems 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.