NHibernate is equiped with an extremely powerful query language that (quite intentionally) looks very much like SQL. But don't be fooled by the syntax; HQL is fully object-oriented, understanding notions like inheritence, polymorphism and association.
NHibernate 配备了非常强大的查询语言(特意)让它看起来非常像 SQL。但不要被其语法所蒙蔽;HQL 是完全面向对象的,理解像 inheritence 继承, polymophism 多态 和 association 关联的概念。
Queries are case-insensitive, except for names of .NET classes and properties. So SeLeCT is the same as sELEct is the same as SELECT but Eg.FOO is not Eg.Foo and foo.barSet is not foo.BARSET.
除了对 .NET 类名及其属性外,查询是大小写不敏感的。因此 SeLeCT 和 sELEct 是与 SELECT 等同的,而 Eg.FOO 与 Eg.Foo 是不同的,foo.barSet 与 foo.BARSET 是不同的。
This manual uses lowercase HQL keywords. Some users find queries with uppercase keywords more readable, but we find this convention ugly when embedded in Java code.
本手册使用小写 HQL 关键字。一些用户会发现大写关键字更可读,但是我们发现此惯例当嵌入到 Java 代码中时有些不协调。
The simplest possible NHibernate query is of the form:
最简单的 NHibernate 查询就是 from:
which simply returns all instances of the class Eg.Cat.
它简单返回 Eg.Cat 类的一个实例。
Most of the time, you will need to assign an alias, since you will want to refer to the Cat in other parts of the query.
很多时候,你需要指定别名,因为在查询语句的其它地方你会想引用 Cat 。
This query assigns the alias cat to Cat instances, so we could use that alias later in the query. The as keyword is optional; we could also write:
此查询指定 cat 给 Cat 实例,因此我们就可以在后面的查询中使用此别名。这个 as 关键字是可选的;我们也可这样写:
Multiple classes may appear, resulting in a cartesian product or "cross" join.
出现多个类,会导致 笛卡尔积 或者称 “交差” 连接。
It is considered good practice to name query aliases using an initial lowercase, consistent with naming standards for local variables (eg. domesticCat).
别名使用小写首字母,变量命名规范的一致性认为是好的作法(例如:domesticCat)。
We may also assign aliases to associated entities, or even to elements of a collection of values, using a join.
我们可能会指定一个关联着实体的别名,或者元素恰好是一个值的集合,此时就应使用联接。
inner join cat.Mate as mate
left outer join cat.Kittens as kitten
from Eg.Cat as cat left join cat.Mate.Kittens as kittens
from Formula form full join form.Parameter param
The supported join types are borrowed from ANSI SQL
所支持的连接类型借用了 ANSI(American National Standards Institute,美国国家标准学会) SQL
-
inner join 内连接
-
left outer join 左外连接
-
right outer join 右外连接
-
full join (not usually useful) 全连接(通常不用)
The inner join, left outer join and right outer join constructs may be abbreviated.
内连接,左外连接和右外连接构造可能会简化。
inner join => join, left outer join => left join, right outer join => right join
In addition, a "fetch" join allows associations or collections of values to be initialized along with their parent objects, using a single select. This is particularly useful in the case of a collection. It effectively overrides the outer join and lazy declarations of the mapping file for associations and collections. See Section 15.1, “Fetching strategies” for more information.
此外,“fetch” 连接允许使用一个 select 来完成父对象及其关联或集合一同被初始化。这尤其是在使用集合时非常有用。它会有效的覆盖对于关联和集合在映射文件中外连接和延迟的声明。更多信息参看 15.1节, “抓取策略” 。
A fetch join does not usually need to assign an alias, because the associated objects should not be used in the where clause (or any other clause). Also, the associated objects are not returned directly in the query results. Instead, they may be accessed via the parent object.
抓取连接(接下来会作用 fetch join)通常不需要指定别名,因为关联对象不会用在 where 子句(或任何其它子名)。而且,关联对象不会通过查询结果直接返回。取而代之,它们可以通过父对象来进行访问。
It is possible to create a cartesian product by join fetching more than one collection in a query, so take care in this case. Join fetching multiple collection roles is also disabled for bag mappings. Note also that the fetch construct may not be used in queries called using Enumerable(). Finally, note that full join fetch and right join fetch are not meaningful.
因为在 query (查询)时通过 join (连接)fetch (抓取)一个以上的 collection(集合)有可能产生 cartesian product (迪卡尔积),因此在这种情形时应当注意。join(连接)fetch(抓取)多个 collection(集合)时对于 bag(包)mapping (映射)是禁用的。提示而且fetch(抓取)结构的查询不会在使用 Enumerable() (枚举)方法时被调用。最后,注意 full join(全连接) 与 right join(右连接)没有意义。
本段多次使用英语希望读者对相关词汇加深印象。
The select clause picks which objects and properties to return in the query result set. Consider:
select 子句抓取对象和属性并将其返回到查询结果集(set)中。揣摩一下:
The query will select Mates of other Cats. Actually, you may express this query more compactly as:
这个查询将 select 到猫的同伴猫,你可能会用此种更为紧凑的查询:
You may even select collection elements, using the special elements function. The following query returns all kittens of any cat.
你甚至可能 select 集合元素,通过使用一个专属 elements(元素)函数。下面的查询会 return(返回)全部 Cat 的全部 kittens(小猫)。
Queries may return properties of any value type including properties of component type:
查询可以返回任何类型的属性包括组件类型的属性:
where cat.Name like 'fri%'
select cust.Name.FirstName from Customer as cust
Queries may return multiple objects and/or properties as an array of type object[]
查询可以返回多个对象和/或属性并当成一个对象数组 object[]
from Eg.DomesticCat as mother
inner join mother.Mate as mate
left outer join mother.Kittens as offspr
or as an actual typesafe object
或当作一个实际的类型安全的对象
from Eg.DomesticCat as mother
join mother.Mate as mate
left join mother.Kittens as offspr
assuming that the class Family has an appropriate constructor.
假定 Family 有相应的构造器
11.5. Aggregate functions - 聚合函数
HQL queries may even return the results of aggregate functions on properties:
HQL 查询甚至可以返回聚合函数对于属性的结果:
Collections may also appear inside aggregate functions in the select clause.
集合也可也出现在 select 子句的聚合函数中。
The supported aggregate functions are
支持的聚合函数有
-
avg(...), sum(...), min(...), max(...)
-
count(*)
-
count(...), count(distinct ...), count(all...)
The distinct and all keywords may be used and have the same semantics as in SQL.
可以使用 distinct 和 所有的关键字,基语义与 SQL 相同。
11.6. Polymorphic queries - 多态查询
A query like:
查询像:
returns instances not only of Cat, but also of subclasses like DomesticCat. NHibernate queries may name any .NET class or interface in the from clause. The query will return instances of all persistent classes that extend that class or implement the interface. The following query would return all persistent objects:
返回实例不仅是 Cat 的实例,而且也是子类像 DomesticCat 的实例。NHibernate 查询可以在 from 子句中命名任何 .NET 类或接口。查询将返回扩展类或是实现了接口的持久化类的实例。下面的查询返回所有持久化对像。
The interface INamed might be implemented by various persistent classes:
INamed 接口可能会被各种持久化类实现:
Note that these last two queries will require more than one SQL SELECT. This means that the order by clause does not correctly order the whole result set.
注意最后面的两个查询将会检索一个以上的 SQL SELECT。这意味着 order by 子句对于全部结果集来说不会是正确的顺序。
The where clause allows you to narrow the list of instances returned.
where 子句允许你减少你返回的实例列表。
returns instances of Cat named 'Fritz'.
返回名称为 'Fritz' 的实例
will return all instances of Foo for which there exists an instance of Bar with a Date property equal to the StartDate property of the Foo. Compound path expressions make the where clause extremely powerful. Consider:
返回 Foo 实例中其属性 StartDate 与 Bar 实例中的 Date 属性相等的实例。组合路径表达式使得 where 子句非常强大。看:
This query translates to an SQL query with a table (inner) join. If you were to write something like
此查询转化成对于表的(内)连接的 SQL 查询。如果你写了像这样的语句
you would end up with a query that would require four table joins in SQL.
你会以具有四张表连接的SQL查询而告终。
The = operator may be used to compare not only properties, but also instances:
= 运算符不仅可以比较属性,还可比较实例:
select cat, mate
from Eg.Cat cat, Eg.Cat mate
where cat.Mate = mate
The special property (lowercase) id may be used to reference the unique identifier of an object. (You may also use its property name.)
这个特殊的属性(小写)id 可用于引用对象的唯一标识。(你也可以用其属性名。)
from Eg.Cat as cat where cat.Mate.id = 69
The second query is efficient. No table join is required!
第二个查询效率高。不需要表连接!
Properties of composite identifiers may also be used. Suppose Person has a composite identifier consisting of Country and MedicareNumber.
也可以使用复合关键字属性。比如一个人有一个复合关键字包括国家和医保编号。
where person.id.Country = 'AU'
and person.id.MedicareNumber = 123456
from Bank.Account account
where account.Owner.id.Country = 'AU'
and account.Owner.id.MedicareNumber = 123456
Once again, the second query requires no table join.
同样,第二个查询不需要表连接。
Likewise, the special property class accesses the discriminator value of an instance in the case of polymorphic persistence. A Java class name embedded in the where clause will be translated to its discriminator value.
同样,特殊属性 class 用于访问在多态持久化情形下访问一个分属实例。
在 where 子句中嵌入 Java 类名将会转译成分属类的值。
You may also specify properties of components or composite user types (and of components of components, etc). Never try to use a path-expression that ends in a property of component type (as opposed to a property of a component). For example, if store.Owner is an entity with a component Address
你也可以指定组件属性或复合用户类型属性(和组件的组件,等等)。永远不要试用以组件属性结束的路径表达式(而不是组件的属性)
store.Owner.Address // error!
An "any" type has the special properties id and class, allowing us to express a join in the following way (where AuditLog.Item is a property mapped with ).
一个具有 id 和 class 属性的 “任可” 类型,允许我们用如下的方法表示一个连接(where AuditLog.Item 是一个映射的属性)
where log.Item.class = 'Eg.Payment, Eg, Version=...' and log.Item.id = payment.id
Notice that log.Item.class and payment.class would refer to the values of completely different database columns in the above query.
注意在上述的查询中 log.Item.class 与 payment.class 将会引用完全不同的两个数据库的值
Expressions allowed in the where clause include most of the kind of things you could write in SQL:
表达式允许在 where 子句中包含你可以写在 SQL 中的许多东西。
-
mathematical operators - 算术运算符 +, -, *, /
-
binary comparison operators - 二元比较运算符 =, >=, <=, <>, !=, like
-
logical operations - 逻辑运算符 and, or, not
-
string concatenation - 字符连接 ||
-
SQL scalar functions like - SQL 标量函数像 upper() and lower()
-
Parentheses ( ) indicate grouping - 圆括号表明成组
-
in, between, is null
-
positional parameters - 定位参数 ?
-
named parameters - 命名参数 :name, :start_date, :x1
-
SQL literals - SQL 字面值 'foo', 69, '1970-01-01 10:00:01.0'
-
Enumeration values and constants - 枚举值和常量 Eg.Color.Tabby
in and between may be used as follows:
in 和 between 可以如下使用:
from Eg.DomesticCat cat where cat.Name in ( 'Foo', 'Bar', 'Baz' )
and the negated forms may be written
否定形式可写成
from Eg.DomesticCat cat where cat.Name not in ( 'Foo', 'Bar', 'Baz' )
Likewise, is null and is not null may be used to test for null values.
同样,is null 和 is not null 可以用于测试空值。
Booleans may be easily used in expressions by declaring HQL query substitutions in NHibernate configuration:
布尔值可以在表达式中使用在 NHibernate 配置文件中声明的 HQL 查询替代内容
This will replace the keywords true and false with the literals 1 and 0 in the translated SQL from this HQL:
在从(下面)这个 HQL 转换成 SQL 时(上面)这个设置会将关键字 true 和 false 用字面值 1 和 0 来替换:
You may test the size of a collection with the special property size, or the special size() function.
你可以通过特定的 size 属性,或是通过这个特别的 size() 函数来测量集合的大小。
from Eg.Cat cat where size(cat.Kittens) > 0
For indexed collections, you may refer to the minimum and maximum indices using minIndex and maxIndex. Similarly, you may refer to the minimum and maximum elements of a collection of basic type using minElement and maxElement.
对于集合来讲,你可能会使用最小索引和最大索引来引用最小值和最大值。同样,你可以通过使用 minElement 和 maxElement 来引用集合当中最小的和最大的基本类型的元素。
There are also functional forms (which, unlike the constructs above, are not case sensitive):
当然也有函数形式(此种形式,不仅结构与上面的不同,而且大小写不敏感):
from Order order where minelement(order.Items) > 10000
The SQL functions any, some, all, exists, in are supported when passed the element or index set of a collection (elements and indices functions) or the result of a subquery (see below).
SQL中的 any,some,all,exists,in 功能适用于传递元素或索引的 set 集合(元素和 indices 函数)或是子查询的结果集。(如下所示)
select p from Eg.NameList list, Eg.Person p where p.Name = some elements(list.Names)
from Eg.Cat cat where exists elements(cat.Kittens)
from Eg.Player p where 3 > all elements(p.Scores)
from Eg.Show show where 'fizard' in indices(show.Acts)
Note that these constructs - size, elements, indices, minIndex, maxIndex, minElement, maxElement - have certain usage restrictions:
注意这些结构 - size, elements, indices, minIndex, maxIndex, minElement, maxElement - 使用上有着一定的限定条件:
-
in a where clause: only for databases with subselects
在 where 子句:仅用于数据库子查询 -
in a select clause: only elements and indices make sense
在 select 子句:仅 elements and indices 有意义
Elements of indexed collections (arrays, lists, maps) may be referred to by index (in a where clause only):
索引集合元素(arrays, lists, maps)可以通过索引来引用(仅在 where 子句):
select person from Person person, Calendar calendar
where calendar.Holidays['national day'] = person.BirthDay
and person.Nationality.Calendar = calendar
select item from Item item, Order order
where order.Items[ order.DeliveredItemIndices[0] ] = item
and order.id = 11
select item from Item item, Order order
where order.Items[ maxindex(order.items) ] = item
and order.id = 11
The expression inside [] may even be an arithmetic expression.
在 [] 中的表达式甚到可以是数学表达式。
HQL also provides the built-in index() function, for elements of a one-to-many association or collection of values.
HQL 也提供内建的 index() 函数,用于一对多关联或集合值。
Scalar SQL functions supported by the underlying database may be used
标量 SQL 函数通过底层数据库支持可能被用作
If you are not yet convinced by all this, think how much longer and less readable the following query would be in SQL:
如果这都不让你信服,想想下面的查询如果是用 SQL 将会有多长多难懂:
where prod.Name = 'widget'
and store.Location.Name in ( 'Melbourne', 'Sydney' )
and prod = all elements(cust.CurrentOrder.LineItems)
Hint: something like
提示:有点像
FROM customers cust, stores store, locations loc, store_customers sc, product prod
WHERE prod.name = 'widget'
AND store.loc_id = loc.id
AND loc.name IN ( 'Melbourne', 'Sydney' )
AND sc.store_id = store.id
AND sc.cust_id = cust.id
AND prod.id = ALL( SELECT item.prod_id
FROM line_items item, orders o
WHERE item.order_id = o.id
AND cust.current_order = o.id )
11.9. The order by clause - order by (排序)子句
The list returned by a query may be ordered by any property of a returned class or components:
列表将会返回通过一个按某一属性排序过的类或组件的查询:
The optional asc or desc indicate ascending or descending order respectively.
可选参数 acs 或 desc 分别表示升序或是降序。
A query that returns aggregate values may be grouped by any property of a returned class or components:
select cat.Color, sum(cat.Weight), count(cat) from Eg.Cat cat group by cat.Color select foo.id, avg( elements(foo.Names) ), max( indices(foo.Names) ) from Eg.Foo foo group by foo.idNote: You may use the elements and indices constructs inside a select clause, even on databases with no subselects.
A having clause is also allowed.
select cat.color, sum(cat.Weight), count(cat) from Eg.Cat cat group by cat.Color having cat.Color in (Eg.Color.Tabby, Eg.Color.Black)SQL functions and aggregate functions are allowed in the having and order by clauses, if supported by the underlying database (ie. not in MySQL).
select cat from Eg.Cat cat join cat.Kittens kitten group by cat.Id, cat.Name, cat.Other, cat.Properties having avg(kitten.Weight) > 100 order by count(kitten) asc, sum(kitten.Weight) descNote that neither the group by clause nor the order by clause may contain arithmetic expressions. Also note that NHibernate currently does not expand a grouped entity, so you can't write group by cat if all properties of cat are non-aggregated. You have to list all non-aggregated properties explicitly.
For databases that support subselects, NHibernate supports subqueries within queries. A subquery must be surrounded by parentheses (often by an SQL aggregate function call). Even correlated subqueries (subqueries that refer to an alias in the outer query) are allowed.
from Eg.Cat as fatcat where fatcat.Weight > ( select avg(cat.Weight) from Eg.DomesticCat cat ) from Eg.DomesticCat as cat where cat.Name = some ( select name.NickName from Eg.Name as name ) from Eg.Cat as cat where not exists ( from eg.Cat as mate where mate.Mate = cat ) from Eg.DomesticCat as cat where cat.Name not in ( select name.NickName from Eg.Name as name )NHibernate queries can be quite powerful and complex. In fact, the power of the query language is one of NHibernate's main selling points. Here are some example queries very similar to queries that I used on a recent project. Note that most queries you will write are much simpler than these!
The following query returns the order id, number of items and total value of the order for all unpaid orders for a particular customer and given minimum total value, ordering the results by total value. In determining the prices, it uses the current catalog. The resulting SQL query, against the ORDER, ORDER_LINE, PRODUCT, CATALOG and PRICE tables has four inner joins and an (uncorrelated) subselect.
select order.id, sum(price.Amount), count(item) from Order as order join order.LineItems as item join item.Product as product, Catalog as catalog join catalog.Prices as price where order.Paid = false and order.Customer = :customer and price.Product = product and catalog.EffectiveDate < sysdate and catalog.EffectiveDate >= all ( select cat.EffectiveDate from Catalog as cat where cat.EffectiveDate < sysdate ) group by order having sum(price.Amount) > :minAmount order by sum(price.Amount) descWhat a monster! Actually, in real life, I'm not very keen on subqueries, so my query was really more like this:
select order.id, sum(price.amount), count(item) from Order as order join order.LineItems as item join item.Product as product, Catalog as catalog join catalog.Prices as price where order.Paid = false and order.Customer = :customer and price.Product = product and catalog = :currentCatalog group by order having sum(price.Amount) > :minAmount order by sum(price.Amount) descThe next query counts the number of payments in each status, excluding all payments in the AwaitingApproval status where the most recent status change was made by the current user. It translates to an SQL query with two inner joins and a correlated subselect against the PAYMENT, PAYMENT_STATUS and PAYMENT_STATUS_CHANGE tables.
select count(payment), status.Name from Payment as payment join payment.CurrentStatus as status join payment.StatusChanges as statusChange where payment.Status.Name <> PaymentStatus.AwaitingApproval or ( statusChange.TimeStamp = ( select max(change.TimeStamp) from PaymentStatusChange change where change.Payment = payment ) and statusChange.User <> :currentUser ) group by status.Name, status.SortOrder order by status.SortOrderIf I would have mapped the StatusChanges collection as a list, instead of a set, the query would have been much simpler to write.
select count(payment), status.Name from Payment as payment join payment.CurrentStatus as status where payment.Status.Name <> PaymentStatus.AwaitingApproval or payment.StatusChanges[ maxIndex(payment.StatusChanges) ].User <> :currentUser group by status.Name, status.SortOrder order by status.SortOrderThe next query uses the MS SQL Server isNull() function to return all the accounts and unpaid payments for the organization to which the current user belongs. It translates to an SQL query with three inner joins, an outer join and a subselect against the ACCOUNT, PAYMENT, PAYMENT_STATUS, ACCOUNT_TYPE, ORGANIZATION and ORG_USER tables.
select account, payment from Account as account left outer join account.Payments as payment where :currentUser in elements(account.Holder.Users) and PaymentStatus.Unpaid = isNull(payment.CurrentStatus.Name, PaymentStatus.Unpaid) order by account.Type.SortOrder, account.AccountNumber, payment.DueDateFor some databases, we would need to do away with the (correlated) subselect.
select account, payment from Account as account join account.Holder.Users as user left outer join account.Payments as payment where :currentUser = user and PaymentStatus.Unpaid = isNull(payment.CurrentStatus.Name, PaymentStatus.Unpaid) order by account.Type.SortOrder, account.AccountNumber, payment.DueDateYou can count the number of query results without actually returning them:
int count = (int) session.CreateQuery("select count(*) from ....").UniqueResult();To order a result by the size of a collection, use the following query:
select usr.id, usr.Name from User as usr left join usr.Messages as msg group by usr.id, usr.Name order by count(msg)If your database supports subselects, you can place a condition upon selection size in the where clause of your query:
from User usr where size(usr.Messages) >= 1If your database doesn't support subselects, use the following query:
select usr.id, usr.Name from User usr join usr.Messages msg group by usr.id, usr.Name having count(msg) >= 1As this solution can't return a User with zero messages because of the inner join, the following form is also useful:
select usr.id, usr.Name from User as usr left join usr.Messages as msg group by usr.id, usr.Name having count(msg) = 0Properties of an object can be bound to named query parameters:
IQuery q = s.CreateQuery("from foo in class Foo where foo.Name=:Name and foo.Size=:Size"); q.SetProperties(fooBean); // fooBean has properties Name and Size IList foos = q.List();Collections are pageable by using the IQuery interface with a filter:
IQuery q = s.CreateFilter( collection, "" ); // the trivial filter q.setMaxResults(PageSize); q.setFirstResult(PageSize * pageNumber); IList page = q.List();Collection elements may be ordered or grouped using a query filter:
ICollection orderedCollection = s.Filter( collection, "order by this.Amount" ); ICollection counts = s.Filter( collection, "select this.Type, count(this) group by this.Type" );原文出处:https://www.hibernate.org/hib_docs/nhibernate/1.2/reference/en/html/queryhql.html