-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
Cascade.java
599 lines (559 loc) · 19.7 KB
/
Cascade.java
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.engine.internal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.bytecode.enhance.spi.interceptor.LazyAttributeLoadingInterceptor;
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.spi.CascadeStyle;
import org.hibernate.engine.spi.CascadingAction;
import org.hibernate.engine.spi.CollectionEntry;
import org.hibernate.engine.spi.EntityEntry;
import org.hibernate.engine.spi.PersistenceContext;
import org.hibernate.engine.spi.Status;
import org.hibernate.event.spi.EventSource;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.type.AssociationType;
import org.hibernate.type.CollectionType;
import org.hibernate.type.ComponentType;
import org.hibernate.type.CompositeType;
import org.hibernate.type.EntityType;
import org.hibernate.type.ForeignKeyDirection;
import org.hibernate.type.Type;
/**
* Delegate responsible for, in conjunction with the various
* {@link org.hibernate.engine.spi.CascadingAction actions}, implementing cascade processing.
*
* @author Gavin King
* @see org.hibernate.engine.spi.CascadingAction
*/
public final class Cascade {
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( Cascade.class );
private Cascade() {
// NOP
}
/**
* Cascade an action from the parent entity instance to all its children.
*
* @param persister The parent's entity persister
* @param parent The parent reference.
* @throws HibernateException
*/
public static void cascade(
final CascadingAction action, final CascadePoint cascadePoint,
final EventSource eventSource, final EntityPersister persister, final Object parent)
throws HibernateException {
cascade( action, cascadePoint, eventSource, persister, parent, null );
}
/**
* Cascade an action from the parent entity instance to all its children. This
* form is typically called from within cascade actions.
*
* @param persister The parent's entity persister
* @param parent The parent reference.
* @param anything Anything ;) Typically some form of cascade-local cache
* which is specific to each CascadingAction type
*/
public static void cascade(
final CascadingAction action,
final CascadePoint cascadePoint,
final EventSource eventSource,
final EntityPersister persister,
final Object parent,
final Object anything) throws HibernateException {
if ( persister.hasCascades() || action.requiresNoCascadeChecking() ) { // performance opt
final boolean traceEnabled = LOG.isTraceEnabled();
if ( traceEnabled ) {
LOG.tracev( "Processing cascade {0} for: {1}", action, persister.getEntityName() );
}
final PersistenceContext persistenceContext = eventSource.getPersistenceContextInternal();
final Type[] types = persister.getPropertyTypes();
final String[] propertyNames = persister.getPropertyNames();
final CascadeStyle[] cascadeStyles = persister.getPropertyCascadeStyles();
final boolean hasUninitializedLazyProperties = persister.hasUninitializedLazyProperties( parent );
for ( int i = 0; i < types.length; i++) {
final CascadeStyle style = cascadeStyles[ i ];
final String propertyName = propertyNames[ i ];
final boolean isUninitializedProperty =
hasUninitializedLazyProperties &&
!persister.getBytecodeEnhancementMetadata().isAttributeLoaded( parent, propertyName );
final Type type = types[i];
if ( style.doCascade( action ) ) {
final Object child;
if ( isUninitializedProperty ) {
// parent is a bytecode enhanced entity.
// Cascade to an uninitialized, lazy value only if
// parent is managed in the PersistenceContext.
// If parent is a detached entity being merged,
// then parent will not be in the PersistencContext
// (so lazy attributes must not be initialized).
if ( persistenceContext.getEntry( parent ) == null ) {
// parent was not in the PersistenceContext
continue;
}
if ( type.isCollectionType() ) {
// CollectionType#getCollection gets the PersistentCollection
// that corresponds to the uninitialized collection from the
// PersistenceContext. If not present, an uninitialized
// PersistentCollection will be added to the PersistenceContext.
// The action may initialize it later, if necessary.
// This needs to be done even when action.performOnLazyProperty() returns false.
final CollectionType collectionType = (CollectionType) type;
child = collectionType.getCollection(
collectionType.getKeyOfOwner( parent, eventSource ),
eventSource,
parent,
null
);
}
else if ( type.isComponentType() ) {
// Hibernate does not support lazy embeddables, so this shouldn't happen.
throw new UnsupportedOperationException(
"Lazy components are not supported."
);
}
else if ( action.performOnLazyProperty() && type.isEntityType() ) {
// Only need to initialize a lazy entity attribute when action.performOnLazyProperty()
// returns true.
LazyAttributeLoadingInterceptor interceptor = persister.getBytecodeEnhancementMetadata()
.extractInterceptor( parent );
child = interceptor.fetchAttribute( parent, propertyName );
}
else {
// Nothing to do, so just skip cascading to this lazy attribute.
continue;
}
}
else {
child = persister.getPropertyValue( parent, i );
}
cascadeProperty(
action,
cascadePoint,
eventSource,
null,
parent,
child,
type,
style,
propertyName,
anything,
false
);
}
else {
if ( action.requiresNoCascadeChecking() ) {
action.noCascade(
eventSource,
parent,
persister,
type,
i
);
}
// If the property is uninitialized, then there cannot be any orphans.
if ( action.deleteOrphans() && !isUninitializedProperty ) {
cascadeLogicalOneToOneOrphanRemoval(
action,
eventSource,
null,
parent,
persister.getPropertyValue( parent, i ),
type,
style,
propertyName,
false
);
}
}
}
if ( traceEnabled ) {
LOG.tracev( "Done processing cascade {0} for: {1}", action, persister.getEntityName() );
}
}
}
/**
* Cascade an action to the child or children
*/
private static void cascadeProperty(
final CascadingAction action,
final CascadePoint cascadePoint,
final EventSource eventSource,
List<String> componentPath,
final Object parent,
final Object child,
final Type type,
final CascadeStyle style,
final String propertyName,
final Object anything,
final boolean isCascadeDeleteEnabled) throws HibernateException {
if ( child != null ) {
if ( type.isAssociationType() ) {
final AssociationType associationType = (AssociationType) type;
if ( cascadeAssociationNow( cascadePoint, associationType ) ) {
cascadeAssociation(
action,
cascadePoint,
eventSource,
componentPath,
parent,
child,
type,
style,
anything,
isCascadeDeleteEnabled
);
}
}
else if ( type.isComponentType() ) {
if ( componentPath == null ) {
componentPath = new ArrayList<>();
}
componentPath.add( propertyName );
cascadeComponent(
action,
cascadePoint,
eventSource,
componentPath,
parent,
child,
(CompositeType) type,
anything
);
componentPath.remove( componentPath.size() - 1 );
}
}
cascadeLogicalOneToOneOrphanRemoval(
action,
eventSource,
componentPath,
parent,
child,
type,
style,
propertyName,
isCascadeDeleteEnabled );
}
private static void cascadeLogicalOneToOneOrphanRemoval(
final CascadingAction action,
final EventSource eventSource,
final List<String> componentPath,
final Object parent,
final Object child,
final Type type,
final CascadeStyle style,
final String propertyName,
final boolean isCascadeDeleteEnabled) throws HibernateException {
// potentially we need to handle orphan deletes for one-to-ones here...
if ( isLogicalOneToOne( type ) ) {
// We have a physical or logical one-to-one. See if the attribute cascade settings and action-type require
// orphan checking
if ( style.hasOrphanDelete() && action.deleteOrphans() ) {
// value is orphaned if loaded state for this property shows not null
// because it is currently null.
final PersistenceContext persistenceContext = eventSource.getPersistenceContextInternal();
final EntityEntry entry = persistenceContext.getEntry( parent );
if ( entry != null && entry.getStatus() != Status.SAVING ) {
Object loadedValue;
if ( componentPath == null ) {
// association defined on entity
loadedValue = entry.getLoadedValue( propertyName );
}
else {
// association defined on component
// Since the loadedState in the EntityEntry is a flat domain type array
// We first have to extract the component object and then ask the component type
// recursively to give us the value of the sub-property of that object
loadedValue = entry.getLoadedValue( componentPath.get( 0 ) );
ComponentType componentType = (ComponentType) entry.getPersister().getPropertyType( componentPath.get( 0 ) );
if ( componentPath.size() != 1 ) {
for ( int i = 1; i < componentPath.size(); i++ ) {
final int subPropertyIndex = componentType.getPropertyIndex( componentPath.get( i ) );
loadedValue = componentType.getPropertyValue( loadedValue, subPropertyIndex );
componentType = (ComponentType) componentType.getSubtypes()[subPropertyIndex];
}
}
loadedValue = componentType.getPropertyValue( loadedValue, componentType.getPropertyIndex( propertyName ) );
}
// orphaned if the association was nulled (child == null) or receives a new value while the
// entity is managed (without first nulling and manually flushing).
if ( child == null || ( loadedValue != null && child != loadedValue ) ) {
EntityEntry valueEntry = persistenceContext.getEntry( loadedValue );
if ( valueEntry == null && loadedValue instanceof HibernateProxy ) {
// un-proxy and re-associate for cascade operation
// useful for @OneToOne defined as FetchType.LAZY
loadedValue = persistenceContext.unproxyAndReassociate( loadedValue );
valueEntry = persistenceContext.getEntry( loadedValue );
// HHH-11965
// Should the unwrapped proxy value be equal via reference to the entity's property value
// provided by the 'child' variable, we should not trigger the orphan removal of the
// associated one-to-one.
if ( child == loadedValue ) {
// do nothing
return;
}
}
if ( valueEntry != null ) {
final String entityName = valueEntry.getPersister().getEntityName();
if ( LOG.isTraceEnabled() ) {
final Object id = valueEntry.getPersister().getIdentifier( loadedValue, eventSource );
final String description = MessageHelper.infoString( entityName, id );
LOG.tracev( "Deleting orphaned entity instance: {0}", description );
}
if ( type.isAssociationType() && ( (AssociationType) type ).getForeignKeyDirection().equals(
ForeignKeyDirection.TO_PARENT
) ) {
// If FK direction is to-parent, we must remove the orphan *before* the queued update(s)
// occur. Otherwise, replacing the association on a managed entity, without manually
// nulling and flushing, causes FK constraint violations.
eventSource.removeOrphanBeforeUpdates( entityName, loadedValue );
}
else {
// Else, we must delete after the updates.
eventSource.delete( entityName, loadedValue, isCascadeDeleteEnabled, new HashSet() );
}
}
}
}
}
}
}
/**
* Check if the association is a one to one in the logical model (either a shared-pk
* or unique fk).
*
* @param type The type representing the attribute metadata
*
* @return True if the attribute represents a logical one to one association
*/
private static boolean isLogicalOneToOne(Type type) {
return type.isEntityType() && ( (EntityType) type ).isLogicalOneToOne();
}
private static boolean cascadeAssociationNow(final CascadePoint cascadePoint, AssociationType associationType) {
return associationType.getForeignKeyDirection().cascadeNow( cascadePoint );
}
private static void cascadeComponent(
final CascadingAction action,
final CascadePoint cascadePoint,
final EventSource eventSource,
final List<String> componentPath,
final Object parent,
final Object child,
final CompositeType componentType,
final Object anything) {
Object[] children = null;
final Type[] types = componentType.getSubtypes();
final String[] propertyNames = componentType.getPropertyNames();
for ( int i = 0; i < types.length; i++ ) {
final CascadeStyle componentPropertyStyle = componentType.getCascadeStyle( i );
final String subPropertyName = propertyNames[i];
if ( componentPropertyStyle.doCascade( action ) || componentPropertyStyle.hasOrphanDelete() && action.deleteOrphans() ) {
if (children == null) {
// Get children on demand.
children = componentType.getPropertyValues( child, eventSource );
}
cascadeProperty(
action,
cascadePoint,
eventSource,
componentPath,
parent,
children[i],
types[i],
componentPropertyStyle,
subPropertyName,
anything,
false
);
}
}
}
private static void cascadeAssociation(
final CascadingAction action,
final CascadePoint cascadePoint,
final EventSource eventSource,
final List<String> componentPath,
final Object parent,
final Object child,
final Type type,
final CascadeStyle style,
final Object anything,
final boolean isCascadeDeleteEnabled) {
if ( type.isEntityType() || type.isAnyType() ) {
cascadeToOne( action, eventSource, parent, child, type, style, anything, isCascadeDeleteEnabled );
}
else if ( type.isCollectionType() ) {
cascadeCollection(
action,
cascadePoint,
eventSource,
componentPath,
parent,
child,
style,
anything,
(CollectionType) type
);
}
}
/**
* Cascade an action to a collection
*/
private static void cascadeCollection(
final CascadingAction action,
final CascadePoint cascadePoint,
final EventSource eventSource,
final List<String> componentPath,
final Object parent,
final Object child,
final CascadeStyle style,
final Object anything,
final CollectionType type) {
final CollectionPersister persister = eventSource.getFactory().getCollectionPersister( type.getRole() );
final Type elemType = persister.getElementType();
CascadePoint elementsCascadePoint = cascadePoint;
if ( cascadePoint == CascadePoint.AFTER_INSERT_BEFORE_DELETE ) {
elementsCascadePoint = CascadePoint.AFTER_INSERT_BEFORE_DELETE_VIA_COLLECTION;
}
//cascade to current collection elements
if ( elemType.isEntityType() || elemType.isAnyType() || elemType.isComponentType() ) {
cascadeCollectionElements(
action,
elementsCascadePoint,
eventSource,
componentPath,
parent,
child,
type,
style,
elemType,
anything,
persister.isCascadeDeleteEnabled()
);
}
}
/**
* Cascade an action to a to-one association or any type
*/
private static void cascadeToOne(
final CascadingAction action,
final EventSource eventSource,
final Object parent,
final Object child,
final Type type,
final CascadeStyle style,
final Object anything,
final boolean isCascadeDeleteEnabled) {
final String entityName = type.isEntityType()
? ( (EntityType) type ).getAssociatedEntityName()
: null;
if ( style.reallyDoCascade( action ) ) {
//not really necessary, but good for consistency...
final PersistenceContext persistenceContext = eventSource.getPersistenceContextInternal();
persistenceContext.addChildParent( child, parent );
try {
action.cascade( eventSource, child, entityName, anything, isCascadeDeleteEnabled );
}
finally {
persistenceContext.removeChildParent( child );
}
}
}
/**
* Cascade to the collection elements
*/
private static void cascadeCollectionElements(
final CascadingAction action,
final CascadePoint cascadePoint,
final EventSource eventSource,
final List<String> componentPath,
final Object parent,
final Object child,
final CollectionType collectionType,
final CascadeStyle style,
final Type elemType,
final Object anything,
final boolean isCascadeDeleteEnabled) throws HibernateException {
final boolean reallyDoCascade = style.reallyDoCascade( action ) && child != CollectionType.UNFETCHED_COLLECTION;
if ( reallyDoCascade ) {
final boolean traceEnabled = LOG.isTraceEnabled();
if ( traceEnabled ) {
LOG.tracev( "Cascade {0} for collection: {1}", action, collectionType.getRole() );
}
final Iterator itr = action.getCascadableChildrenIterator( eventSource, collectionType, child );
while ( itr.hasNext() ) {
cascadeProperty(
action,
cascadePoint,
eventSource,
componentPath,
parent,
itr.next(),
elemType,
style,
null,
anything,
isCascadeDeleteEnabled
);
}
if ( traceEnabled ) {
LOG.tracev( "Done cascade {0} for collection: {1}", action, collectionType.getRole() );
}
}
final boolean deleteOrphans = style.hasOrphanDelete()
&& action.deleteOrphans()
&& elemType.isEntityType()
&& child instanceof PersistentCollection
// a newly instantiated collection can't have orphans
&& ! ( (PersistentCollection) child ).isNewlyInstantiated();
if ( deleteOrphans ) {
final boolean traceEnabled = LOG.isTraceEnabled();
if ( traceEnabled ) {
LOG.tracev( "Deleting orphans for collection: {0}", collectionType.getRole() );
}
// we can do the cast since orphan-delete does not apply to:
// 1. newly instantiated collections
// 2. arrays (we can't track orphans for detached arrays)
final String entityName = collectionType.getAssociatedEntityName( eventSource.getFactory() );
deleteOrphans( eventSource, entityName, (PersistentCollection) child );
if ( traceEnabled ) {
LOG.tracev( "Done deleting orphans for collection: {0}", collectionType.getRole() );
}
}
}
/**
* Delete any entities that were removed from the collection
*/
private static void deleteOrphans(EventSource eventSource, String entityName, PersistentCollection pc) throws HibernateException {
//TODO: suck this logic into the collection!
final Collection orphans;
if ( pc.wasInitialized() ) {
final CollectionEntry ce = eventSource.getPersistenceContextInternal().getCollectionEntry( pc );
orphans = ce==null
? java.util.Collections.EMPTY_LIST
: ce.getOrphans( entityName, pc );
}
else {
orphans = pc.getQueuedOrphans( entityName );
}
for ( Object orphan : orphans ) {
if ( orphan != null ) {
LOG.tracev( "Deleting orphaned entity instance: {0}", entityName );
eventSource.delete( entityName, orphan, false, new HashSet() );
}
}
}
}