简体   繁体   English

编写具有多个子元素限制的Hibernate Criteria API查询

[英]Writing a Hibernate Criteria API Query with restrictions for multiple sub-elements

I have a data model that looks like this (simplified example): 我有一个看起来像这样的数据模型(简化示例):

public class Address { private List<AddressLine> addressLines; }

public class AddressLine { private String value; private String type; }

I am trying to use the Criteria API to search for Addresses in the database that contain specific combinations of AddressLines. 我正在尝试使用Criteria API在数据库中搜索包含AddressLines特定组合的地址。 For example, to retrieve all addresses that contain the address lines {(type="CITY", value="London"), (type="COUNTRY", value="GB")}. 例如,要检索包含地址行{(type =“ CITY”,value =“ London”),(type =“ COUNTRY”,value =“ GB”)}的所有地址。 I haven't been able to find any examples of such a query. 我还没有找到这种查询的任何示例。

As far as I have been able to get is to query for an Address based on a single AddressLine. 据我所能获得的是基于单个AddressLine查询一个地址。

session.createCriteria(Address.class) .createCriteria("addressLines") .add(Restrictions.and(Restrictions.eq("type", type), Restrictions.eq("value", value))).list()

If I add a restriction for a second address lines the SQL that hibernate generates is basically asking SELECT x WHERE xy = 'a' AND xy = 'b' so will never return any results. 如果我增加了第二条地址线的限制,那么休眠生成的SQL基本上是在询问SELECT x WHERE xy ='a'和xy ='b',因此永远不会返回任何结果。

I have found similar questions being asked before but none of them have an accepted or voted for answer. 我发现之前也曾提出过类似的问题,但是没有一个问题被接受或投票赞成。

You need to write the Criteria equivalent of 您需要编写与

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')

This means writing a DetachedCriteria for each subquery, with an id projection, and using these detached criterias as argument of two Subqueries.exists() calls. 这意味着为每个子查询编写一个带有id投影的DetachedCriteria,并将这些分离的条件用作两个Subqueries.exists()调用的参数。 The alias of the address entity in the main criteria can be used in the detached criterias to implement the line1.address.id = a.id restriction. 可以在分离的条件中使用主要条件中的地址实体的别名,以实现line1.address.id = a.id限制。

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

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