Hibernate: Criteria Query child objects (associations) by Entity (not Id)

I would like to query a Parent object by a list of child objects with Hibernate Criteria Query. I know how to do it with IDs of the childs but not using entities directly.

This works:

List<Long>  listOfChildLongChildIds = new ArrayList<Long>();
listOfChildLongChildIds.add(new Long(1));
listOfChildLongChildIds.add(new Long(2));

Criteria criteria = getSession().createCriteria(Parent.class);
Criteria criteriaChilds = criteria.createCriteria("childs");
criteriaChilds.add(Restrictions.in("id", listOfChildLongChildIds));

But how to do this, when the list contains Child Objects/Entities like this:

List<Child>  listOfChildEntities = new ArrayList<Child>();
listOfChildEntities.add(QueryChildFromDatabse);
listOfChildEntities.add(QueryChildFromDatabse);

(This means I do not use the ID of the child but only the Entitiy itself. The reason is otherwise I would have to iterate through my list of childs and extract all Ids and put them into a list what I think is most likely unnecessary. But I was not able to find any information how to query by entity lists itself):

Then the code above using

criteriaChilds.add(Restrictions.in("id",listOfChildEntities));

will throw an exception:

Child cannot be cast to java.lang.Long


我认为你应该能够做到这样的事情:

Criteria criteria = getSession().createCriteria(Parent.class);
criteria.createCriteria("childs","childs");
criteria.add(Restrictions.in("childs.id", listOfChildLongChildIds));

您应该能够将对象传递给Restrictions.in方法。

Restrictions.in("childs", <childObjectslist>)
链接地址: http://www.djcxy.com/p/6320.html

上一篇: (N)Hibernate:一次搜索2个字段

下一篇: Hibernate:Criteria按实体查询子对象(关联)(不是Id)