
第 15 章 HQL: Hibernate 查询语言
- 世界杯开幕式
- 2025-05-28 15:43:21
- 1230
15.9. where 子句where 子句允许你将返回的实例列表的范围缩小。如果没有指定别名,你可以使用属性名来直接引用属性:
from Cat where name='Fritz'如果指派了别名,需要使用完整的属性名:
from Cat as cat where cat.name='Fritz'返回名为(属性 name 等于)'Fritz' 的 Cat 类的实例。
下面的查询:
select foo
from Foo foo, Bar bar
where foo.startDate = bar.date将返回所有满足下面条件的 Foo 类的实例: 存在如下的 bar 的一个实例,其 date 属性等于 Foo 的 startDate 属性。复合路径表达式使得 where 子句非常的强大,考虑如下情况:
from Cat cat where cat.mate.name is not null该查询将被翻译成为一个含有表连接(内连接)的 SQL 查询。如果你打算写像这样的查询语句:
from Foo foo
where foo.bar.baz.customer.address.city is not null在 SQL 中,你为达此目的将需要进行一个四表连接的查询。
= 运算符不仅可以被用来比较属性的值,也可以用来比较实例:
from Cat cat, Cat rival where cat.mate = rival.mateselect cat, mate
from Cat cat, Cat mate
where cat.mate = mateThe special property (lowercase) id can be used to reference the unique identifier of an object. See 第 15.5 节 “引用 identifier 属性 ” for more information.
from Cat as cat where cat.id = 123
from Cat as cat where cat.mate.id = 69第二个查询是有效的。此时不需要进行表连接。
同样也可以使用复合标识符。比如 Person 类有一个复合标识符,它由 country 属性与 medicareNumber 属性组成:
from bank.Person person
where person.id.country = 'AU'
and person.id.medicareNumber = 123456from bank.Account account
where account.owner.id.country = 'AU'
and account.owner.id.medicareNumber = 123456第二个查询也不需要进行表连接。
See 第 15.5 节 “引用 identifier 属性 ” for more information regarding referencing identifier properties)
同样的,特殊属性 class 在进行多态持久化的情况下被用来存取一个实例的鉴别值(discriminator value)。一个嵌入到 where 子句中的 Java 类的名字将被转换为该类的鉴别值。
from Cat cat where cat.class = DomesticCatYou can also use components or composite user types, or properties of said component types. See 第 15.17 节 “组件” for more information.
一个“任意”类型有两个特殊的属性 id 和 class,来允许我们按照下面的方式表达一个连接(AuditLog.item 是一个属性,该属性被映射为
from AuditLog log, Payment payment
where log.item.class = 'Payment' and log.item.id = payment.id注意,在上面的查询与句中,log.item.class 和 payment.class 将涉及到完全不同的数据库中的列。
