package org.hibernate.engine.internal;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import org.hibernate.HibernateException;
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.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.type.AssociationType;
import org.hibernate.type.CollectionType;
import org.hibernate.type.CompositeType;
import org.hibernate.type.EntityType;
import org.hibernate.type.ForeignKeyDirection;
import org.hibernate.type.Type;
public final class Cascade {
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( Cascade.class );
private int componentPathStackDepth = 0;
private final CascadingAction action;
private final EventSource eventSource;
private CascadePoint cascadePoint;
public Cascade(final CascadingAction action, final CascadePoint cascadePoint, final EventSource eventSource) {
this.cascadePoint = cascadePoint;
this.eventSource = eventSource;
this.action = action;
}
public void cascade(final EntityPersister persister, final Object parent) {
cascade( persister, parent, null );
}
public void cascade(final EntityPersister persister, final Object parent, final Object anything) {
if ( persister.hasCascades() || action.requiresNoCascadeChecking() ) {
final boolean traceEnabled = LOG.isTraceEnabled();
if ( traceEnabled ) {
LOG.tracev( "Processing cascade {0} for: {1}", action, persister.getEntityName() );
}
final Type[] types = persister.getPropertyTypes();
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 = persister.getPropertyNames()[i];
if ( hasUninitializedLazyProperties && persister.getPropertyLaziness()[i] && ! action.performOnLazyProperty() ) {
continue;
}
if ( style.doCascade( action ) ) {
cascadeProperty(
parent,
persister.getPropertyValue( parent, i ),
types[i],
style,
propertyName,
anything,
false
);
}
else if ( action.requiresNoCascadeChecking() ) {
action.noCascade(
eventSource,
persister.getPropertyValue( parent, i ),
parent,
persister,
i
);
}
}
if ( traceEnabled ) {
LOG.tracev( "Done processing cascade {0} for: {1}", action, persister.getEntityName() );
}
}
}
private void cascadeProperty(
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( associationType ) ) {
cascadeAssociation(
parent,
child,
type,
style,
anything,
isCascadeDeleteEnabled
);
}
}
else if ( type.isComponentType() ) {
cascadeComponent( parent, child, (CompositeType) type, propertyName, anything );
}
}
if ( isLogicalOneToOne( type ) ) {
if ( style.hasOrphanDelete() && action.deleteOrphans() ) {
final EntityEntry entry = eventSource.getPersistenceContext().getEntry( parent );
if ( entry != null && entry.getStatus() != Status.SAVING ) {
final Object loadedValue;
if ( componentPathStackDepth == 0 ) {
loadedValue = entry.getLoadedValue( propertyName );
}
else {
loadedValue = null;
}
if ( child == null || ( loadedValue != null && child != loadedValue ) ) {
final EntityEntry valueEntry = eventSource
.getPersistenceContext().getEntry(
loadedValue );
if ( valueEntry != null ) {
final String entityName = valueEntry.getPersister().getEntityName();
if ( LOG.isTraceEnabled() ) {
final Serializable 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.FOREIGN_KEY_TO_PARENT )) {
eventSource.removeOrphanBeforeUpdates( entityName, loadedValue );
}
else {
eventSource.delete( entityName, loadedValue, isCascadeDeleteEnabled, new HashSet() );
}
}
}
}
}
}
}
private boolean isLogicalOneToOne(Type type) {
return type.isEntityType() && ( (EntityType) type ).isLogicalOneToOne();
}
private boolean cascadeAssociationNow(AssociationType associationType) {
return associationType.getForeignKeyDirection().cascadeNow( cascadePoint );
}
private void cascadeComponent(
final Object parent,
final Object child,
final CompositeType componentType,
final String componentPropertyName,
final Object anything) {
componentPathStackDepth++;
final Object[] children = componentType.getPropertyValues( child, eventSource );
final Type[] types = componentType.getSubtypes();
for ( int i=0; i<types.length; i++ ) {
final CascadeStyle componentPropertyStyle = componentType.getCascadeStyle( i );
final String subPropertyName = componentType.getPropertyNames()[i];
if ( componentPropertyStyle.doCascade( action ) ) {
cascadeProperty(
parent,
children[i],
types[i],
componentPropertyStyle,
subPropertyName,
anything,
false
);
}
}
componentPathStackDepth--;
}
private void cascadeAssociation(
final Object parent,
final Object child,
final Type type,
final CascadeStyle style,
final Object anything,
final boolean isCascadeDeleteEnabled) {
if ( type.isEntityType() || type.isAnyType() ) {
cascadeToOne( parent, child, type, style, anything, isCascadeDeleteEnabled );
}
else if ( type.isCollectionType() ) {
cascadeCollection( parent, child, style, anything, (CollectionType) type );
}
}
private void cascadeCollection(
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();
final CascadePoint originalCascadePoint = cascadePoint;
if ( cascadePoint == CascadePoint.AFTER_INSERT_BEFORE_DELETE) {
cascadePoint = CascadePoint.AFTER_INSERT_BEFORE_DELETE_VIA_COLLECTION;
}
if ( elemType.isEntityType() || elemType.isAnyType() || elemType.isComponentType() ) {
cascadeCollectionElements(
parent,
child,
type,
style,
elemType,
anything,
persister.isCascadeDeleteEnabled()
);
}
cascadePoint = originalCascadePoint;
}
private void cascadeToOne(
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 ) ) {
eventSource.getPersistenceContext().addChildParent( child, parent );
try {
action.cascade( eventSource, child, entityName, anything, isCascadeDeleteEnabled );
}
finally {
eventSource.getPersistenceContext().removeChildParent( child );
}
}
}
private void cascadeCollectionElements(
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(
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;
if ( deleteOrphans ) {
final boolean traceEnabled = LOG.isTraceEnabled();
if ( traceEnabled ) {
LOG.tracev( "Deleting orphans for collection: {0}", collectionType.getRole() );
}
final String entityName = collectionType.getAssociatedEntityName( eventSource.getFactory() );
deleteOrphans( entityName, (PersistentCollection) child );
if ( traceEnabled ) {
LOG.tracev( "Done deleting orphans for collection: {0}", collectionType.getRole() );
}
}
}
private void deleteOrphans(String entityName, PersistentCollection pc) throws HibernateException {
final Collection orphans;
if ( pc.wasInitialized() ) {
final CollectionEntry ce = eventSource.getPersistenceContext().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() );
}
}
}
}