14.12. 子查询

对于支持子查询的数据库,Hibernate支持在查询中使用子查询。一个子查询必须被圆括号包围起来(经常是SQL聚集函数的圆括号)。 甚至相互关联的子查询(引用到外部查询中的别名的子查询)也是允许的。

from Cat as fatcat 
where fatcat.weight > ( 
    select avg(cat.weight) from DomesticCat cat 
)
from DomesticCat as cat 
where cat.name = some ( 
    select name.nickName from Name as name 
)
from Cat as cat 
where not exists ( 
    from Cat as mate where mate.mate = cat 
)
from DomesticCat as cat 
where cat.name not in ( 
    select name.nickName from Name as name 
)
select cat.id, (select max(kit.weight) from cat.kitten kit) 
from Cat as cat

注意,HQL自查询只可以在select或者where子句中出现。

在select列表中包含一个表达式以上的子查询,你可以使用一个元组构造符(tuple constructors):

from Cat as cat 
where not ( cat.name, cat.color ) in ( 
    select cat.name, cat.color from DomesticCat cat 
)

注意在某些数据库中(不包括Oracle与HSQL),你也可以在其他语境中使用元组构造符, 比如查询用户类型的组件与组合:

from Person where name = ('Gavin', 'A', 'King')

该查询等价于更复杂的:

from Person where name.first = 'Gavin' and name.initial = 'A' and name.last = 'King')

有两个很好的理由使你不应当作这样的事情:首先,它不完全适用于各个数据库平台;其次,查询现在依赖于映射文件中属性的顺序。