Java Code Examples for org.hibernate.type.Type#isAssociationType()

The following examples show how to use org.hibernate.type.Type#isAssociationType() . 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: CriteriaQueryTranslator.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private String getPathEntityName(String path) {
	Queryable persister = ( Queryable ) sessionFactory.getEntityPersister( rootEntityName );
	StringTokenizer tokens = new StringTokenizer( path, "." );
	String componentPath = "";
	while ( tokens.hasMoreTokens() ) {
		componentPath += tokens.nextToken();
		Type type = persister.toType( componentPath );
		if ( type.isAssociationType() ) {
			AssociationType atype = ( AssociationType ) type;
			persister = ( Queryable ) sessionFactory.getEntityPersister(
					atype.getAssociatedEntityName( sessionFactory )
			);
			componentPath = "";
		}
		else if ( type.isComponentType() ) {
			componentPath += '.';
		}
		else {
			throw new QueryException( "not an association: " + componentPath );
		}
	}
	return persister.getEntityName();
}
 
Example 2
Source File: AbstractEntityPersister.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Warning:
 * When there are duplicated property names in the subclasses
 * of the class, this method may return the wrong table
 * number for the duplicated subclass property (note that
 * SingleTableEntityPersister defines an overloaded form
 * which takes the entity name.
 */
public int getSubclassPropertyTableNumber(String propertyPath) {
	String rootPropertyName = StringHelper.root(propertyPath);
	Type type = propertyMapping.toType(rootPropertyName);
	if ( type.isAssociationType() ) {
		AssociationType assocType = ( AssociationType ) type;
		if ( assocType.useLHSPrimaryKey() ) {
			// performance op to avoid the array search
			return 0;
		}
		else if ( type.isCollectionType() ) {
			// properly handle property-ref-based associations
			rootPropertyName = assocType.getLHSPropertyName();
		}
	}
	//Enable for HHH-440, which we don't like:
	/*if ( type.isComponentType() && !propertyName.equals(rootPropertyName) ) {
		String unrooted = StringHelper.unroot(propertyName);
		int idx = ArrayHelper.indexOf( getSubclassColumnClosure(), unrooted );
		if ( idx != -1 ) {
			return getSubclassColumnTableNumberClosure()[idx];
		}
	}*/
	int index = ArrayHelper.indexOf( getSubclassPropertyNameClosure(), rootPropertyName); //TODO: optimize this better!
	return index==-1 ? 0 : getSubclassPropertyTableNumber(index);
}
 
Example 3
Source File: Cascade.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Cascade an action to the child or children
 */
private void cascadeProperty(
		final Object child,
		final Type type,
		final CascadeStyle style,
		final Object anything,
		final boolean isCascadeDeleteEnabled) throws HibernateException {

	if (child!=null) {
		if ( type.isAssociationType() ) {
			AssociationType associationType = (AssociationType) type;
			if ( cascadeAssociationNow( associationType ) ) {
				cascadeAssociation(
						child,
						type,
						style,
						anything,
						isCascadeDeleteEnabled
					);
			}
		}
		else if ( type.isComponentType() ) {
			cascadeComponent( child, (AbstractComponentType) type, anything );
		}
	}
}
 
Example 4
Source File: AbstractLoadPlanBuildingAssociationVisitationStrategy.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean startingAttribute(AttributeDefinition attributeDefinition) {
	log.tracef(
			"%s Starting attribute %s",
			StringHelper.repeat( ">>", fetchSourceStack.size() ),
			attributeDefinition
	);

	final Type attributeType = attributeDefinition.getType();

	final boolean isComponentType = attributeType.isComponentType();
	final boolean isAssociationType = attributeType.isAssociationType();
	final boolean isBasicType = ! ( isComponentType || isAssociationType );
	currentPropertyPath = currentPropertyPath.append( attributeDefinition.getName() );
	if ( isBasicType ) {
		return true;
	}
	else if ( isAssociationType ) {
		// also handles any type attributes...
		return handleAssociationAttribute( (AssociationAttributeDefinition) attributeDefinition );
	}
	else {
		return handleCompositeAttribute( attributeDefinition );
	}
}
 
Example 5
Source File: PropertyFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @deprecated See mainly {@link #buildEntityBasedAttribute}
 */
@Deprecated
public static StandardProperty buildStandardProperty(Property property, boolean lazyAvailable) {
	final Type type = property.getValue().getType();

	// we need to dirty check collections, since they can cause an owner
	// version number increment

	// we need to dirty check many-to-ones with not-found="ignore" in order
	// to update the cache (not the database), since in this case a null
	// entity reference can lose information

	boolean alwaysDirtyCheck = type.isAssociationType() &&
			( (AssociationType) type ).isAlwaysDirtyChecked();

	return new StandardProperty(
			property.getName(),
			type,
			lazyAvailable && property.isLazy(),
			property.isInsertable(),
			property.isUpdateable(),
			property.getValueGenerationStrategy(),
			property.isOptional(),
			alwaysDirtyCheck || property.isUpdateable(),
			property.isOptimisticLocked(),
			property.getCascadeStyle(),
			property.getValue().getFetchMode()
	);
}
 
Example 6
Source File: AbstractEntityPersister.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Warning:
 * When there are duplicated property names in the subclasses
 * of the class, this method may return the wrong table
 * number for the duplicated subclass property (note that
 * SingleTableEntityPersister defines an overloaded form
 * which takes the entity name.
 */
public int getSubclassPropertyTableNumber(String propertyPath) {
	String rootPropertyName = StringHelper.root( propertyPath );
	Type type = propertyMapping.toType( rootPropertyName );
	if ( type.isAssociationType() ) {
		AssociationType assocType = (AssociationType) type;
		if ( assocType.useLHSPrimaryKey() ) {
			// performance op to avoid the array search
			return 0;
		}
		else if ( type.isCollectionType() ) {
			// properly handle property-ref-based associations
			rootPropertyName = assocType.getLHSPropertyName();
		}
	}
	//Enable for HHH-440, which we don't like:
	/*if ( type.isComponentType() && !propertyName.equals(rootPropertyName) ) {
		String unrooted = StringHelper.unroot(propertyName);
		int idx = ArrayHelper.indexOf( getSubclassColumnClosure(), unrooted );
		if ( idx != -1 ) {
			return getSubclassColumnTableNumberClosure()[idx];
		}
	}*/
	int index = ArrayHelper.indexOf(
			getSubclassPropertyNameClosure(),
			rootPropertyName
	); //TODO: optimize this better!
	return index == -1 ? 0 : getSubclassPropertyTableNumber( index );
}
 
Example 7
Source File: JoinWalker.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * For an entity class, add to a list of associations to be fetched 
 * by outerjoin
 */
private final void walkEntityTree(
	final OuterJoinLoadable persister,
	final String alias,
	final String path,
	final int currentDepth) 
throws MappingException {

	int n = persister.countSubclassProperties();
	for ( int i=0; i<n; i++ ) {
		Type type = persister.getSubclassPropertyType(i);
		if ( type.isAssociationType() ) {
			walkEntityAssociationTree(
				(AssociationType) type,
				persister,
				i,
				alias,
				path,
				persister.isSubclassPropertyNullable(i),
				currentDepth
			);
		}
		else if ( type.isComponentType() ) {
			walkComponentTree(
				(AbstractComponentType) type,
				i,
				0,
				persister,
				alias,
				subPath( path, persister.getSubclassPropertyName(i) ),
				currentDepth
			);
		}
	}
}
 
Example 8
Source File: IdentNode.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private int resolveAsNakedPropertyRef() {
	FromElement fromElement = locateSingleFromElement();
	if (fromElement == null) {
		return UNKNOWN;
	}
	Queryable persister = fromElement.getQueryable();
	if (persister == null) {
		return UNKNOWN;
	}
	Type propertyType = getNakedPropertyType(fromElement);
	if (propertyType == null) {
		// assume this ident's text does *not* refer to a property on the given persister
		return UNKNOWN;
	}

	if ((propertyType.isComponentType() || propertyType.isAssociationType() )) {
		return COMPONENT_REF;
	}

	setFromElement(fromElement);
	String property = getText();
	String[] columns = getWalker().isSelectStatement()
			? persister.toColumns(fromElement.getTableAlias(), property)
			: persister.toColumns(property);
	String text = StringHelper.join(", ", columns);
	setText(columns.length == 1 ? text : "(" + text + ")");
	setType(SqlTokenTypes.SQL_TOKEN);

	// these pieces are needed for usage in select clause
	super.setDataType(propertyType);
	nakedPropertyRef = true;

	return PROPERTY_REF;
}
 
Example 9
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 10
Source File: Cascade.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Cascade an action to the child or children
 */
private static void cascadeProperty(
		final CascadingAction action,
		final CascadePoint cascadePoint,
		final EventSource eventSource,
		final int componentPathStackDepth,
		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,
						componentPathStackDepth,
						parent,
						child,
						type,
						style,
						anything,
						isCascadeDeleteEnabled
					);
			}
		}
		else if ( type.isComponentType() ) {
			cascadeComponent(
					action,
					cascadePoint,
					eventSource,
					componentPathStackDepth,
					parent,
					child,
					(CompositeType) type,
					anything
			);
		}
	}

	cascadeLogicalOneToOneOrphanRemoval(
			action,
			eventSource,
			componentPathStackDepth,
			parent,
			child,
			type,
			style,
			propertyName,
			isCascadeDeleteEnabled );
}
 
Example 11
Source File: AttributeNodeImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private <X> SubgraphImpl<X> internalMakeKeySubgraph(Class<X> type) {
	if ( ! attribute.isCollection() ) {
		throw new IllegalArgumentException(
				String.format( "Non-collection attribute [%s] cannot be target of key subgraph", getAttributeName() )
		);
	}

	final PluralAttributeImpl pluralAttribute = (PluralAttributeImpl) attribute;
	if ( pluralAttribute.getCollectionType() != PluralAttribute.CollectionType.MAP ) {
		throw new IllegalArgumentException(
				String.format( "Non-Map attribute [%s] cannot be target of key subgraph", getAttributeName() )
		);
	}

	final AssociationType attributeType = (AssociationType) Helper.resolveType( sessionFactory(), attribute );
	final QueryableCollection collectionPersister = (QueryableCollection) attributeType.getAssociatedJoinable( sessionFactory() );
	final Type indexType = collectionPersister.getIndexType();

	if ( ! indexType.isAssociationType() ) {
		throw new IllegalArgumentException(
				String.format( "Map index [%s] is not an entity; cannot be target of key subgraph", getAttributeName() )
		);
	}

	if ( keySubgraphMap == null ) {
		keySubgraphMap = new HashMap<>();
	}

	final AssociationType indexAssociationType = (AssociationType) indexType;
	final EntityPersister indexEntityPersister = (EntityPersister) indexAssociationType.getAssociatedJoinable( sessionFactory() );

	if ( type == null ) {
		type = indexEntityPersister.getMappedClass();
	}
	else {
		if ( !isTreatableAs( indexEntityPersister, type ) ) {
			throw new IllegalArgumentException(
					String.format(
							"Map key [%s] cannot be treated as requested type [%s] : %s",
							getAttributeName(),
							type.getName(),
							indexEntityPersister.getMappedClass().getName()
					)
			);
		}
	}

	final SubgraphImpl<X> subgraph = new SubgraphImpl<>( this.sessionFactory, attribute.getDeclaringType(), type );
	keySubgraphMap.put( type, subgraph );
	return subgraph;
}
 
Example 12
Source File: JoinWalker.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * For a collection role, return a list of associations to be fetched by outerjoin
 */
private void walkCollectionTree(
	final QueryableCollection persister,
	final String alias,
	final String path,
	final int currentDepth)
throws MappingException {

	if ( persister.isOneToMany() ) {
		walkEntityTree(
				(OuterJoinLoadable) persister.getElementPersister(),
				alias,
				path,
				currentDepth
			);
	}
	else {
		Type type = persister.getElementType();
		if ( type.isAssociationType() ) {
			// a many-to-many;
			// decrement currentDepth here to allow join across the association table
			// without exceeding MAX_FETCH_DEPTH (i.e. the "currentDepth - 1" bit)
			AssociationType associationType = (AssociationType) type;
			String[] aliasedLhsColumns = persister.getElementColumnNames(alias);
			String[] lhsColumns = persister.getElementColumnNames();
			// if the current depth is 0, the root thing being loaded is the
			// many-to-many collection itself.  Here, it is alright to use
			// an inner join...
			boolean useInnerJoin = currentDepth == 0;
			final int joinType = getJoinType(
					associationType,
					persister.getFetchMode(),
					path,
					persister.getTableName(),
					lhsColumns,
					!useInnerJoin,
					currentDepth - 1, 
					null //operations which cascade as far as the collection also cascade to collection elements
				);
			addAssociationToJoinTreeIfNecessary(
					associationType,
					aliasedLhsColumns,
					alias,
					path,
					currentDepth - 1,
					joinType
				);
		}
		else if ( type.isComponentType() ) {
			walkCompositeElementTree(
					(AbstractComponentType) type,
					persister.getElementColumnNames(),
					persister,
					alias,
					path,
					currentDepth
				);
		}
	}

}
 
Example 13
Source File: SingleTableEntityPersister.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private int getSubclassPropertyTableNumber(String propertyName, String entityName) {
	Type type = propertyMapping.toType(propertyName);
	if ( type.isAssociationType() && ( (AssociationType) type ).useLHSPrimaryKey() ) return 0;
	final Integer tabnum = (Integer) propertyTableNumbersByNameAndSubclass.get(entityName + '.' + propertyName);
	return tabnum==null ? 0 : tabnum.intValue();
}
 
Example 14
Source File: GrailsHibernateDomainClass.java    From AlgoTrader with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Contructor to be used by all child classes to create a new instance
 * and get the name right.
 *
 * @param clazz          the Grails class
 * @param sessionFactory The Hibernate SessionFactory instance
 * @param metaData       The ClassMetaData for this class retrieved from the SF
 * @param defaultConstraints The default global constraints definition
 */
public GrailsHibernateDomainClass(Class<?> clazz, SessionFactory sessionFactory, GrailsApplication application, ClassMetadata metaData, Map<String, Object> defaultConstraints) {
	super(clazz, "");
	this.application = application;

	new StandardAnnotationMetadata(clazz);
	String ident = metaData.getIdentifierPropertyName();
	this.defaultConstraints = defaultConstraints;
	if (ident != null) {
		Class<?> identType = getPropertyType(ident);
		this.identifier = new GrailsHibernateDomainClassProperty(this, ident);
		this.identifier.setIdentity(true);
		this.identifier.setType(identType);
		this.propertyMap.put(ident, this.identifier);
	}

	// configure the version property
	final int versionIndex = metaData.getVersionProperty();
	String versionPropertyName = null;
	if (versionIndex > -1) {
		versionPropertyName = metaData.getPropertyNames()[versionIndex];
		this.version = new GrailsHibernateDomainClassProperty(this, versionPropertyName);
		this.version.setType(getPropertyType(versionPropertyName));
	}

	// configure remaining properties
	String[] propertyNames = metaData.getPropertyNames();
	boolean[] propertyNullablility = metaData.getPropertyNullability();
	for (int i = 0; i < propertyNames.length; i++) {
		String propertyName = propertyNames[i];
		if (!propertyName.equals(ident) && !(versionPropertyName != null && propertyName.equals(versionPropertyName))) {
			GrailsHibernateDomainClassProperty prop = new GrailsHibernateDomainClassProperty(this, propertyName);
			prop.setType(getPropertyType(propertyName));
			Type hibernateType = metaData.getPropertyType(propertyName);

			// if its an association type
			if (hibernateType.isAssociationType()) {
				prop.setAssociation(true);
				// get the associated type from the session factory and set it on the property
				AssociationType assType = (AssociationType) hibernateType;
				if (assType instanceof AnyType) {
					continue;
				}
				try {
					String associatedEntity = assType.getAssociatedEntityName((SessionFactoryImplementor) sessionFactory);
					ClassMetadata associatedMetaData = sessionFactory.getClassMetadata(associatedEntity);
					prop.setRelatedClassType(associatedMetaData.getMappedClass(EntityMode.POJO));
				} catch (MappingException me) {
					// other side must be a value object
					if (hibernateType.isCollectionType()) {
						prop.setRelatedClassType(Collection.class);
					}
				}
				// configure type of relationship
				if (hibernateType.isCollectionType()) {
					prop.setOneToMany(true);
				} else if (hibernateType.isEntityType()) {
					prop.setManyToOne(true);
					// might not really be true, but for our purposes this is ok
					prop.setOneToOne(true);
				}

				prop.setOptional(propertyNullablility[i]);
			}
			this.propertyMap.put(propertyName, prop);
		}
	}

	this.properties = this.propertyMap.values().toArray(new GrailsDomainClassProperty[this.propertyMap.size()]);
	// process the constraints
	evaluateConstraints();
}
 
Example 15
Source File: AbstractCollectionReference.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private CollectionFetchableElement buildElementGraph() {
	final CollectionPersister persister = collectionQuerySpace.getCollectionPersister();
	final Type type = persister.getElementType();
	if ( type.isAssociationType() ) {
		if ( type.isEntityType() ) {
			final EntityPersister elementPersister = persister.getFactory().getEntityPersister(
					( (EntityType) type ).getAssociatedEntityName()
			);
			final ExpandingEntityQuerySpace entityQuerySpace = QuerySpaceHelper.INSTANCE.makeEntityQuerySpace(
					collectionQuerySpace,
					elementPersister,
					CollectionPropertyNames.COLLECTION_ELEMENTS,
					(EntityType) persister.getElementType(),
					collectionQuerySpace.getExpandingQuerySpaces().generateImplicitUid(),
					collectionQuerySpace.canJoinsBeRequired(),
					allowElementJoin
			);
			return new CollectionFetchableElementEntityGraph( this, entityQuerySpace );
		}
		else if ( type.isAnyType() ) {
			return new CollectionFetchableElementAnyGraph( this );
		}
	}
	else if ( type.isComponentType() ) {
		final ExpandingCompositeQuerySpace compositeQuerySpace = QuerySpaceHelper.INSTANCE.makeCompositeQuerySpace(
				collectionQuerySpace,
				new CompositePropertyMapping(
						(CompositeType) persister.getElementType(),
						(PropertyMapping) persister,
						""
				),
				CollectionPropertyNames.COLLECTION_ELEMENTS,
				(CompositeType) persister.getElementType(),
				collectionQuerySpace.getExpandingQuerySpaces().generateImplicitUid(),
				collectionQuerySpace.canJoinsBeRequired(),
				allowElementJoin
		);
		return new CollectionFetchableElementCompositeGraph( this, compositeQuerySpace );
	}

	return null;
}
 
Example 16
Source File: AbstractCollectionReference.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private CollectionFetchableIndex buildIndexGraph() {
	final CollectionPersister persister = collectionQuerySpace.getCollectionPersister();
	if ( persister.hasIndex() ) {
		final Type type = persister.getIndexType();
		if ( type.isAssociationType() ) {
			if ( type.isEntityType() ) {
				final EntityPersister indexPersister = persister.getFactory().getEntityPersister(
						( (EntityType) type ).getAssociatedEntityName()
				);

				final ExpandingEntityQuerySpace entityQuerySpace = QuerySpaceHelper.INSTANCE.makeEntityQuerySpace(
						collectionQuerySpace,
						indexPersister,
						CollectionPropertyNames.COLLECTION_INDICES,
						(EntityType) persister.getIndexType(),
						collectionQuerySpace.getExpandingQuerySpaces().generateImplicitUid(),
						collectionQuerySpace.canJoinsBeRequired(),
						allowIndexJoin
				);
				return new CollectionFetchableIndexEntityGraph( this, entityQuerySpace );
			}
			else if ( type.isAnyType() ) {
				return new CollectionFetchableIndexAnyGraph( this );
			}
		}
		else if ( type.isComponentType() ) {
			final ExpandingCompositeQuerySpace compositeQuerySpace = QuerySpaceHelper.INSTANCE.makeCompositeQuerySpace(
					collectionQuerySpace,
					new CompositePropertyMapping(
							(CompositeType) persister.getIndexType(),
							(PropertyMapping) persister,
							""
					),
					CollectionPropertyNames.COLLECTION_INDICES,
					(CompositeType) persister.getIndexType(),
					collectionQuerySpace.getExpandingQuerySpaces().generateImplicitUid(),
					collectionQuerySpace.canJoinsBeRequired(),
					allowIndexJoin
			);
			return new CollectionFetchableIndexCompositeGraph( this, compositeQuerySpace );
		}
	}

	return null;
}
 
Example 17
Source File: AbstractSelectExpression.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public boolean isScalar() throws SemanticException {
	// Default implementation:
	// If this node has a data type, and that data type is not an association, then this is scalar.
	Type type = getDataType();
	return type != null && !type.isAssociationType();	// Moved here from SelectClause [jsd]
}
 
Example 18
Source File: CriteriaQueryTranslator.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private CriteriaInfoProvider getPathInfo(String path) {
	StringTokenizer tokens = new StringTokenizer( path, "." );
	String componentPath = "";

	// start with the 'rootProvider'
	CriteriaInfoProvider provider = nameCriteriaInfoMap.get( rootEntityName );

	while ( tokens.hasMoreTokens() ) {
		componentPath += tokens.nextToken();
		final Type type = provider.getType( componentPath );
		if ( type.isAssociationType() ) {
			// CollectionTypes are always also AssociationTypes - but there's not always an associated entity...
			final AssociationType atype = (AssociationType) type;
			final CollectionType ctype = type.isCollectionType() ? (CollectionType)type : null;
			final Type elementType = (ctype != null) ? ctype.getElementType( sessionFactory ) : null;
			// is the association a collection of components or value-types? (i.e a colloction of valued types?)
			if ( ctype != null  && elementType.isComponentType() ) {
				provider = new ComponentCollectionCriteriaInfoProvider( helper.getCollectionPersister(ctype.getRole()) );
			}
			else if ( ctype != null && !elementType.isEntityType() ) {
				provider = new ScalarCollectionCriteriaInfoProvider( helper, ctype.getRole() );
			}
			else {
				provider = new EntityCriteriaInfoProvider(
						(Queryable) sessionFactory.getEntityPersister( atype.getAssociatedEntityName( sessionFactory ) )
				);
			}

			componentPath = "";
		}
		else if ( type.isComponentType() ) {
			if (!tokens.hasMoreTokens()) {
				throw new QueryException(
						"Criteria objects cannot be created directly on components.  Create a criteria on " +
								"owning entity and use a dotted property to access component property: " + path
				);
			}
			else {
				componentPath += '.';
			}
		}
		else {
			throw new QueryException( "not an association: " + componentPath );
		}
	}

	return provider;
}
 
Example 19
Source File: JoinWalker.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Walk the association tree for an entity, adding associations which should
 * be join fetched to the {@link #associations} inst var.  This form is the
 * entry point into the walking for a given entity, starting the recursive
 * calls into {@link #walkEntityTree(org.hibernate.persister.entity.OuterJoinLoadable, String, PropertyPath, int)}.
 *
 * @param persister The persister representing the entity to be walked.
 * @param alias The (root) alias to use for this entity/persister.
 * @param path The property path to the entity being walked
 * @param currentDepth The current join depth
 *
 * @throws org.hibernate.MappingException ???
 */
private void walkEntityTree(
		final OuterJoinLoadable persister,
		final String alias,
		final PropertyPath path,
		final int currentDepth) throws MappingException {
	int n = persister.countSubclassProperties();
	for ( int i = 0; i < n; i++ ) {
		Type type = persister.getSubclassPropertyType( i );
		if ( type.isAssociationType() ) {
			walkEntityAssociationTree(
					(AssociationType) type,
					persister,
					i,
					alias,
					path,
					persister.isSubclassPropertyNullable( i ),
					currentDepth
			);
		}
		else if ( type.isComponentType() ) {
			walkComponentTree(
					(CompositeType) type,
					i,
					0,
					persister,
					alias,
					path.append( persister.getSubclassPropertyName( i ) ),
					currentDepth
			);
		}
	}

	// if the entity has a composite identifier, see if we need to handle
	// its sub-properties separately
	final Type idType = persister.getIdentifierType();
	if ( idType.isComponentType() ) {
		final CompositeType cidType = (CompositeType) idType;
		if ( cidType.isEmbedded() ) {
			// we have an embedded composite identifier.  Most likely we need to process the composite
			// properties separately, although there is an edge case where the identifier is really
			// a simple identifier (single value) wrapped in a JPA @IdClass or even in the case of a
			// a simple identifier (single value) wrapped in a Hibernate composite type.
			//
			// We really do not have a built-in method to determine that.  However, generally the
			// persister would report that there is single, physical identifier property which is
			// explicitly at odds with the notion of "embedded composite".  So we use that for now
			if ( persister.getEntityMetamodel().getIdentifierProperty().isEmbedded() ) {
				walkComponentTree(
						cidType,
						-1,
						0,
						persister,
						alias,
						path,
						currentDepth
				);
			}
		}
	}
}
 
Example 20
Source File: IgnitePropertyHelper.java    From hibernate-ogm-ignite with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
	 * Returns the {@link PropertyIdentifier} for the given property path.
	 *
	 * In passing, it creates all the necessary aliases for embedded/associations.
	 *
	 * @param path the path to the property
	 * @param targetEntityType the type of the entity
	 * @return the {@link PropertyIdentifier}
	 */
	PropertyIdentifier getPropertyIdentifier(PropertyPath path, String targetEntityType) {
		// we analyze the property path to find all the associations/embedded
		// which are in the way and create proper aliases for them

		List<String> propertyPath = path.getNodeNamesWithoutAlias();
		String entityAlias;
		boolean isLastElementAssociation = true;
		if ( path.getFirstNode().isAlias() ) {
			entityAlias = path.getFirstNode().getName();
		}
		else {
			entityAlias = findAliasForType( targetEntityType );
		}
		String propertyEntityType = entityNameByAlias.get( entityAlias );
		if ( propertyEntityType == null ) {
			propertyEntityType = targetEntityType;
		}

		String propertyAlias = entityAlias;
		String propertyName;

		List<String> currentPropertyPath = new ArrayList<>();
		List<String> lastAssociationPath = new ArrayList<>();

		OgmEntityPersister currentPersister = getPersister( propertyEntityType );
		OgmEntityPersister predPersister = currentPersister;
		String predJoinAlias = entityAlias;

		for ( String property : propertyPath ) {
			currentPropertyPath.add( property );
			Type currentPropertyType = getPropertyType( propertyEntityType, Collections.singletonList( property ) );

			if ( currentPropertyType.isAssociationType() ) {
				propertyEntityType = currentPropertyType.getName();
				currentPersister = getPersister( propertyEntityType );
				AssociationType associationPropertyType = (AssociationType) currentPropertyType;
				Joinable associatedJoinable = associationPropertyType.getAssociatedJoinable( getSessionFactory() );
				if ( associatedJoinable.isCollection()
					&& ( (OgmCollectionPersister) associatedJoinable ).getType().isComponentType() ) {
					// we have a collection of embedded
					throw new NotYetImplementedException( "Query with collection of embeddables" );
//					propertyAlias = aliasResolver.createAliasForEmbedded( entityAlias, currentPropertyPath, optionalMatch );
				}
				else {
					// last in path? - no need for join
					if ( currentPropertyPath.size() == propertyPath.size() ) {
						propertyName = getColumnName( predPersister.getEntityType().getName(),
							Collections.singletonList( property ) );
						return new PropertyIdentifier( predJoinAlias, propertyName );
					}
					// else, we register an implicit join
					lastAssociationPath.add( property );
					throw new NotYetImplementedException( "Query on associated property" );
					// predPersister = currentPersister;
					// isLastElementAssociation = true;
				}
			}
			else if ( currentPropertyType.isComponentType()
				&& !isIdProperty( currentPersister, propertyPath.subList( lastAssociationPath.size(), propertyPath.size() ) ) ) {
				// we are in the embedded case and the embedded is not the id of the entity (the id is stored as normal
				// properties)
				String embeddedProperty = String.join( ".", propertyPath.subList( lastAssociationPath.size(), propertyPath.size() ) );
				String[] columns = currentPersister.getPropertyColumnNames( embeddedProperty );
				if ( columns.length > 1 ) {
					throw new NotYetImplementedException( "Query with composite-ID association" );
				}
				return new PropertyIdentifier( propertyAlias, columns[0] );
			}
			else {
				isLastElementAssociation = false;
			}
		}

		if ( isLastElementAssociation ) {
			// even the last element is an association, we need to find a suitable identifier property
			propertyName = getPersister( propertyEntityType ).getIdentifierPropertyName();
		}
		else {
			// the last element is a property so we can build the rest with this property
			propertyName = getColumnName( propertyEntityType, propertyPath.subList( lastAssociationPath.size(), propertyPath.size() ) );
		}
		return new PropertyIdentifier( predJoinAlias, propertyName );
	}