forked from nhibernate/nhibernate-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_parentchild.xml
431 lines (358 loc) · 15.9 KB
/
example_parentchild.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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
<chapter id="example-parentchild">
<title>Example: Parent/Child</title>
<para>
One of the first things that new users want to do with NHibernate is to model a parent/child type
relationship. There are two different approaches to this. The most convenient
approach, especially for new users, is to model both <literal>Parent</literal> and <literal>Child</literal>
as entity classes with a <literal><one-to-many></literal> association from <literal>Parent</literal>
to <literal>Child</literal>. The alternative approach is to declare the <literal>Child</literal> as a
<literal><composite-element></literal>. The default semantics of a one to many
association in NHibernate are much less close to the usual semantics of a parent/child relationship than
those of a composite element mapping. We will explain how to use a <emphasis>bidirectional one to many
association with cascades</emphasis> to model a parent/child relationship efficiently and elegantly.
</para>
<sect1 id="example-parentchild-collections">
<title>A note about collections</title>
<para>
NHibernate collections are considered to be a logical part of their owning entity and not of the
contained entities. Be aware that this is a critical distinction that has the following consequences:
</para>
<itemizedlist>
<listitem>
<para>
When you remove/add an object from/to a collection, the version number of the collection owner
is incremented.
</para>
</listitem>
<listitem>
<para>
If an object that was removed from a collection is an instance of a value type (e.g., a composite
element), that object will cease to be persistent and its state will be completely removed from
the database. Likewise, adding a value type instance to the collection will cause its state to
be immediately persistent.
</para>
</listitem>
<listitem>
<para>
Conversely, if an entity is removed from a collection (a one-to-many or many-to-many
association), it will not be deleted by default. This behavior is completely consistent; a
change to the internal state of another entity should not cause the associated entity to vanish.
Likewise, adding an entity to a collection does not cause that entity to become persistent, by
default.
</para>
</listitem>
</itemizedlist>
<para>
Adding an entity to a collection, by default, merely creates a link between the two entities. Removing
the entity will remove the link. This is appropriate for all sorts of cases. However, it is not
appropriate in the case of a parent/child relationship. In this case, the life of the child is bound to
the life cycle of the parent.
</para>
</sect1>
<sect1 id="example-parentchild-bidir">
<title>Bidirectional one-to-many</title>
<para>
Suppose we start with a simple <literal><one-to-many></literal> association from
<literal>Parent</literal> to <literal>Child</literal>.
</para>
<programlisting><![CDATA[<set name="Children">
<key column="parent_id" />
<one-to-many class="Child" />
</set>]]></programlisting>
<para>
If we were to execute the following code:
</para>
<programlisting><![CDATA[Parent p = ...;
Child c = new Child();
p.Children.Add(c);
session.Save(c);
session.Flush();]]></programlisting>
<para>
NHibernate would issue two SQL statements:
</para>
<itemizedlist>
<listitem>
<para>an <literal>INSERT</literal> to create the record for <literal>c</literal></para>
</listitem>
<listitem>
<para>
an <literal>UPDATE</literal> to create the link from <literal>p</literal> to
<literal>c</literal>
</para>
</listitem>
</itemizedlist>
<para>
This is not only inefficient, but also violates any <literal>NOT NULL</literal> constraint on the
<literal>parent_id</literal> column. You can fix the nullability constraint violation by specifying
<literal>not-null="true"</literal> in the collection mapping:
</para>
<programlisting><![CDATA[<set name="Children">
<key column="parent_id" not-null="true"/>
<one-to-many class="Child"/>
</set>]]></programlisting>
<para>
However, this is not the recommended solution.
</para>
<para>
The underlying cause of this behavior is that the link (the foreign key
<literal>parent_id</literal>) from <literal>p</literal> to <literal>c</literal> is not considered
part of the state of the <literal>Child</literal> object and is therefore not created in the
<literal>INSERT</literal>. The solution is to make the link part of the <literal>Child</literal>
mapping.
</para>
<programlisting><![CDATA[<many-to-one name="Parent" column="parent_id" not-null="true"/>]]></programlisting>
<para>
You also need to add the <literal>Parent</literal> property to the <literal>Child</literal> class.
</para>
<para>
Now that the <literal>Child</literal> entity is managing the state of the link, we tell the collection not
to update the link. We use the <literal>inverse</literal> attribute to do this:
</para>
<programlisting><![CDATA[<set name="Children" inverse="true">
<key column="parent_id"/>
<one-to-many class="Child"/>
</set>]]></programlisting>
<para>
The following code would be used to add a new <literal>Child</literal>:
</para>
<programlisting><![CDATA[Parent p = session.Load<Parent>(pid);
Child c = new Child();
c.Parent = p;
p.Children.Add(c);
session.Save(c);
session.Flush();]]></programlisting>
<para>
Only one SQL <literal>INSERT</literal> would now be issued.
</para>
<para>
You could also create an <literal>AddChild()</literal> method of <literal>Parent</literal>.
</para>
<programlisting><![CDATA[public void AddChild(Child c)
{
c.Parent = this;
children.Add(c);
}]]></programlisting>
<para>
The code to add a <literal>Child</literal> looks like
</para>
<programlisting><![CDATA[Parent p = session.Load<Parent>(pid);
Child c = new Child();
p.AddChild(c);
session.Save(c);
session.Flush();]]></programlisting>
</sect1>
<sect1 id="example-parentchild-cascades">
<title>Cascading lifecycle</title>
<para>
You can address the frustrations of the explicit call to <literal>Save()</literal> by using
cascades.
</para>
<programlisting><![CDATA[<set name="Children" inverse="true" cascade="all">
<key column="parent_id"/>
<one-to-many class="Child"/>
</set>]]></programlisting>
<para>
This simplifies the code above to:
</para>
<programlisting><![CDATA[Parent p = session.Load<Parent>(pid);
Child c = new Child();
p.AddChild(c);
session.Flush();]]></programlisting>
<para>
Similarly, we do no more need to iterate over the children when saving or deleting a
<literal>Parent</literal>. The following removes <literal>p</literal> and all its children
from the database.
</para>
<programlisting><![CDATA[Parent p = session.Load<Parent>(pid);
session.Delete(p);
session.Flush();]]></programlisting>
<para>
However, the following code:
</para>
<programlisting><![CDATA[Parent p = session.Load<Parent>(pid);
// Get one child out of the set
Child c = p.Children.First();
p.Children.Remove(c);
c.Parent = null;
session.Flush();]]></programlisting>
<para>
will not remove <literal>c</literal> from the database. In this case, it will only remove
the link to <literal>p</literal> and cause a <literal>NOT NULL</literal> constraint violation.
You need to explicitly <literal>Delete()</literal> the <literal>Child</literal>.
</para>
<programlisting><![CDATA[Parent p = session.Load<Parent>(pid);
// Get one child out of the set
Child c = p.Children.First();
p.Children.Remove(c);
session.Delete(c);
session.Flush();]]></programlisting>
<para>
In our case, a <literal>Child</literal> cannot exist without its parent. So if we remove a
<literal>Child</literal> from the collection, we do want it to be deleted. To do this, we must
use <literal>cascade="all-delete-orphan"</literal>.
</para>
<programlisting><![CDATA[<set name="Children" inverse="true" cascade="all-delete-orphan">
<key column="parent_id"/>
<one-to-many class="Child"/>
</set>]]></programlisting>
<para>
Even though the collection mapping specifies <literal>inverse="true"</literal>, cascades are still
processed by iterating the collection elements. If you need an object be saved, deleted or
updated by cascade, you must add it to the collection. It is not enough to simply set its parent.
</para>
</sect1>
<sect1 id="example-parentchild-update">
<title>Using cascading <literal>Update()</literal></title>
<para>
Suppose we loaded up a <literal>Parent</literal> in one <literal>ISession</literal>, made some
changes in a UI action and wanted to persist these changes in a new <literal>ISession</literal>
by calling <literal>Update()</literal>. The <literal>Parent</literal> will contain a collection
of children and, since the cascading update is enabled, NHibernate needs to know which children
are newly instantiated and which represent existing rows in the database. We will also assume
that both <literal>Parent</literal> and <literal>Child</literal> have generated identifier
properties of type <literal>long</literal>. NHibernate will use the identifier and
version/timestamp property value to determine which of the children are new. (See
<xref linkend="manipulatingdata-updating-detached"/>.)
</para>
<para>
The <literal>unsaved-value</literal> attribute is used to specify the identifier value of a newly
instantiated instance. <emphasis>In NHibernate it is not necessary to specify
<literal>unsaved-value</literal> explicitly.</emphasis>
</para>
<para>
The following code will update <literal>parent</literal> and <literal>child</literal> and insert
<literal>newChild</literal>.
</para>
<programlisting><![CDATA[//parent and child were both loaded in a previous session
parent.AddChild(child);
Child newChild = new Child();
parent.AddChild(newChild);
session.Update(parent);
session.Flush();]]></programlisting>
<para>
This may be suitable for the case of a generated identifier, but what about assigned identifiers
and composite identifiers? This is more difficult, since NHibernate cannot use the identifier
property to distinguish between a newly instantiated object, with an identifier assigned by the
user, and an object loaded in a previous session. In this case, NHibernate will either use the
timestamp or version property, or will actually query the second-level cache or, worst case, the
database, to see if the row exists.
</para>
<para>
To avoid the worst case, either:
</para>
<itemizedlist>
<listitem>
<para>
define an <literal>unsaved-value</literal> on a <literal><version></literal>
or <literal><timestamp></literal> property mapping for the class.
</para>
</listitem>
<listitem>
<para>
set <literal>unsaved-value="none"</literal> and explicitly <literal>Save()</literal>
newly instantiated children before calling <literal>Update(parent)</literal>.
</para>
</listitem>
<listitem>
<para>
set <literal>unsaved-value="any"</literal> and explicitly <literal>Update()</literal>
previously persistent children before calling <literal>Update(parent)</literal>.
</para>
</listitem>
<listitem>
<para>
implement <literal>IInterceptor.IsTransient()</literal> for providing your own strategy
for distinguishing newly instantiated objects.
</para>
</listitem>
</itemizedlist>
<para>
For the <literal>IInterceptor</literal> solution, you could by example define a base class for
your persistent classes:
</para>
<programlisting><![CDATA[public class Persistent
{
private bool _saved = false;
public virtual void OnSave()
{
_saved = true;
}
public virtual void OnLoad()
{
_saved = true;
}
public virtual void OnDelete()
{
_saved = false;
}
...
public virtual bool IsSaved
{
get { return _saved; }
}
}]]></programlisting>
<para>
(The <literal>saved</literal> property is non-persistent.)
Then implement in you interceptor class <literal>IsTransient()</literal>, along with
<literal>OnLoad()</literal>, <literal>OnSave()</literal> and <literal>OnDelete()</literal>
as follows:
</para>
<programlisting><![CDATA[public object IsTransient(object entity)
{
if (entity is Persistent)
{
return !((Persistent) entity).IsSaved;
}
else
{
return null;
}
}
public bool OnLoad(object entity,
object id,
object[] state,
string[] propertyNames,
IType[] types)
{
if (entity is Persistent)
((Persistent) entity).OnLoad();
return false;
}
public boolean OnSave(object entity,
object id,
object[] state,
string[] propertyNames,
IType[] types)
{
if (entity is Persistent)
((Persistent) entity).OnSave();
return false;
}
public virtual void OnDelete(object entity,
object id,
object[] state,
string[] propertyNames,
IType[] types)
{
if (entity is Persistent)
((Persistent) entity).OnDelete();
}]]></programlisting>
<para>
See <xref linkend="objectstate-interceptors"/> for more information.
</para>
</sect1>
<sect1 id="example-parentchild-conclusion">
<title>Conclusion</title>
<para>
There is quite a bit to digest here and it might look confusing first time around. However, in practice, it
all works out quite nicely. Most NHibernate applications use the parent / child pattern in many places.
</para>
<para>
We mentioned an alternative in the first paragraph. None of the above issues exist in the case of
<literal><composite-element></literal> mappings, which have exactly the semantics of a parent/child
relationship. Unfortunately, there are two big limitations to composite element classes: composite elements
cannot own collections, and they should not be the child of any entity other than the unique parent. (However,
they <emphasis>may</emphasis> have a surrogate primary key, using an <literal><idbag></literal> mapping.)
</para>
</sect1>
</chapter>