Hibernate Criteria Filtering by attributes of collection

拥有回忆 提交于 2019-12-12 18:17:07

问题


I am using the criteria sub API of hibernate for managing dynamic queries that a front user can perform. As long the filtering is done thought properties of the root entity (called it "Root") everything is fine, assuming that the associations paths are properly specified with alias.

But i reach a complicated query to perform, it involves a collection of child objects (whose class let's call it "Child"). I have to select root entities not only by the value of a property of child object (that is can be done very trivial), a have to go deeper and also check, for that child object (that fulfill some criteria) if matches another criteria, but only for that child!

So, putting it on more concrete examples, let's assume the following declarations:

class Root {
    Long id;
    Collection<Child> childs;
}

class Child {
    Long id;
    ValueObject attr;
}

class ValueObject {
    String attribute;
}

And when the times to perform the query comes, this is the code that a fortune thread executes :

Criteria criteria = session.createCriteria(Root.class);
criteria.createAlias("childs","childs");
criteria.createAlias("childs.attr","attr_childs");
criteria.add(Restrictions.eq("childs.id",20L));
criteria.add(Restrictions.eq("childs.attr","foo"));

But i want, not to matches all the Root objects that contains a child whose id is 20 and, on the other hands, that also contains another child (doesn't matter if it is the same) whose attr value is "foo". What i really want is to retrieve all the Root object that contains a child whose id is 20 and whose attr value is "foo", (all of this restrictions are fulfilled by the same entity child!).

I try to find information about this, but all seems to obfuscated!

If someone could help i will be very grateful!

Thanks to all!

Greetings!

Víctor.

来源:https://stackoverflow.com/questions/22919886/hibernate-criteria-filtering-by-attributes-of-collection

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