Java 编写具有多个子元素限制的Hibernate Criteria API查询
我有一个如下所示的数据模型(简化示例):Java 编写具有多个子元素限制的Hibernate Criteria API查询,java,sql,hibernate,criteria,Java,Sql,Hibernate,Criteria,我有一个如下所示的数据模型(简化示例): 公共类地址{私有列表地址行;} 公共类地址行{私有字符串值;私有字符串类型;} 我试图使用CriteriaAPI在数据库中搜索包含特定地址行组合的地址。例如,检索包含地址行{(type=“CITY”,value=“London”),(type=“COUNTRY”,value=“GB”)}的所有地址。我还没有找到任何这样一个查询的例子 就我所能得到的而言,是基于单个地址行查询地址 session.createCriteria(Address.class)
公共类地址{私有列表地址行;}
公共类地址行{私有字符串值;私有字符串类型;}
我试图使用CriteriaAPI在数据库中搜索包含特定地址行组合的地址。例如,检索包含地址行{(type=“CITY”,value=“London”),(type=“COUNTRY”,value=“GB”)}的所有地址。我还没有找到任何这样一个查询的例子
就我所能得到的而言,是基于单个地址行查询地址
session.createCriteria(Address.class)
.createCriteria(“地址行”)
.add(Restrictions.and(Restrictions.eq(“type”,type),Restrictions.eq(“value”,value))).list()
如果我为第二个地址行添加一个限制,hibernate生成的SQL基本上是询问SELECT x,其中x.y='a'和x.y='b',因此永远不会返回任何结果
我发现以前有人问过类似的问题,但没有一个答案被接受或投票赞成。你需要写出与之相当的标准
select a from Address a where
exists (select line1.id from AddressLine line1 where line1.address.id = a.id
and line1.type = 'CITY'
and line1.value = 'London')
and exists (select line2.id from AddressLine line where line2.address.id = a.id
and line2.type = 'COUNTRY'
and line2.value = 'GB')
这意味着为每个子查询编写一个DetachedCriteria,使用id投影,并将这些分离的Criteria用作两个
子查询.exists()
调用的参数。主条件中地址实体的别名可以在分离的条件中使用,以实现line1.address.id=a.id
限制。我不确定如何将其转换为条件(我不熟悉Hibernate)。今天我将进一步研究文档。我还发现这个问题非常相似。它没有回答这个问题,但有一些代码片段可以帮助实现您的解决方案。但是,这些代码片段不显示exists()调用。我链接到的答案中提出的可能解决方案存在以下异常:org.hibernate.QueryException:重复关联路径
select a from Address a where
exists (select line1.id from AddressLine line1 where line1.address.id = a.id
and line1.type = 'CITY'
and line1.value = 'London')
and exists (select line2.id from AddressLine line where line2.address.id = a.id
and line2.type = 'COUNTRY'
and line2.value = 'GB')