HQL & JPQL - Part Ⅱ

Basic HQL and JPQL queries

We apply selection to name the data source, restriction to match records to the criteria, and projection to select the data you want returned from a query.

Eclipse插件Hibernate Tools,可以直接写HQL来查询,可看到生成的SQL及查询结果。
此处只关注SELECT语句,HQL也支持UPDATE,DELETE,INSERT..SELECT; JPQL支持UPDATE,DELETE.
HQL查询语句可以省略select clause,但是JPQL不能省略。

Selection

查询一个实体类:

// HQL,注意JPQL需要加上select clause
from Item

生成的SQL:

select i.ITEM_ID, i.NAME, i.DESCRIPTION, ... from ITEM i

Using aliases

使用别名,as关键字可省略,HQL/JPQL中关键字不区分大小写。

// HQL
from Item as item
from Item item
// JPQL
select item from Item item

Polymorphic queries

多态查询,可以查询父类及其子类。

// CreditCard和BankAccount是BillingDetails的子类。
from BillingDetails

// 查询出所有persistent objects
from java.lang.Object

// 查询出所有实现了Serializable接口的persistent objects
from java.io.Serializable

Restriction

WHERE子句

// 查询条件值用单引号括起
from User u where u.email = 'foo@hibernate.org'

// 还可以使用字面量true false
from Item i where i.isActive = true

Comparison expressions

from Bid bid where bid.amount between 1 and 10
from Bid bid where bid.amount > 100
from User u where u.email in ('foo@bar', 'bar@foo')

// 判断是否为空
from User u where u.email is null
from Item i where i.successfulBid is not null

// 模糊查询
from User u where u.firstname like 'G%'
from User u where u.firstname not like '%Foo B%
// 转义%,返回firstname以%Foo开头的用户
from User u where u.firstname like '\%Foo%' escape='\'

// 运算
from Bid bid where ( bid.amount / 0.71 ) - 100.0 > 0.0

// 逻辑运算
from User user where user.firstname like 'G%' and user.lastname like 'K%'
from User u where ( u.firstname like 'G%' and u.lastname like 'K%' ) or u.email in ('foo@hibernate.org', 'bar@hibernate.org' )
Operator Description
. Navigation path expression operator
+, - Unary positive or negative signing (all unsigned numeric values are considered positive)
*, / Regular multiplication and division of numeric values
+, - Regular addition and subtraction of numeric values
=, <>, <, >, >=, <=, [NOT] BETWEEN,[NOT] LIKE, [NOT] IN, IS [NOT] NULL Binary comparison operators with SQL semantics
IS [NOT] EMPTY, [NOT] MEMBER [OF] Binary operators for collections in HQL and JPQL
NOT, AND, OR Logical operators for ordering of expression evaluation

Expressions with collections

// 返回所有bids集合属性不为空的Item对象
from Item i where i.bids is not empty

// 返回主键是123的Item对象,还有此对象所属的Category对象
from Item i, Category c where i.id = '123' and i member of c.items

.id总是指定实体类的主键属性,即使其属性名称不是id。

Another trick you use here is the special .id path; this field always refers to the database identifier of an entity, no matter what the name of the identifier property is.

Calling functions

在WHERE,HAVING子句中调用函数:

from User u where lower(u.email) = 'foo@hibernate.org'

HQL,JPQL提供了统一的字符串拼接函数concat():

from User user where concat(user.firstname, user.lastname) like 'G% K%'

利用size()函数判断集合大小:

from Item i where size(i.bids) > 3

JPA标准中支持的函数:

Function Applicability
UPPER(s), LOWER(s) String values; returns a string value
CONCAT(s1, s2) String values; returns a string value
SUBSTRING(s, offset, length) String values (offset starts at 1); returns a string value
TRIM( [[BOTH | LEADING | TRAILING] char [FROM]] s) Trims spaces on BOTH sides of s if no char or other specification is given; returns a string value
LENGTH(s) String value; returns a numeric value
LOCATE(search, s, offset) Searches for position of ss in s starting at offset; returns a numeric value
ABS(n), SQRT(n), MOD(dividend,divisor) Numeric values; returns an absolute of same type as input, square root as double, and the remainder of a division as an integer
SIZE(c) Collection expressions; returns an integer, or 0 if empty

Hibernate扩展的函数:

Function Applicability
BIT_LENGTH(s) Returns the number of bits in s
CURRENT_DATE(), CURRENT_TIME(),CURRENT_TIMESTAMP() Returns the date and/or time of the database management system machine
SECOND(d), MINUTE(d), HOUR(d),DAY(d), MONTH(d), YEAR(d) Extracts the time and date from a temporal argument
CAST(t as Type) Casts a given type t to a Hibernate Type
INDEX(joinedCollection) Returns the index of joined collection element
MINELEMENT(c), MAXELEMENT(c),MININDEX(c), MAXINDEX(c),ELEMENTS(c), INDICES(c) Returns an element or index of indexed collections(maps, lists, arrays)
Registered in org.hibernate.Dialect Extends HQL with other functions in a dialect

以上所有函数都会被Hibernate转换成不同数据库的特定SQL函数。如果在HQL中使用的函数,Hibernate无法识别,Hibernate会直接传递此函数到数据库。

Ordering query results

from User u order by u.username desc

from User u order by u.lastname asc, u.firstname asc

Projection

Projection,投射,其实就是指定要查询的字段。

Simple projection of entities and scalar values

Query q = session.createQuery("from Item i, Bid b");
// Query q = entityManager.createQuery("select i, b from Item i, Bid b");
Iterator pairs = q.list().iterator();
// Iterator pairs = q.getResultList().iterator();
while (pairs.hasNext()) {
    Object[] pair = (Object[]) pairs.next();
    Item item = (Item) pair[0];
    Bid bid = (Bid) pair[1];
}

以上查询返回了 a List of Object[],List中每个元素是对象数组,数组中包含两个实体对象。

以下查询也返回 a List of Object[],但是数组元素不是实体对象,而是scalar value,所以这种查询被称为scalar query

select i.id, i.description, i.initialPrice from Item i where i.endDate > current_date()

Getting distinct results

去重,使用distinct关键字。

select distinct item.description from Item item

Calling functions

在SELECT子句中也可以使用函数,尤其是aggregate functions,后面一节将会讲到。

select item.startDate, current_date() from Item item

select item.startDate, item.endDate, upper(item.name) from Item item

需要注意的是:和WHERE子句不同,当在SELECT子句中,如果使用的函数Hibernate无法识别,是不会传送给数据库的;函数必须在org.hibernate.Dialect中注册。


此文是对《Java Persistence with Hibernate》第14章第二部分的归纳。

Markdown表格中如果要显示'|',可以使用HTML字符实体&#124;

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,219评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,363评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,933评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,020评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,400评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,640评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,896评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,597评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,327评论 1 244
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,581评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,072评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,399评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,054评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,849评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,672评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,585评论 2 270

推荐阅读更多精彩内容

  • Joins, reporting queries, and subselects 在抓取策略这篇文章中有提到dyn...
    ilaoke阅读 3,455评论 0 3
  • Defining the global fetch plan Retrieving persistent obje...
    ilaoke阅读 5,447评论 1 6
  • 写在前面: 这两天课少,于是趁着空闲来写一个教程,希望能够有些帮助。 我自己到现在自学绘画大约有两年了,期间没有报...
    念落安阅读 1,409评论 0 11
  • 小白点是月亮 太阳当空照 其实那些只是灰机
    傻羊羊阅读 287评论 1 1
  • 就让风捎去满心的祝福, 在季节的胸膛里埋葬, 就让野草丛生, 在荒无人烟的沙漠里堆起白骨。 就让我孤独如人, 在尘...
    摩诘梵心阅读 257评论 4 14