org.hibernate.type.ForeignKeyDirection Java Examples

The following examples show how to use org.hibernate.type.ForeignKeyDirection. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JoinWalker.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Used to detect circularities in the joined graph, note that
 * this method is side-effecty
 */
protected boolean isDuplicateAssociation(
		final String lhsTable,
		final String[] lhsColumnNames,
		final AssociationType type) {
	final String foreignKeyTable;
	final String[] foreignKeyColumns;
	if ( type.getForeignKeyDirection() == ForeignKeyDirection.FROM_PARENT ) {
		foreignKeyTable = lhsTable;
		foreignKeyColumns = lhsColumnNames;
	}
	else {
		foreignKeyTable = type.getAssociatedJoinable( getFactory() ).getTableName();
		foreignKeyColumns = JoinHelper.getRHSColumnNames( type, getFactory() );
	}
	return isDuplicateAssociation( foreignKeyTable, foreignKeyColumns );
}
 
Example #2
Source File: JoinWalker.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Used to detect circularities in the joined graph, note that 
 * this method is side-effecty
 */
protected boolean isDuplicateAssociation(
	final String lhsTable,
	final String[] lhsColumnNames,
	final AssociationType type
) {
	final String foreignKeyTable;
	final String[] foreignKeyColumns;
	if ( type.getForeignKeyDirection()==ForeignKeyDirection.FOREIGN_KEY_FROM_PARENT ) {
		foreignKeyTable = lhsTable;
		foreignKeyColumns = lhsColumnNames;
	}
	else {
		foreignKeyTable = type.getAssociatedJoinable( getFactory() ).getTableName();
		foreignKeyColumns = JoinHelper.getRHSColumnNames( type, getFactory() );
	}
	return isDuplicateAssociation(foreignKeyTable, foreignKeyColumns);
}
 
Example #3
Source File: DefaultReactiveMergeEventListener.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected void copyValues(
		final EntityPersister persister,
		final Object entity,
		final Object target,
		final SessionImplementor source,
		final MergeContext copyCache,
		final ForeignKeyDirection foreignKeyDirection) {

	final Object[] copiedValues;

	if ( foreignKeyDirection == ForeignKeyDirection.TO_PARENT ) {
		// this is the second pass through on a merge op, so here we limit the
		// replacement to associations types (value types were already replaced
		// during the first pass)
		copiedValues = TypeHelper.replaceAssociations(
				persister.getPropertyValues( entity ),
				persister.getPropertyValues( target ),
				persister.getPropertyTypes(),
				source,
				target,
				copyCache,
				foreignKeyDirection
		);
	}
	else {
		copiedValues = TypeHelper.replace(
				persister.getPropertyValues( entity ),
				persister.getPropertyValues( target ),
				persister.getPropertyTypes(),
				source,
				target,
				copyCache,
				foreignKeyDirection
		);
	}

	persister.setPropertyValues( target, copiedValues );
}
 
Example #4
Source File: DefaultMergeEventListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected void copyValues(
		final EntityPersister persister,
		final Object entity, 
		final Object target, 
		final SessionImplementor source,
		final Map copyCache,
		final ForeignKeyDirection foreignKeyDirection) {

	final Object[] copiedValues;

	if ( foreignKeyDirection == ForeignKeyDirection.FOREIGN_KEY_TO_PARENT ) {
		// this is the second pass through on a merge op, so here we limit the
		// replacement to associations types (value types were already replaced
		// during the first pass)
		copiedValues = TypeFactory.replaceAssociations(
				persister.getPropertyValues( entity, source.getEntityMode() ),
				persister.getPropertyValues( target, source.getEntityMode() ),
				persister.getPropertyTypes(),
				source,
				target,
				copyCache,
				foreignKeyDirection
		);
	}
	else {
		copiedValues = TypeFactory.replace(
				persister.getPropertyValues( entity, source.getEntityMode() ),
				persister.getPropertyValues( target, source.getEntityMode() ),
				persister.getPropertyTypes(),
				source,
				target,
				copyCache,
				foreignKeyDirection
		);
	}

	persister.setPropertyValues( target, copiedValues, source.getEntityMode() );
}
 
Example #5
Source File: EntityBasedAssociationAttribute.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public AssociationKey getAssociationKey() {
	final AssociationType type = getType();

	if ( type.isAnyType() ) {
		return new AssociationKey(
				JoinHelper.getLHSTableName( type, attributeNumber(), (OuterJoinLoadable) getSource() ),
				JoinHelper.getLHSColumnNames(
						type,
						attributeNumber(),
						0,
						(OuterJoinLoadable) getSource(),
						sessionFactory()
				)
		);
	}

	final Joinable joinable = type.getAssociatedJoinable( sessionFactory() );

	if ( type.getForeignKeyDirection() == ForeignKeyDirection.FROM_PARENT ) {
		final String lhsTableName;
		final String[] lhsColumnNames;

		if ( joinable.isCollection() ) {
			final QueryableCollection collectionPersister = (QueryableCollection) joinable;
			lhsTableName = collectionPersister.getTableName();
			lhsColumnNames = collectionPersister.getElementColumnNames();
		}
		else {
			final OuterJoinLoadable entityPersister = (OuterJoinLoadable) source();
			lhsTableName = getLHSTableName( type, attributeNumber(), entityPersister );
			lhsColumnNames = getLHSColumnNames( type, attributeNumber(), entityPersister, sessionFactory() );
		}
		return new AssociationKey( lhsTableName, lhsColumnNames );
	}
	else {
		return new AssociationKey( joinable.getTableName(), getRHSColumnNames( type, sessionFactory() ) );
	}
}
 
Example #6
Source File: DefaultMergeEventListener.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected void entityIsTransient(MergeEvent event, Map copyCache) {

		LOG.trace( "Merging transient instance" );

		final Object entity = event.getEntity();
		final EventSource source = event.getSession();

		final String entityName = event.getEntityName();
		final EntityPersister persister = source.getEntityPersister( entityName, entity );

		final Serializable id = persister.hasIdentifierProperty() ?
				persister.getIdentifier( entity, source ) :
				null;
		if ( copyCache.containsKey( entity ) ) {
			persister.setIdentifier( copyCache.get( entity ), id, source );
		}
		else {
			( (MergeContext) copyCache ).put( entity, source.instantiate( persister, id ), true ); //before cascade!
		}
		final Object copy = copyCache.get( entity );

		// cascade first, so that all unsaved objects get their
		// copy created before we actually copy
		//cascadeOnMerge(event, persister, entity, copyCache, Cascades.CASCADE_BEFORE_MERGE);
		super.cascadeBeforeSave( source, persister, entity, copyCache );
		copyValues( persister, entity, copy, source, copyCache, ForeignKeyDirection.FROM_PARENT );

		saveTransientEntity( copy, entityName, event.getRequestedId(), source, copyCache );

		// cascade first, so that all unsaved objects get their
		// copy created before we actually copy
		super.cascadeAfterSave( source, persister, entity, copyCache );
		copyValues( persister, entity, copy, source, copyCache, ForeignKeyDirection.TO_PARENT );

		event.setResult( copy );
	}
 
Example #7
Source File: DefaultMergeEventListener.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected void copyValues(
		final EntityPersister persister,
		final Object entity,
		final Object target,
		final SessionImplementor source,
		final Map copyCache,
		final ForeignKeyDirection foreignKeyDirection) {

	final Object[] copiedValues;

	if ( foreignKeyDirection == ForeignKeyDirection.TO_PARENT ) {
		// this is the second pass through on a merge op, so here we limit the
		// replacement to associations types (value types were already replaced
		// during the first pass)
		copiedValues = TypeHelper.replaceAssociations(
				persister.getPropertyValues( entity ),
				persister.getPropertyValues( target ),
				persister.getPropertyTypes(),
				source,
				target,
				copyCache,
				foreignKeyDirection
		);
	}
	else {
		copiedValues = TypeHelper.replace(
				persister.getPropertyValues( entity ),
				persister.getPropertyValues( target ),
				persister.getPropertyTypes(),
				source,
				target,
				copyCache,
				foreignKeyDirection
		);
	}

	persister.setPropertyValues( target, copiedValues );
}
 
Example #8
Source File: ColumnMapperSingleColumnTypeAdapter.java    From jadira with Apache License 2.0 4 votes vote down vote up
@Override
public Object replace(Object original, Object target,
		SharedSessionContractImplementor session, Object owner, @SuppressWarnings("rawtypes") Map copyCache,
		ForeignKeyDirection foreignKeyDirection) throws HibernateException {
	return columnMapper.getHibernateType().replace(original, target, session, owner, copyCache, foreignKeyDirection);
}
 
Example #9
Source File: DefaultReactiveMergeEventListener.java    From hibernate-reactive with GNU Lesser General Public License v2.1 4 votes vote down vote up
protected CompletionStage<Void> entityIsTransient(MergeEvent event, MergeContext copyCache) {

		LOG.trace( "Merging transient instance" );

		final Object entity = event.getEntity();
		final EventSource session = event.getSession();

		final String entityName = event.getEntityName();
		final EntityPersister persister = session.getEntityPersister( entityName, entity );

		final Serializable id = persister.hasIdentifierProperty()
				? persister.getIdentifier( entity, session )
				: null;

		final Object copy;
		final Object existingCopy = copyCache.get( entity );
		if ( existingCopy != null ) {
			persister.setIdentifier( copyCache.get( entity ), id, session );
			copy = existingCopy;
		}
		else {
			copy = session.instantiate( persister, id );

			//before cascade!
			copyCache.put( entity, copy, true );
		}

		// cascade first, so that all unsaved objects get their
		// copy created before we actually copy
		//cascadeOnMerge(event, persister, entity, copyCache, Cascades.CASCADE_BEFORE_MERGE);
		return super.cascadeBeforeSave( session, persister, entity, copyCache )
				.thenAccept( v -> copyValues( persister, entity, copy, session, copyCache, ForeignKeyDirection.FROM_PARENT ) )
				.thenCompose( v -> saveTransientEntity( copy, entityName, event.getRequestedId(), session, copyCache ) )
				.thenCompose( v -> super.cascadeAfterSave( session, persister, entity, copyCache ) )
				.thenAccept( v -> {
					copyValues(persister, entity, copy, session, copyCache, ForeignKeyDirection.TO_PARENT);

					event.setResult(copy);

					if (copy instanceof PersistentAttributeInterceptable) {
						final PersistentAttributeInterceptable interceptable = (PersistentAttributeInterceptable) copy;
						final PersistentAttributeInterceptor interceptor = interceptable.$$_hibernate_getInterceptor();
						if (interceptor == null) {
							persister.getBytecodeEnhancementMetadata().injectInterceptor(copy, id, session);
						}
					}
				});
	}
 
Example #10
Source File: DefaultMergeEventListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
protected void entityIsTransient(MergeEvent event, Map copyCache) {
	
	log.trace("merging transient instance");
	
	final Object entity = event.getEntity();
	final EventSource source = event.getSession();

	final EntityPersister persister = source.getEntityPersister( event.getEntityName(), entity );
	final String entityName = persister.getEntityName();
	
	final Serializable id = persister.hasIdentifierProperty() ?
			persister.getIdentifier( entity, source.getEntityMode() ) :
	        null;
	
	final Object copy = persister.instantiate( id, source.getEntityMode() );  //TODO: should this be Session.instantiate(Persister, ...)?
	copyCache.put(entity, copy); //before cascade!
	
	// cascade first, so that all unsaved objects get their
	// copy created before we actually copy
	//cascadeOnMerge(event, persister, entity, copyCache, Cascades.CASCADE_BEFORE_MERGE);
	super.cascadeBeforeSave(source, persister, entity, copyCache);
	copyValues(persister, entity, copy, source, copyCache, ForeignKeyDirection.FOREIGN_KEY_FROM_PARENT);
	
	//this bit is only *really* absolutely necessary for handling 
	//requestedId, but is also good if we merge multiple object 
	//graphs, since it helps ensure uniqueness
	final Serializable requestedId = event.getRequestedId();
	if (requestedId==null) {
		saveWithGeneratedId( copy, entityName, copyCache, source, false );
	}
	else {
		saveWithRequestedId( copy, requestedId, entityName, copyCache, source );
	}
	
	// cascade first, so that all unsaved objects get their 
	// copy created before we actually copy
	super.cascadeAfterSave(source, persister, entity, copyCache);
	copyValues(persister, entity, copy, source, copyCache, ForeignKeyDirection.FOREIGN_KEY_TO_PARENT);
	
	event.setResult(copy);

}
 
Example #11
Source File: ImmutableType.java    From hibernate-types with Apache License 2.0 4 votes vote down vote up
@Override
public Object replace(Object original, Object target, SessionImplementor session, Object owner, Map copyCache, ForeignKeyDirection foreignKeyDirection) throws HibernateException {
    return replace(original, target, owner);
}
 
Example #12
Source File: ImmutableType.java    From hibernate-types with Apache License 2.0 4 votes vote down vote up
@Override
public Object replace(Object original, Object target, SessionImplementor session, Object owner, Map copyCache, ForeignKeyDirection foreignKeyDirection) throws HibernateException {
    return replace(original, target, owner);
}
 
Example #13
Source File: ImmutableType.java    From hibernate-types with Apache License 2.0 4 votes vote down vote up
@Override
public Object replace(Object original, Object target, SessionImplementor session, Object owner, Map copyCache, ForeignKeyDirection foreignKeyDirection) throws HibernateException {
    return replace(original, target, owner);
}
 
Example #14
Source File: ImmutableType.java    From hibernate-types with Apache License 2.0 4 votes vote down vote up
@Override
public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner, Map copyCache, ForeignKeyDirection foreignKeyDirection) throws HibernateException {
    return replace(original, target, owner);
}
 
Example #15
Source File: SingularAttributeSourceManyToOneImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public ForeignKeyDirection getForeignKeyDirection() {
	return ForeignKeyDirection.TO_PARENT;
}
 
Example #16
Source File: ModelBinder.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public void bindOneToOne(
		final MappingDocument sourceDocument,
		final SingularAttributeSourceOneToOne oneToOneSource,
		final OneToOne oneToOneBinding) {
	oneToOneBinding.setPropertyName( oneToOneSource.getName() );

	relationalObjectBinder.bindFormulas(
			sourceDocument,
			oneToOneSource.getFormulaSources(),
			oneToOneBinding
	);


	if ( oneToOneSource.isConstrained() ) {
		if ( oneToOneSource.getCascadeStyleName() != null
				&& oneToOneSource.getCascadeStyleName().contains( "delete-orphan" ) ) {
			throw new MappingException(
					String.format(
							Locale.ENGLISH,
							"one-to-one attribute [%s] cannot specify orphan delete cascading as it is constrained",
							oneToOneSource.getAttributeRole().getFullPath()
					),
					sourceDocument.getOrigin()
			);
		}
		oneToOneBinding.setConstrained( true );
		oneToOneBinding.setForeignKeyType( ForeignKeyDirection.FROM_PARENT );
	}
	else {
		oneToOneBinding.setForeignKeyType( ForeignKeyDirection.TO_PARENT );
	}

	oneToOneBinding.setLazy( oneToOneSource.getFetchCharacteristics().getFetchTiming() == FetchTiming.DELAYED );
	oneToOneBinding.setFetchMode(
			oneToOneSource.getFetchCharacteristics().getFetchStyle() == FetchStyle.SELECT
					? FetchMode.SELECT
					: FetchMode.JOIN
	);
	oneToOneBinding.setUnwrapProxy( oneToOneSource.getFetchCharacteristics().isUnwrapProxies() );


	if ( StringHelper.isNotEmpty( oneToOneSource.getReferencedEntityAttributeName() ) ) {
		oneToOneBinding.setReferencedPropertyName( oneToOneSource.getReferencedEntityAttributeName() );
		oneToOneBinding.setReferenceToPrimaryKey( false );
	}
	else {
		oneToOneBinding.setReferenceToPrimaryKey( true );
	}

	// todo : probably need some reflection here if null
	oneToOneBinding.setReferencedEntityName( oneToOneSource.getReferencedEntityName() );

	if ( oneToOneSource.isEmbedXml() == Boolean.TRUE ) {
		DeprecationLogger.DEPRECATION_LOGGER.logDeprecationOfEmbedXmlSupport();
	}

	if ( StringHelper.isNotEmpty( oneToOneSource.getExplicitForeignKeyName() ) ) {
		oneToOneBinding.setForeignKeyName( oneToOneSource.getExplicitForeignKeyName() );
	}

	oneToOneBinding.setCascadeDeleteEnabled( oneToOneSource.isCascadeDeleteEnabled() );
}
 
Example #17
Source File: SingularAttributeSourceOneToOneImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public ForeignKeyDirection getForeignKeyDirection() {
	return oneToOneElement.isConstrained()  ? ForeignKeyDirection.FROM_PARENT : ForeignKeyDirection.TO_PARENT;
}
 
Example #18
Source File: CompositeIdentifierSingularAttributeSourceManyToOneImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public ForeignKeyDirection getForeignKeyDirection() {
	return ForeignKeyDirection.TO_PARENT;
}
 
Example #19
Source File: Cascade.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private static void cascadeLogicalOneToOneOrphanRemoval(
			final CascadingAction action,
			final EventSource eventSource,
			final int componentPathStackDepth,
			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 EntityEntry entry = eventSource.getPersistenceContext().getEntry( parent );
				if ( entry != null && entry.getStatus() != Status.SAVING ) {
					Object loadedValue;
					if ( componentPathStackDepth == 0 ) {
						// association defined on entity
						loadedValue = entry.getLoadedValue( propertyName );
					}
					else {
						// association defined on component
						// 		todo : this is currently unsupported because of the fact that
						//		we do not know the loaded state of this value properly
						//		and doing so would be very difficult given how components and
						//		entities are loaded (and how 'loaded state' is put into the
						//		EntityEntry).  Solutions here are to either:
						//			1) properly account for components as a 2-phase load construct
						//			2) just assume the association was just now orphaned and
						// 				issue the orphan delete.  This would require a special
						//				set of SQL statements though since we do not know the
						//				orphaned value, something a delete with a subquery to
						// 				match the owner.
//							final EntityType entityType = (EntityType) type;
//							final String getPropertyPath = composePropertyPath( entityType.getPropertyName() );
						loadedValue = null;
					}

					// 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 = eventSource
								.getPersistenceContext().getEntry(
										loadedValue );

						if ( valueEntry == null && loadedValue instanceof HibernateProxy ) {
							// un-proxy and re-associate for cascade operation
							// useful for @OneToOne defined as FetchType.LAZY
							loadedValue = eventSource.getPersistenceContext().unproxyAndReassociate( loadedValue );
							valueEntry = eventSource.getPersistenceContext().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 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.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() );
							}
						}
					}
				}
			}
		}
	}
 
Example #20
Source File: HbmBinder.java    From cacheonix-core with GNU Lesser General Public License v2.1 3 votes vote down vote up
public static void bindOneToOne(Element node, OneToOne oneToOne, String path, boolean isNullable,
		Mappings mappings) throws MappingException {

	bindColumns( node, oneToOne, isNullable, false, null, mappings );

	Attribute constrNode = node.attribute( "constrained" );
	boolean constrained = constrNode != null && constrNode.getValue().equals( "true" );
	oneToOne.setConstrained( constrained );

	oneToOne.setForeignKeyType( constrained ?
			ForeignKeyDirection.FOREIGN_KEY_FROM_PARENT :
			ForeignKeyDirection.FOREIGN_KEY_TO_PARENT );

	initOuterJoinFetchSetting( node, oneToOne );
	initLaziness( node, oneToOne, mappings, true );

	oneToOne.setEmbedded( "true".equals( node.attributeValue( "embed-xml" ) ) );

	Attribute fkNode = node.attribute( "foreign-key" );
	if ( fkNode != null ) oneToOne.setForeignKeyName( fkNode.getValue() );

	Attribute ukName = node.attribute( "property-ref" );
	if ( ukName != null ) oneToOne.setReferencedPropertyName( ukName.getValue() );

	oneToOne.setPropertyName( node.attributeValue( "name" ) );

	oneToOne.setReferencedEntityName( getEntityName( node, mappings ) );

	validateCascade( node, path );
}
 
Example #21
Source File: OneToOne.java    From cacheonix-core with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * Returns the foreignKeyType.
 * @return AssociationType.ForeignKeyType
 */
public ForeignKeyDirection getForeignKeyType() {
	return foreignKeyType;
}
 
Example #22
Source File: OneToOne.java    From cacheonix-core with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * Sets the foreignKeyType.
 * @param foreignKeyType The foreignKeyType to set
 */
public void setForeignKeyType(ForeignKeyDirection foreignKeyType) {
	this.foreignKeyType = foreignKeyType;
}
 
Example #23
Source File: OneToOne.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Sets the foreignKeyType.
 * @param foreignKeyType The foreignKeyType to set
 */
public void setForeignKeyType(ForeignKeyDirection foreignKeyType) {
	this.foreignKeyType = foreignKeyType;
}
 
Example #24
Source File: OneToOne.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Returns the foreignKeyType.
 * @return AssociationType.ForeignKeyType
 */
public ForeignKeyDirection getForeignKeyType() {
	return foreignKeyType;
}
 
Example #25
Source File: SingularAttributeSourceToOne.java    From lams with GNU General Public License v2.0 votes vote down vote up
public ForeignKeyDirection getForeignKeyDirection();