Hibernate filtering query collections

2020-02-15 02:10发布

问题:

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.