4.7. 关于动态注入
特定的表达式类型仅在 select 子句中有效。Hibernate 将此"动态实例化"称为"动态实例化"。Java Persistence 查询语言支持部分功能,并将其称为"结构表达式"。
示例:动态注入示例 - 结构
select new Family( mother, mate, offspr )
from DomesticCat as mother
join mother.mate as mate
left join mother.kittens as offspr
因此,我们不在这里处理 Object[],而是将值嵌套在 type-safe java 对象中,该对象将作为查询的结果返回。类引用必须完全限定,并且必须具有匹配的构造器。
此处的类不需要映射。如果确实代表某一实体,则生成的实例将返回为 NEW 状态(非 managed!)。
这也是 Java Persistence 查询语言支持的部分。HQL 支持其他"动态实例化"功能。首先,查询可以指定返回列表,而不是用于 scalar 结果的 Object[]:
示例:动态注入示例 - 列表
select new list(mother, offspr, mate.name)
from DomesticCat as mother
inner join mother.mate as mate
left outer join mother.kittens as offspr
这个查询的结果将是 List<List>,而不是 List<Object[]>。
HQL 还支持将井号结果换算成一个映射。
示例:动态注入示例 - 映射
select new map( mother as mother, offspr as offspr, mate as mate )
from DomesticCat as mother
inner join mother.mate as mate
left outer join mother.kittens as offspr
select new map( max(c.bodyWeight) as max, min(c.bodyWeight) as min, count(*) as n )
from Cat cxt
这个查询的结果将是 List<Map<String,Object>>,而不是 List<Object[]>。映射的键由提供给所选表达式的别名定义。