HQL查询的where语句实例介绍



HQL查询的where子句实例介绍。

(1)where子句用于筛选选中的结果,缩小选择的范围。如果没有为持久化实例命名别名,则可以直接使用属性名来引用属性。

如下面两条HQL语句:

from Person where name like “tom%”

form Person as p where p.name like “tom%”

(2)复合属性表达式加强了where子句的功能,例如,如下的HQL语句:

from Cat cat where cat.mate.name like “kit%”

上面语句被翻译成以下含有内连接的SQL查询:

select * from cat_table as table1 cat_table as table2

where table1.mate = table2.mate

and table1.name like ”’kit%’”

实际上这种用法使用了隐式连接查询,从Hibernate3.2.3之后,只有当cat,mate属性引用的是普通组件属性或者单独的关联实体时才可接着在后面使用点好(.)来引用mate属性,如cat,mate.name; 如果cat,mate是集合属性,Hibernate3.2.3以后的版本不支持这种用法。


“=”号不仅可以被用来比较属性的值,也可以用来比较实例。

select cat,mate from Cat cat, Cat mate where cat.mate = mate

(3)在进行多态持久化的情况下,class关键字用来存取一个实例的鉴别值。嵌入where子句的Java类名,将被作为该类的鉴别值。

//执行多态查询时,默认会选出Cat及其所有子类的实例

//在如下HQL语句中,将只选出DomesticCat类的实例

from Cat cat where cat.class = DomesticCat

(4)当where子句中的运算符只支持基本类型或者字符串时,where子句中的属性表达式必须以基本类型或者字符串结尾,不要使用组件类型属性结尾,例如Account和Person属性,而Person有Name属性,Name属性有firstName属性。

如下所示:

//firstName是字符串

from Account as a where a.person.name.firstName like “dd%”

//下面是错误实例

from Account as a where a.person.name like “dd%”