forked from nhibernate/nhibernate-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquery_criteria.xml
389 lines (319 loc) · 14.4 KB
/
query_criteria.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
<chapter id="querycriteria">
<title>Criteria Queries</title>
<para>
NHibernate features an intuitive, extensible criteria query API.
</para>
<sect1 id="querycriteria-creating">
<title>Creating an <literal>ICriteria</literal> instance</title>
<para>
The interface <literal>NHibernate.ICriteria</literal> represents a query against
a particular persistent class. The <literal>ISession</literal> is a factory for
<literal>ICriteria</literal> instances.
</para>
<programlisting><![CDATA[ICriteria crit = sess.CreateCriteria<Cat>();
crit.SetMaxResults(50);
var cats = crit.List<Cat>();]]></programlisting>
</sect1>
<sect1 id="querycriteria-narrowing">
<title>Narrowing the result set</title>
<para>
An individual query criterion is an instance of the interface
<literal>NHibernate.Expression.ICriterion</literal>. The class
<literal>NHibernate.Expression.Expression</literal> defines
factory methods for obtaining certain built-in
<literal>ICriterion</literal> types.
</para>
<programlisting><![CDATA[var cats = sess.CreateCriteria<Cat>()
.Add( Expression.Like("Name", "Fritz%") )
.Add( Expression.Between("Weight", minWeight, maxWeight) )
.List<Cat>();]]></programlisting>
<para>
Expressions may be grouped logically.
</para>
<programlisting><![CDATA[var cats = sess.CreateCriteria<Cat>()
.Add( Expression.Like("Name", "Fritz%") )
.Add( Expression.Or(
Expression.Eq( "Age", 0 ),
Expression.IsNull("Age")
) )
.List<Cat>();]]></programlisting>
<programlisting><![CDATA[var cats = sess.CreateCriteria<Cat>()
.Add( Expression.In( "Name", new String[] { "Fritz", "Izi", "Pk" } ) )
.Add( Expression.Disjunction()
.Add( Expression.IsNull("Age") )
.Add( Expression.Eq("Age", 0 ) )
.Add( Expression.Eq("Age", 1 ) )
.Add( Expression.Eq("Age", 2 ) )
) )
.List<Cat>();]]></programlisting>
<para>
There are quite a range of built-in criterion types (<literal>Expression</literal>
subclasses), but one that is especially useful lets you specify SQL directly.
</para>
<programlisting><![CDATA[// Create a string parameter for the SqlString below
var cats = sess.CreateCriteria<Cat>()
.Add(Expression.Sql("lower({alias}.Name) like lower(?)",
"Fritz%", NHibernateUtil.String))
.List<Cat>();]]></programlisting>
<para>
The <literal>{alias}</literal> placeholder with be replaced by the row alias
of the queried entity.
</para>
</sect1>
<sect1 id="querycriteria-ordering">
<title>Ordering the results</title>
<para>
You may order the results using <literal>NHibernate.Expression.Order</literal>.
</para>
<programlisting><![CDATA[var cats = sess.CreateCriteria<Cat>()
.Add( Expression.Like("Name", "F%")
.AddOrder( Order.Asc("Name") )
.AddOrder( Order.Desc("Age") )
.SetMaxResults(50)
.List<Cat>();]]></programlisting>
</sect1>
<sect1 id="querycriteria-associations">
<title>Associations</title>
<para>
You may easily specify constraints upon related entities by navigating
associations using <literal>CreateCriteria()</literal>.
</para>
<programlisting><![CDATA[var cats = sess.CreateCriteria<Cat>()
.Add( Expression.Like("Name", "F%")
.CreateCriteria("Kittens")
.Add( Expression.Like("Name", "F%") )
.List<Cat>();]]></programlisting>
<para>
Note that the second <literal>CreateCriteria()</literal> returns a new
instance of <literal>ICriteria</literal>, which refers to the elements of
the <literal>Kittens</literal> collection.
</para>
<para>
The following, alternate form is useful in certain circumstances.
</para>
<programlisting><![CDATA[var cats = sess.CreateCriteria<Cat>()
.CreateAlias("Kittens", "kt")
.CreateAlias("Mate", "mt")
.Add( Expression.EqProperty("kt.Name", "mt.Name") )
.List<Cat>();]]></programlisting>
<para>
(<literal>CreateAlias()</literal> does not create a new instance of
<literal>ICriteria</literal>.)
</para>
<para>
Note that the kittens collections held by the <literal>Cat</literal> instances
returned by the previous two queries are <emphasis>not</emphasis> pre-filtered
by the criteria! If you wish to retrieve just the kittens that match the
criteria, you must use <literal>SetResultTransformer(Transformers.AliasToEntityMap)</literal>.
</para>
<programlisting><![CDATA[var cats = sess.CreateCriteria<Cat>()
.CreateCriteria("Kittens", "kt")
.Add( Expression.Eq("Name", "F%") )
.SetResultTransformer(Transformers.AliasToEntityMap)
.List<IDictionary>();
foreach ( IDictionary map in cats )
{
Cat cat = (Cat) map[CriteriaSpecification.RootAlias];
Cat kitten = (Cat) map["kt"];
}]]></programlisting>
<para>
Note that for retrieving just kittens you can also use an entity projection.
See <xref linkend="querycriteria-projection"/> for more information.
</para>
</sect1>
<sect1 id="querycriteria_entityjoin">
<title>Join entities without association (Entity joins or ad hoc joins)</title>
<para>
In criteria you have the ability to define a join to any entity, not just through a mapped association.
To achieve it, use <literal>CreateEntityAlias</literal> and <literal>CreateEntityCriteria</literal>. By example:
</para>
<programlisting><![CDATA[IList<Cat> uniquelyNamedCats = sess.CreateCriteria<Cat>("c")
.CreateEntityAlias(
"joinedCat",
Restrictions.And(
Restrictions.EqProperty("c.Name", "joinedCat.Name"),
Restrictions.NotEqProperty("c.Id", "joinedCat.Id")),
JoinType.LeftOuterJoin,
typeof(Cat).FullName)
.Add(Restrictions.IsNull("joinedCat.Id"))
.List();]]></programlisting>
</sect1>
<sect1 id="querycriteria-dynamicfetching">
<title>Dynamic association fetching</title>
<para>
You may specify association fetching semantics at runtime using
<literal>SetFetchMode()</literal>.
</para>
<programlisting><![CDATA[var cats = sess.CreateCriteria<Cat>()
.Add( Expression.Like("Name", "Fritz%") )
.SetFetchMode("Mate", FetchMode.Eager)
.SetFetchMode("Kittens", FetchMode.Eager)
.List<Cat>();]]></programlisting>
<para>
This query will fetch both <literal>Mate</literal> and <literal>Kittens</literal>
by outer join. See <xref linkend="performance-fetching"/> for more information.
</para>
</sect1>
<sect1 id="querycriteria-examples">
<title>Example queries</title>
<para>
The class <literal>NHibernate.Expression.Example</literal> allows
you to construct a query criterion from a given instance.
</para>
<programlisting><![CDATA[Cat cat = new Cat();
cat.Sex = 'F';
cat.Color = Color.Black;
var results = session.CreateCriteria<Cat>()
.Add( Example.Create(cat) )
.List<Cat>();]]></programlisting>
<para>
Version properties, identifiers and associations are ignored. By default,
null-valued properties and properties which return an empty string from
the call to <code>ToString()</code> are excluded.
</para>
<para>
You can adjust how the <literal>Example</literal> is applied.
</para>
<programlisting><![CDATA[Example example = Example.Create(cat)
.ExcludeZeroes() //exclude null- or zero-valued properties
.ExcludeProperty("Color") //exclude the property named "color"
.IgnoreCase() //perform case insensitive string comparisons
.EnableLike(); //use like for string comparisons
var results = session.CreateCriteria<Cat>()
.Add(example)
.List<Cat>();]]></programlisting>
<para>
You can even use examples to place criteria upon associated objects.
</para>
<programlisting><![CDATA[var results = session.CreateCriteria<Cat>()
.Add( Example.Create(cat) )
.CreateCriteria("Mate")
.Add( Example.Create( cat.Mate ) )
.List<Cat>();]]></programlisting>
</sect1>
<sect1 id="querycriteria-projection">
<title>Projections, aggregation and grouping</title>
<para>
The class <literal>NHibernate.Expression.Projections</literal> is a
factory for <literal>IProjection</literal> instances. We apply a
projection to a query by calling <literal>SetProjection()</literal>.
</para>
<programlisting><![CDATA[var results = session.CreateCriteria<Cat>()
.SetProjection( Projections.RowCount() )
.Add( Expression.Eq("Color", Color.BLACK) )
.List<int>();]]></programlisting>
<programlisting><![CDATA[var results = session.CreateCriteria<Cat>()
.SetProjection( Projections.ProjectionList()
.Add( Projections.RowCount() )
.Add( Projections.Avg("Weight") )
.Add( Projections.Max("Weight") )
.Add( Projections.GroupProperty("Color") )
)
.List<object[]>();]]></programlisting>
<para>
There is no explicit "group by" necessary in a criteria query. Certain
projection types are defined to be <emphasis>grouping projections</emphasis>,
which also appear in the SQL <literal>group by</literal> clause.
</para>
<para>
An alias may optionally be assigned to a projection, so that the projected value
may be referred to in restrictions or orderings. Here are two different ways to
do this:
</para>
<programlisting><![CDATA[var results = session.CreateCriteria<Cat>()
.SetProjection( Projections.Alias( Projections.GroupProperty("Color"), "colr" ) )
.AddOrder( Order.Asc("colr") )
.List<string>();]]></programlisting>
<programlisting><![CDATA[var results = session.CreateCriteria<Cat>()
.SetProjection( Projections.GroupProperty("Color").As("colr") )
.AddOrder( Order.Asc("colr") )
.List<string>();]]></programlisting>
<para>
The <literal>Alias()</literal> and <literal>As()</literal> methods simply wrap a
projection instance in another, aliased, instance of <literal>IProjection</literal>.
As a shortcut, you can assign an alias when you add the projection to a
projection list:
</para>
<programlisting><![CDATA[var results = session.CreateCriteria<Cat>()
.SetProjection( Projections.ProjectionList()
.Add( Projections.RowCount(), "catCountByColor" )
.Add( Projections.Avg("Weight"), "avgWeight" )
.Add( Projections.Max("Weight"), "maxWeight" )
.Add( Projections.GroupProperty("Color"), "color" )
)
.AddOrder( Order.Desc("catCountByColor") )
.AddOrder( Order.Desc("avgWeight") )
.List<object[]>();]]></programlisting>
<programlisting><![CDATA[var results = session.CreateCriteria(typeof(DomesticCat), "cat")
.CreateAlias("kittens", "kit")
.SetProjection( Projections.ProjectionList()
.Add( Projections.Property("cat.Name"), "catName" )
.Add( Projections.Property("kit.Name"), "kitName" )
)
.AddOrder( Order.Asc("catName") )
.AddOrder( Order.Asc("kitName") )
.List<object[]>();]]></programlisting>
<para>
You can also add an entity projection to a criteria query:
</para>
<programlisting><![CDATA[var kittens = sess.CreateCriteria<Cat>()
.CreateCriteria("Kittens", "kt")
.Add(Expression.Eq("Name", "F%"))
.SetProjection(Projections.Entity(typeof(Cat), "kt"))
.List();]]></programlisting>
<programlisting><![CDATA[var cats = sess.CreateCriteria<Cat>()
.CreateCriteria("Kittens", "kt")
.Add(Expression.Eq("Name", "F%"))
.SetProjection(
Projections.RootEntity(),
Projections.Entity(typeof(Cat), "kt"))
.List<object[]>();
foreach (var objs in cats)
{
Cat cat = (Cat) objs[0];
Cat kitten = (Cat) objs[1];
}]]></programlisting>
<para>
See <xref linkend="queryqueryover-projectionentities"/> for more information.
</para>
</sect1>
<sect1 id="querycriteria-detachedqueries">
<title>Detached queries and sub-queries</title>
<para>
The <literal>DetachedCriteria</literal> class lets you create a query outside the scope
of a session, and then later execute it using some arbitrary <literal>ISession</literal>.
</para>
<programlisting><![CDATA[DetachedCriteria query = DetachedCriteria.For<Cat>()
.Add( Expression.Eq("sex", 'F') );
using (ISession session = ....)
using (ITransaction txn = session.BeginTransaction())
{
var results = query.GetExecutableCriteria(session).SetMaxResults(100).List<Cat>();
txn.Commit();
}]]></programlisting>
<para>
A <literal>DetachedCriteria</literal> may also be used to express a sub-query. ICriterion
instances involving sub-queries may be obtained via <literal>Subqueries</literal>.
<!-- or <literal>Property</literal>.-->
</para>
<programlisting><![CDATA[DetachedCriteria avgWeight = DetachedCriteria.For<Cat>()
.SetProjection( Projections.Avg("Weight") );
session.CreateCriteria<Cat>()
.Add( Subqueries.Gt("Weight", avgWeight) )
.List<Cat>();]]></programlisting>
<programlisting><![CDATA[DetachedCriteria weights = DetachedCriteria.For<Cat>()
.SetProjection( Projections.Property("Weight") );
session.CreateCriteria<Cat>()
.Add( Subqueries.GeAll("Weight", weights) )
.List<Cat>();]]></programlisting>
<para>
Even correlated sub-queries are possible:
</para>
<programlisting><![CDATA[DetachedCriteria avgWeightForSex = DetachedCriteria.For<Cat>("cat2")
.SetProjection( Projections.Avg("Weight") )
.Add( Expression.EqProperty("cat2.Sex", "cat.Sex") );
session.CreateCriteria(typeof(Cat), "cat")
.Add( Subqueries.Gt("weight", avgWeightForSex) )
.List<Cat>();]]></programlisting>
</sect1>
</chapter>