最近,做项目使用的是查询语句是hql语句,而我对于hql语句还不是很熟悉,现在总结一下,等到用的时候还比较方便,提高点效率。
HQL(Hibernate QueryLanguage)它能够提供更加灵活方便的数据库查询能力。它是完全面向对象 的查询。有继承,多态,关联之类的概念。
之前,我们学习过SQL,有了SQL学习的基础,学习HQL就没有什么难的啦。
一、大小写敏感问题
在HQL语句中,对大小写并不敏感。不过在查询语句一般都是小写,这样看起来更方便一些。
二、From子句
简单的写法为:from Person,但是一般情况下都会有一个别名。例如from Person(as) person,其中as可以省略,这样做的目的是为了后面的查询语句中可能会引用到Person。如果我们有了别名person,就相当于person为Person的实例,在后面的查询语句中就可以直接使用了。
三、关联与外连接
受支持的连接类型是从SQL中借鉴来的:inner join,left outer join,right outer join ,full join。我们也可以为每一个元素指定别名。
例如: from Person personleft join person.Name as name
四、select子句
select子句选择将哪些对象与属性返回到查询结果集中,查询语句可以返回值为任何类型的属性,包括返回类型为某种组件的属性,也可以返回多个对象,放在Object[]队列中,list对象中,或者返回一个世纪类型安全的Java对象。
返回一个list对象:
selectnew list(mother, offspr, mate.name)
fromDomesticCat as mother
inner join mother.mate as mate
left outer join mother.kittens as offspr
五、聚集函数
HQL查询可以返回作用于属性之上的聚集函数的计算结果:
受支持的聚集函数如下:
avg(...),sum(...), min(...), max(...)
count(*)
count(...),count(distinct ...), count(all...)
六、where子句
where子句允许你将返回的实例列表的范围缩小。如果没有指定别名,你可以使用属性名来直接引用属性。
例如:
select person
from Person person, Bar bar
where person.bornDate = bar.date
fromCat as cat where cat.id = 123
七、表达式
支持的表达式有:
1、数学运算符+, -, *, /
2、二进制比较运算符=, >=, <=, <>, !=, like
3、逻辑运算符and, or, not
4、in, not in, between, is null, is not null, is empty, is not empty,member of and not member of
5、"简单的" case, case ... when ... then ... else ... end,和"搜索" case, case when ... then ... else ... end
6、字符串连接符...||... or concat(...,...)
7、current_date(), current_time(), current_timestamp()
8、second(...), minute(...), hour(...), day(...), month(...),year(...),
9、EJB-QL 3.0定义的任何函数或操作:substring(), trim(), lower(), upper(),length(), locate(), abs(), sqrt(), bit_length()
10、coalesce() 和 nullif()
11、cast(... as ...), 其第二个参数是某Hibernate类型的名字,以及extract(... from...),只要ANSI cast() 和 extract() 被底层数据库支持
12、任何数据库支持的SQL标量函数,比如sign(), trunc(), rtrim(), sin()
13、JDBC参数传入 ?
其他的还有,Order by,group by 子查询等。