15.6. select 子句

优质
小牛编辑
131浏览
2023-12-01

select 子句选择将哪些对象与属性返回到查询结果集中。考虑如下情况:

select mate
from Cat as cat
    inner join cat.mate as mate

该语句将选择其它 Catmate(其他猫的配偶)。实际上,你可以更简洁的用以下的查询语句表达相同的含义:

select cat.mate from Cat cat

查询语句可以返回值为任何类型的属性,包括返回类型为某种组件(Component)的属性:

select cat.name from DomesticCat cat
where cat.name like 'fri%'
select cust.name.firstName from Customer as cust

查询语句可以返回多个对象和(或)属性,存放在 Object[] 队列中,

select mother, offspr, mate.name
from DomesticCat as mother
    inner join mother.mate as mate
    left outer join mother.kittens as offspr

或存放在一个 List 对象中:

select new list(mother, offspr, mate.name)
from DomesticCat as mother
    inner join mother.mate as mate
    left outer join mother.kittens as offspr

假设类 Family 有一个合适的构造函数 - 作为实际的类型安全的 Java 对象:

select new Family(mother, mate, offspr)
from DomesticCat as mother
    join mother.mate as mate
    left join mother.kittens as offspr

你可以使用关键字 as 给“被选择了的表达式”指派别名:

select max(bodyWeight) as max, min(bodyWeight) as min, count(*) as n
from Cat cat

这种做法在与子句 select new map 一起使用时最有用:

select new map( max(bodyWeight) as max, min(bodyWeight) as min, count(*) as n )
from Cat cat

该查询返回了一个 Map 的对象,内容是别名与被选择的值组成的名-值映射。