Java Code Examples for org.hibernate.type.Type.isCollectionType()

The following are Jave code examples for showing how to use isCollectionType() of the org.hibernate.type.Type class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: lams   File: HibernateTraversableResolver.java   View Source Code Vote up 6 votes
private void addAssociationsToTheSetForOneProperty(String name, Type type, String prefix, SessionFactoryImplementor factory) {

		if ( type.isCollectionType() ) {
			CollectionType collType = (CollectionType) type;
			Type assocType = collType.getElementType( factory );
			addAssociationsToTheSetForOneProperty(name, assocType, prefix, factory);
		}
		//ToOne association
		else if ( type.isEntityType() || type.isAnyType() ) {
			associations.add( prefix + name );
		} else if ( type.isComponentType() ) {
			CompositeType componentType = (CompositeType) type;
			addAssociationsToTheSetForAllProperties(
					componentType.getPropertyNames(),
					componentType.getSubtypes(),
					(prefix.equals( "" ) ? name : prefix + name) + ".",
					factory);
		}
	}
 
Example 2
Project: lams   File: AbstractEmptinessExpression.java   View Source Code Vote up 6 votes
protected QueryableCollection getQueryableCollection(
		String entityName,
		String propertyName,
		SessionFactoryImplementor factory) throws HibernateException {
	final PropertyMapping ownerMapping = (PropertyMapping) factory.getEntityPersister( entityName );
	final Type type = ownerMapping.toType( propertyName );
	if ( !type.isCollectionType() ) {
		throw new MappingException(
				"Property path [" + entityName + "." + propertyName + "] does not reference a collection"
		);
	}

	final String role = ( (CollectionType) type ).getRole();
	try {
		return (QueryableCollection) factory.getCollectionPersister( role );
	}
	catch ( ClassCastException cce ) {
		throw new QueryException( "collection role is not queryable: " + role );
	}
	catch ( Exception e ) {
		throw new QueryException( "collection role not found: " + role );
	}
}
 
Example 3
Project: lams   File: AbstractEntityPersister.java   View Source Code Vote up 6 votes
/**
 * 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 4
Project: lams   File: PropertyFactory.java   View Source Code Vote up 6 votes
private static NonIdentifierAttributeNature decode(Type type) {
	if ( type.isAssociationType() ) {
		AssociationType associationType = (AssociationType) type;

		if ( type.isComponentType() ) {
			// an any type is both an association and a composite...
			return NonIdentifierAttributeNature.ANY;
		}

		return type.isCollectionType()
				? NonIdentifierAttributeNature.COLLECTION
				: NonIdentifierAttributeNature.ENTITY;
	}
	else {
		if ( type.isComponentType() ) {
			return NonIdentifierAttributeNature.COMPOSITE;
		}

		return NonIdentifierAttributeNature.BASIC;
	}
}
 
Example 5
Project: lams   File: Nullability.java   View Source Code Vote up 6 votes
/**
 * check sub elements-nullability. Returns property path that break
 * nullability or null if none
 *
 * @param propertyType type to check
 * @param value value to check
 *
 * @return property path
 * @throws HibernateException error while getting subcomponent values
 */
private String checkSubElementsNullability(Type propertyType, Object value) throws HibernateException {
	if ( propertyType.isComponentType() ) {
		return checkComponentNullability( value, (CompositeType) propertyType );
	}

	if ( propertyType.isCollectionType() ) {
		// persistent collections may have components
		final CollectionType collectionType = (CollectionType) propertyType;
		final Type collectionElementType = collectionType.getElementType( session.getFactory() );

		if ( collectionElementType.isComponentType() ) {
			// check for all components values in the collection
			final CompositeType componentType = (CompositeType) collectionElementType;
			final Iterator itr = CascadingActions.getLoadedElementsIterator( session, collectionType, value );
			while ( itr.hasNext() ) {
				final Object compositeElement = itr.next();
				if ( compositeElement != null ) {
					return checkComponentNullability( compositeElement, componentType );
				}
			}
		}
	}

	return null;
}
 
Example 6
Project: lams   File: AbstractVisitor.java   View Source Code Vote up 6 votes
/**
 * Visit a property value. Dispatch to the
 * correct handler for the property type.
 * @param value
 * @param type
 * @throws HibernateException
 */
final Object processValue(Object value, Type type) throws HibernateException {

	if ( type.isCollectionType() ) {
		//even process null collections
		return processCollection( value, (CollectionType) type );
	}
	else if ( type.isEntityType() ) {
		return processEntity( value, (EntityType) type );
	}
	else if ( type.isComponentType() ) {
		return processComponent( value, (CompositeType) type );
	}
	else {
		return null;
	}
}
 
Example 7
Project: lams   File: FromPathExpressionParser.java   View Source Code Vote up 6 votes
public void end(QueryTranslatorImpl q) throws QueryException {
	if ( !isCollectionValued() ) {
		Type type = getPropertyType();
		if ( type.isEntityType() ) {
			// "finish off" the join
			token( ".", q );
			token( null, q );
		}
		else if ( type.isCollectionType() ) {
			// default to element set if no elements() specified
			token( ".", q );
			token( CollectionPropertyNames.COLLECTION_ELEMENTS, q );
		}
	}
	super.end( q );
}
 
Example 8
Project: lams   File: FromElementFactory.java   View Source Code Vote up 6 votes
private FromElement createCollectionJoin(JoinSequence collectionJoinSequence, String tableAlias)
			throws SemanticException {
		String text = queryableCollection.getTableName();
		AST ast = createFromElement( text );
		FromElement destination = (FromElement) ast;
		Type elementType = queryableCollection.getElementType();
		if ( elementType.isCollectionType() ) {
			throw new SemanticException( "Collections of collections are not supported!" );
		}
		destination.initializeCollection( fromClause, classAlias, tableAlias );
		destination.setType( JOIN_FRAGMENT );        // Tag this node as a JOIN.
		destination.setIncludeSubclasses( false );    // Don't include subclasses in the join.
		destination.setCollectionJoin( true );        // This is a clollection join.
		destination.setJoinSequence( collectionJoinSequence );
		destination.setOrigin( origin, false );
		destination.setCollectionTableAlias( tableAlias );
//		origin.addDestination( destination );
// This was the cause of HHH-242
//		origin.setType( FROM_FRAGMENT );			// Set the parent node type so that the AST is properly formed.
		origin.setText( "" );                        // The destination node will have all the FROM text.
		origin.setCollectionJoin( true );            // The parent node is a collection join too (voodoo - see JoinProcessor)
		fromClause.addCollectionJoinFromElementByPath( path, destination );
		fromClause.getWalker().addQuerySpaces( queryableCollection.getCollectionSpaces() );
		return destination;
	}
 
Example 9
Project: lams   File: PathExpressionParser.java   View Source Code Vote up 6 votes
public void end(QueryTranslatorImpl q) throws QueryException {
	ignoreInitialJoin = false;

	Type propertyType = getPropertyType();
	if ( propertyType != null && propertyType.isCollectionType() ) {
		collectionRole = ( ( CollectionType ) propertyType ).getRole();
		collectionName = q.createNameForCollection( collectionRole );
		prepareForIndex( q );
	}
	else {
		columns = currentColumns();
		setType();
	}

	//important!!
	continuation = false;

}
 
Example 10
Project: lams   File: Property.java   View Source Code Vote up 5 votes
public CascadeStyle getCascadeStyle() throws MappingException {
	Type type = value.getType();
	if ( type.isComponentType() ) {
		return getCompositeCascadeStyle( (CompositeType) type, cascade );
	}
	else if ( type.isCollectionType() ) {
		return getCollectionCascadeStyle( ( (Collection) value ).getElement().getType(), cascade );
	}
	else {
		return getCascadeStyle( cascade );			
	}
}
 
Example 11
Project: lams   File: SQLQueryReturnProcessor.java   View Source Code Vote up 5 votes
private void processJoinReturn(NativeSQLQueryJoinReturn fetchReturn) {
		String alias = fetchReturn.getAlias();
//		if ( alias2Persister.containsKey( alias ) || collectionAliases.contains( alias ) ) {
		if ( alias2Persister.containsKey( alias ) || alias2CollectionPersister.containsKey( alias ) ) {
			// already been processed...
			return;
		}

		String ownerAlias = fetchReturn.getOwnerAlias();

		// Make sure the owner alias is known...
		if ( !alias2Return.containsKey( ownerAlias ) ) {
			throw new HibernateException( "Owner alias [" + ownerAlias + "] is unknown for alias [" + alias + "]" );
		}

		// If this return's alias has not been processed yet, do so b4 further processing of this return
		if ( !alias2Persister.containsKey( ownerAlias ) ) {
			NativeSQLQueryNonScalarReturn ownerReturn = ( NativeSQLQueryNonScalarReturn ) alias2Return.get(ownerAlias);
			processReturn( ownerReturn );
		}

		SQLLoadable ownerPersister = ( SQLLoadable ) alias2Persister.get( ownerAlias );
		Type returnType = ownerPersister.getPropertyType( fetchReturn.getOwnerProperty() );

		if ( returnType.isCollectionType() ) {
			String role = ownerPersister.getEntityName() + '.' + fetchReturn.getOwnerProperty();
			addCollection( role, alias, fetchReturn.getPropertyResultsMap() );
//			collectionOwnerAliases.add( ownerAlias );
		}
		else if ( returnType.isEntityType() ) {
			EntityType eType = ( EntityType ) returnType;
			String returnEntityName = eType.getAssociatedEntityName();
			SQLLoadable persister = getSQLLoadable( returnEntityName );
			addPersister( alias, fetchReturn.getPropertyResultsMap(), persister );
		}

	}
 
Example 12
Project: lams   File: EntityMetamodel.java   View Source Code Vote up 5 votes
private boolean indicatesCollection(Type type) {
	if ( type.isCollectionType() ) {
		return true;
	}
	else if ( type.isComponentType() ) {
		Type[] subtypes = ( (CompositeType) type ).getSubtypes();
		for ( int i = 0; i < subtypes.length; i++ ) {
			if ( indicatesCollection( subtypes[i] ) ) {
				return true;
			}
		}
	}
	return false;
}
 
Example 13
Project: lams   File: FetchProfile.java   View Source Code Vote up 5 votes
/**
 * Add a fetch to the profile.
 *
 * @param fetch The fetch to add.
 */
public void addFetch(final Fetch fetch) {
	final String fetchAssociactionRole = fetch.getAssociation().getRole();
	final Type associationType = fetch.getAssociation().getOwner().getPropertyType( fetch.getAssociation().getAssociationPath() );
	if ( associationType.isCollectionType() ) {
		LOG.tracev( "Handling request to add collection fetch [{0}]", fetchAssociactionRole );

		// couple of things for which to account in the case of collection
		// join fetches
		if ( Fetch.Style.JOIN == fetch.getStyle() ) {
			// first, if this is a bag we need to ignore it if we previously
			// processed collection join fetches
			if ( BagType.class.isInstance( associationType ) ) {
				if ( containsJoinFetchedCollection ) {
					LOG.containsJoinFetchedCollection( fetchAssociactionRole );
					// EARLY EXIT!!!
					return;
				}
			}

			// also, in cases where we are asked to add a collection join
			// fetch where we had already added a bag join fetch previously,
			// we need to go back and ignore that previous bag join fetch.
			if ( containsJoinFetchedBag ) {
				// just for safety...
				if ( fetches.remove( bagJoinFetch.getAssociation().getRole() ) != bagJoinFetch ) {
					LOG.unableToRemoveBagJoinFetch();
				}
				bagJoinFetch = null;
				containsJoinFetchedBag = false;
			}

			containsJoinFetchedCollection = true;
		}
	}
	fetches.put( fetchAssociactionRole, fetch );
}
 
Example 14
Project: lams   File: Cascade.java   View Source Code Vote up 5 votes
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 );
	}
}
 
Example 15
Project: lams   File: DefaultRefreshEventListener.java   View Source Code Vote up 5 votes
private void evictCachedCollections(Type[] types, Serializable id, SessionFactoryImplementor factory)
		throws HibernateException {
	for ( Type type : types ) {
		if ( type.isCollectionType() ) {
			factory.getCache().evictCollection( ( (CollectionType) type ).getRole(), id );
		}
		else if ( type.isComponentType() ) {
			CompositeType actype = (CompositeType) type;
			evictCachedCollections( actype.getSubtypes(), id, factory );
		}
	}
}
 
Example 16
Project: lams   File: DotNode.java   View Source Code Vote up 5 votes
@Override
public void resolveInFunctionCall(boolean generateJoin, boolean implicitJoin) throws SemanticException {
	if ( isResolved() ) {
		return;
	}
	Type propertyType = prepareLhs();            // Prepare the left hand side and get the data type.
	if ( propertyType != null && propertyType.isCollectionType() ) {
		resolveIndex( null );
	}
	else {
		resolveFirstChild();
		super.resolve( generateJoin, implicitJoin );
	}
}
 
Example 17
Project: lams   File: CriteriaQueryTranslator.java   View Source Code Vote up 4 votes
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 18
Project: lams   File: TableBasedDeleteHandlerImpl.java   View Source Code Vote up 4 votes
public TableBasedDeleteHandlerImpl(
		SessionFactoryImplementor factory,
		HqlSqlWalker walker,
		String catalog,
		String schema) {
	super( factory, walker, catalog, schema );

	DeleteStatement deleteStatement = ( DeleteStatement ) walker.getAST();
	FromElement fromElement = deleteStatement.getFromClause().getFromElement();

	this.targetedPersister = fromElement.getQueryable();
	final String bulkTargetAlias = fromElement.getTableAlias();

	final ProcessedWhereClause processedWhereClause = processWhereClause( deleteStatement.getWhereClause() );
	this.idSelectParameterSpecifications = processedWhereClause.getIdSelectParameterSpecifications();
	this.idInsertSelect = generateIdInsertSelect( targetedPersister, bulkTargetAlias, processedWhereClause );
	log.tracev( "Generated ID-INSERT-SELECT SQL (multi-table delete) : {0}", idInsertSelect );
	
	final String idSubselect = generateIdSubselect( targetedPersister );
	deletes = new ArrayList<String>();
	
	// If many-to-many, delete the FK row in the collection table.
	// This partially overlaps with DeleteExecutor, but it instead uses the temp table in the idSubselect.
	for ( Type type : targetedPersister.getPropertyTypes() ) {
		if ( type.isCollectionType() ) {
			CollectionType cType = (CollectionType) type;
			AbstractCollectionPersister cPersister = (AbstractCollectionPersister)factory.getCollectionPersister( cType.getRole() );
			if ( cPersister.isManyToMany() ) {
				deletes.add( generateDelete( cPersister.getTableName(),
						cPersister.getKeyColumnNames(), idSubselect, "bulk delete - m2m join table cleanup"));
			}
		}
	}

	String[] tableNames = targetedPersister.getConstraintOrderedTableNameClosure();
	String[][] columnNames = targetedPersister.getContraintOrderedTableKeyColumnClosure();
	for ( int i = 0; i < tableNames.length; i++ ) {
		// TODO : an optimization here would be to consider cascade deletes and not gen those delete statements;
		//      the difficulty is the ordering of the tables here vs the cascade attributes on the persisters ->
		//          the table info gotten here should really be self-contained (i.e., a class representation
		//          defining all the needed attributes), then we could then get an array of those
		deletes.add( generateDelete( tableNames[i], columnNames[i], idSubselect, "bulk delete"));
	}
}
 
Example 19
Project: Layer-Query   File: CustomCriteriaQueryTranslator.java   View Source Code Vote up 4 votes
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 20
Project: lams   File: DeleteExecutor.java   View Source Code Vote up 4 votes
public DeleteExecutor(HqlSqlWalker walker, Queryable persister) {
	super( walker, persister );
	
	final SessionFactoryImplementor factory = walker.getSessionFactoryHelper().getFactory();
	final Dialect dialect = factory.getDialect();
	
	try {
		final DeleteStatement deleteStatement = (DeleteStatement) walker.getAST();
		
		final String idSubselectWhere;
		if ( deleteStatement.hasWhereClause() ) {
			final AST whereClause = deleteStatement.getWhereClause();
			final SqlGenerator gen = new SqlGenerator( factory );
			gen.whereClause( whereClause );
			parameterSpecifications = gen.getCollectedParameters();
			idSubselectWhere = gen.getSQL().length() > 7 ? gen.getSQL() : "";
		}
		else {
			parameterSpecifications = new ArrayList<ParameterSpecification>();
			idSubselectWhere = "";
		}
		
		// If many-to-many, delete the FK row in the collection table.
		for ( Type type : persister.getPropertyTypes() ) {
			if ( type.isCollectionType() ) {
				final CollectionType cType = (CollectionType) type;
				final AbstractCollectionPersister cPersister = (AbstractCollectionPersister) factory
						.getCollectionPersister( cType.getRole() );
				if ( cPersister.isManyToMany() ) {
					if ( persister.getIdentifierColumnNames().length > 1
							&& !dialect.supportsTuplesInSubqueries() ) {
						LOG.warn(
								"This dialect is unable to cascade the delete into the many-to-many join table" +
								" when the entity has multiple primary keys.  Either properly setup cascading on" +
								" the constraints or manually clear the associations prior to deleting the entities."
						);
					}
					else {
						final String idSubselect = "(select "
								+ StringHelper.join( ", ", persister.getIdentifierColumnNames() ) + " from "
								+ persister.getTableName() + idSubselectWhere + ")";
						final String where = "(" + StringHelper.join( ", ", cPersister.getKeyColumnNames() )
								+ ") in " + idSubselect;
						final Delete delete = new Delete().setTableName( cPersister.getTableName() ).setWhere( where );
						if ( factory.getSettings().isCommentsEnabled() ) {
							delete.setComment( "delete FKs in join table" );
						}
						deletes.add( delete.toStatementString() );
					}
				}
			}
		}
	}
	catch (RecognitionException e) {
		throw new HibernateException( "Unable to delete the FKs in the join table!", e );
	}
}