1.from子句
from字句是最简单的HQL语句,
例如 from Student,也可以写成select s from Student s。它简单地返回Student类的所有实例。
Query query = session.createQuery(“from Student”);
List list = query.list();
for (int i=0;i<list.size(); i++)
{
Student stu = (Student)list.get(i);
System.out.println(stu.getName());
}
我们也可以为相关联的实体甚至是对一个集合中的全部元素指定一个别名, 这时要使用关键字join
。
from Cat as cat inner join cat.mate as mate left outer join cat.kittens as kitten
from Cat as cat left join cat.mate.kittens as kittens
from Formula form full join form.parameter param
受支持的连接类型是从ANSI SQL中借鉴来的。
-
inner join
(内连接) -
left outer join
(左外连接) -
right outer join
(右外连接) -
full join
(全连接,并不常用)
语句inner join
, left outer join
以及 right outer join
可以简写。
from Cat as cat join cat.mate as mate left join cat.kittens as kitten
select
子句选择将哪些对象与属性返 回到查询结果集中. 考虑如下情况:
select mate from Cat as cat inner join cat.mate as mate
该语句将选择mate
s of other Cat
s。(其他猫的配偶) 实际上, 你可以更简洁的用以下的查询语句表达相同的含义:
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
也可能直接返回一个实际的类型安全的Java对象,
select new Family(mother, mate, offspr) from DomesticCat as mother join mother.mate as mate left join mother.kittens as offspr
假设类Family
有一个合适的构造函数.
你可以使用关键字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
的对象,内容是别名与被选择的值组成的名-值映射。