繁体   English   中英

休眠条件查询以匹配所有子集合元素

[英]Hibernate criteria query to match against all child collection elements

这个问题很相似, 这一个 ,但反应是最小的那个问题。

我有一个带有一组子实体的父类。 子实体只是字符串的包装器,与父实体位于不同的表中。 我希望有一个条件查询,当子实体集的所有成员都返回true时返回一个父实体。 此条件与字符串列表之一匹配。 这是我的位置:

Criteria c = criteria();
Criteria ands = c.createCriteria("ands");
Disjunction dis = Restrictions.disjunction();
for (String value : values) {
    dis.add(Restrictions.like("value", "%" + value + "%"));
}
ands.add(dis);
return list(c);

“和”是具有“值”字段(是字符串)的一组实体。 “ criteria()”为父类创建一个条件。 “ list()”仅调用criteria.list();

这只是与任何元素匹配,而不是全部。

希望这是有道理的。 任何帮助,不胜感激。

作为理论练习,您可以执行以下操作:

Criterion condition = ...;

Criteria c = s.createCriteria(Parent.class, "p");
DetachedCriteria dc = DetachedCriteria.forClass(Parent.class, "p2")
    .createCriteria("ands", "c")
    .add(Restrictions.not(condition))
    .add(Property.forName("p.id").eqProperty("p2.id"))
    .setProjection(Projections.id());

c.add(Subqueries.notExists(dc));

但是,此方法不适合实际使用,因为它需要额外的join (由于Criteria API中缺少in elements子句)。 还要注意,它使用双重否定( SELECT ... WHERE NOT EXISTS (SELECT ... WHERE NOT <condition>) ),因此它可能会出现NULL问题。

编辑:在HQL中可以这样写:

from Parent p
where not exists (select c from p.ands c where not <condition>)

要么

from Parent p
where not exists (select c from Child c 
    where not <condition> and c in elements(p.ands))

但是,据我所知,两个查询都不能用Criteria API表示(您不能在子查询中使用from p.ands编写,也不能in elements使用)。 因此,在Criteria API中,您必须使用其他联接(注释2 Parent ):

from Parent p
where not exists (select c from Parent p2 join p2.ands c 
    where not <condition> and p = p2)

那分离不应该是合取吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM