Java Code Examples for org.hibernate.type.CollectionType#getRole()

The following examples show how to use org.hibernate.type.CollectionType#getRole() . 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: IdentNode.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public void resolveIndex(AST parent) throws SemanticException {
	// An ident node can represent an index expression if the ident
	// represents a naked property ref
	//      *Note: this makes the assumption (which is currently the case
	//      in the hql-sql grammar) that the ident is first resolved
	//      itself (addrExpr -> resolve()).  The other option, if that
	//      changes, is to call resolve from here; but it is
	//      currently un-needed overhead.
	if (!(isResolved() && nakedPropertyRef)) {
		throw new UnsupportedOperationException();
	}

	String propertyName = getOriginalText();
	if (!getDataType().isCollectionType()) {
		throw new SemanticException("Collection expected; [" + propertyName + "] does not refer to a collection property");
	}

	// TODO : most of below was taken verbatim from DotNode; should either delegate this logic or super-type it
	CollectionType type = (CollectionType) getDataType();
	String role = type.getRole();
	QueryableCollection queryableCollection = getSessionFactoryHelper().requireQueryableCollection(role);

	String alias = null;  // DotNode uses null here...
	String columnTableAlias = getFromElement().getTableAlias();
	JoinType joinType = JoinType.INNER_JOIN;
	boolean fetch = false;

	FromElementFactory factory = new FromElementFactory(
			getWalker().getCurrentFromClause(),
			getFromElement(),
			propertyName,
			alias,
			getFromElement().toColumns(columnTableAlias, propertyName, false),
			true
	);
	FromElement elem = factory.createCollection(queryableCollection, role, joinType, fetch, true);
	setFromElement(elem);
	getWalker().addQuerySpaces(queryableCollection.getCollectionSpaces());	// Always add the collection's query spaces.
}
 
Example 2
Source File: IdentNode.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void resolveIndex(AST parent) throws SemanticException {
	// An ident node can represent an index expression if the ident
	// represents a naked property ref
	//      *Note: this makes the assumption (which is currently the case
	//      in the hql-sql grammar) that the ident is first resolved
	//      itself (addrExpr -> resolve()).  The other option, if that
	//      changes, is to call resolve from here; but it is
	//      currently un-needed overhead.
	if (!(isResolved() && nakedPropertyRef)) {
		throw new UnsupportedOperationException();
	}

	String propertyName = getOriginalText();
	if (!getDataType().isCollectionType()) {
		throw new SemanticException("Collection expected; [" + propertyName + "] does not refer to a collection property");
	}

	// TODO : most of below was taken verbatim from DotNode; should either delegate this logic or super-type it
	CollectionType type = (CollectionType) getDataType();
	String role = type.getRole();
	QueryableCollection queryableCollection = getSessionFactoryHelper().requireQueryableCollection(role);

	String alias = null;  // DotNode uses null here...
	String columnTableAlias = getFromElement().getTableAlias();
	int joinType = JoinFragment.INNER_JOIN;
	boolean fetch = false;

	FromElementFactory factory = new FromElementFactory(
			getWalker().getCurrentFromClause(),
			getFromElement(),
			propertyName,
			alias,
			getFromElement().toColumns(columnTableAlias, propertyName, false),
			true
	);
	FromElement elem = factory.createCollection(queryableCollection, role, joinType, fetch, true);
	setFromElement(elem);
	getWalker().addQuerySpaces(queryableCollection.getCollectionSpaces());	// Always add the collection's query spaces.
}
 
Example 3
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 4
Source File: Collections.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
    * Initialize the role of the collection.
    *
    * @param collection The collection to be updated by reachability.
    * @param type The type of the collection.
    * @param entity The owner of the collection.
 * @param session The session from which this request originates
    */
public static void processReachableCollection(
		PersistentCollection collection,
		CollectionType type,
		Object entity,
		SessionImplementor session) {
	collection.setOwner( entity );
	final CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( collection );

	if ( ce == null ) {
		// refer to comment in StatefulPersistenceContext.addCollection()
		throw new HibernateException(
				"Found two representations of same collection: " +
				type.getRole()
		);
	}

	final SessionFactoryImplementor factory = session.getFactory();
	final CollectionPersister persister = factory.getMetamodel().collectionPersister( type.getRole() );

	ce.setCurrentPersister( persister );
	//TODO: better to pass the id in as an argument?
	ce.setCurrentKey( type.getKeyOfOwner( entity, session ) );

	final boolean isBytecodeEnhanced = persister.getOwnerEntityPersister().getInstrumentationMetadata().isEnhancedForLazyLoading();
	if ( isBytecodeEnhanced && !collection.wasInitialized() ) {
		// skip it
		LOG.debugf(
				"Skipping uninitialized bytecode-lazy collection: %s",
				MessageHelper.collectionInfoString( persister, collection, ce.getCurrentKey(), session )
		);
		ce.setReached( true );
		ce.setProcessed( true );
	}
	else {
		// The CollectionEntry.isReached() stuff is just to detect any silly users
		// who set up circular or shared references between/to collections.
		if ( ce.isReached() ) {
			// We've been here before
			throw new HibernateException(
					"Found shared references to a collection: " + type.getRole()
			);
		}
		ce.setReached( true );

		if ( LOG.isDebugEnabled() ) {
			if ( collection.wasInitialized() ) {
				LOG.debugf(
						"Collection found: %s, was: %s (initialized)",
						MessageHelper.collectionInfoString(
								persister,
								collection,
								ce.getCurrentKey(),
								session
						),
						MessageHelper.collectionInfoString(
								ce.getLoadedPersister(),
								collection,
								ce.getLoadedKey(),
								session
						)
				);
			}
			else {
				LOG.debugf(
						"Collection found: %s, was: %s (uninitialized)",
						MessageHelper.collectionInfoString(
								persister,
								collection,
								ce.getCurrentKey(),
								session
						),
						MessageHelper.collectionInfoString(
								ce.getLoadedPersister(),
								collection,
								ce.getLoadedKey(),
								session
						)
				);
			}
		}

		prepareCollectionForUpdate( collection, ce, factory );
	}
}
 
Example 5
Source File: DotNode.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private void dereferenceCollection(
		CollectionType collectionType,
		boolean implicitJoin,
		boolean indexed,
		String classAlias,
		AST parent)
		throws SemanticException {

	dereferenceType = DereferenceType.COLLECTION;
	String role = collectionType.getRole();

	//foo.bars.size (also handles deprecated stuff like foo.bars.maxelement for backwardness)
	boolean isSizeProperty = getNextSibling() != null &&
			CollectionProperties.isAnyCollectionProperty( getNextSibling().getText() );

	if ( isSizeProperty ) {
		indexed = true; //yuck!
	}

	QueryableCollection queryableCollection = getSessionFactoryHelper().requireQueryableCollection( role );
	String propName = getPath();
	FromClause currentFromClause = getWalker().getCurrentFromClause();

	// If the lhs of the join is a "component join", we need to go back to the
	// first non-component-join as the origin to properly link aliases and
	// join columns
	FromElement lhsFromElement = getLhs().getFromElement();
	while ( lhsFromElement != null && ComponentJoin.class.isInstance( lhsFromElement ) ) {
		lhsFromElement = lhsFromElement.getOrigin();
	}
	if ( lhsFromElement == null ) {
		throw new QueryException( "Unable to locate appropriate lhs" );
	}

	// determine whether we should use the table name or table alias to qualify the column names...
	// we need to use the table-name when:
	//		1) the top-level statement is not a SELECT
	//		2) the LHS FromElement is *the* FromElement from the top-level statement
	//
	// there is a caveat here.. if the update/delete statement are "multi-table" we should continue to use
	// the alias also, even if the FromElement is the root one...
	//
	// in all other cases, we should use the table alias
	if ( getWalker().getStatementType() != SqlTokenTypes.SELECT ) {
		if ( isFromElementUpdateOrDeleteRoot( lhsFromElement ) ) {
			// at this point we know we have the 2 conditions above,
			// lets see if we have the mentioned "multi-table" caveat...
			boolean useAlias = false;
			if ( getWalker().getStatementType() != SqlTokenTypes.INSERT ) {
				final Queryable persister = lhsFromElement.getQueryable();
				if ( persister.isMultiTable() ) {
					useAlias = true;
				}
			}
			if ( !useAlias ) {
				final String lhsTableName = lhsFromElement.getQueryable().getTableName();
				columns = getFromElement().toColumns( lhsTableName, propertyPath, false, true );
			}
		}
	}

	// We do not look for an existing join on the same path, because
	// it makes sense to join twice on the same collection role
	FromElementFactory factory = new FromElementFactory(
			currentFromClause,
			lhsFromElement,
			propName,
			classAlias,
			getColumns(),
			implicitJoin
	);
	FromElement elem = factory.createCollection( queryableCollection, role, joinType, fetch, indexed );

	LOG.debugf( "dereferenceCollection() : Created new FROM element for %s : %s", propName, elem );

	setImpliedJoin( elem );
	setFromElement( elem );    // This 'dot' expression now refers to the resulting from element.

	if ( isSizeProperty ) {
		elem.setText( "" );
		elem.setUseWhereFragment( false );
	}

	if ( !implicitJoin ) {
		EntityPersister entityPersister = elem.getEntityPersister();
		if ( entityPersister != null ) {
			getWalker().addQuerySpaces( entityPersister.getQuerySpaces() );
		}
	}
	getWalker().addQuerySpaces( queryableCollection.getCollectionSpaces() );    // Always add the collection's query spaces.
}
 
Example 6
Source File: FromElementFactory.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
FromElement createElementJoin(QueryableCollection queryableCollection) throws SemanticException {
		FromElement elem;

		implied = true; //TODO: always true for now, but not if we later decide to support elements() in the from clause
		inElementsFunction = true;
		Type elementType = queryableCollection.getElementType();
		if ( !elementType.isEntityType() ) {
			throw new IllegalArgumentException( "Cannot create element join for a collection of non-entities!" );
		}
		this.queryableCollection = queryableCollection;
		SessionFactoryHelper sfh = fromClause.getSessionFactoryHelper();
		FromElement destination = null;
		String tableAlias = null;
		EntityPersister entityPersister = queryableCollection.getElementPersister();
		tableAlias = fromClause.getAliasGenerator().createName( entityPersister.getEntityName() );
		String associatedEntityName = entityPersister.getEntityName();
		EntityPersister targetEntityPersister = sfh.requireClassPersister( associatedEntityName );
		// Create the FROM element for the target (the elements of the collection).
		destination = createAndAddFromElement(
				associatedEntityName,
				classAlias,
				targetEntityPersister,
				(EntityType) queryableCollection.getElementType(),
				tableAlias
		);
		// If the join is implied, then don't include sub-classes on the element.
		if ( implied ) {
			destination.setIncludeSubclasses( false );
		}
		fromClause.addCollectionJoinFromElementByPath( path, destination );
//		origin.addDestination(destination);
		// Add the query spaces.
		fromClause.getWalker().addQuerySpaces( entityPersister.getQuerySpaces() );

		CollectionType type = queryableCollection.getCollectionType();
		String role = type.getRole();
		String roleAlias = origin.getTableAlias();

		String[] targetColumns = sfh.getCollectionElementColumns( role, roleAlias );
		AssociationType elementAssociationType = sfh.getElementAssociationType( type );

		// Create the join element under the from element.
		JoinType joinType = JoinType.INNER_JOIN;
		JoinSequence joinSequence = sfh.createJoinSequence(
				implied,
				elementAssociationType,
				tableAlias,
				joinType,
				targetColumns
		);
		elem = initializeJoin( path, destination, joinSequence, targetColumns, origin, false );
		elem.setUseFromFragment( true );    // The associated entity is implied, but it must be included in the FROM.
		elem.setCollectionTableAlias( roleAlias );    // The collection alias is the role.
		return elem;
	}
 
Example 7
Source File: Collections.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Initialize the role of the collection.
 *
 * @param collection The collection to be updated by reachibility.
 * @param type The type of the collection.
 * @param entity The owner of the collection.
 * @throws HibernateException
 */
public static void processReachableCollection(
		PersistentCollection collection,
        CollectionType type,
        Object entity,
        SessionImplementor session)
throws HibernateException {

	collection.setOwner(entity);

	CollectionEntry ce = session.getPersistenceContext().getCollectionEntry(collection);

	if ( ce == null ) {
		// refer to comment in StatefulPersistenceContext.addCollection()
		throw new HibernateException(
				"Found two representations of same collection: " +
				type.getRole()
		);
	}

	// The CollectionEntry.isReached() stuff is just to detect any silly users  
	// who set up circular or shared references between/to collections.
	if ( ce.isReached() ) {
		// We've been here before
		throw new HibernateException(
				"Found shared references to a collection: " +
				type.getRole()
		);
	}
	ce.setReached(true);

	SessionFactoryImplementor factory = session.getFactory();
	CollectionPersister persister = factory.getCollectionPersister( type.getRole() );
	ce.setCurrentPersister(persister);
	ce.setCurrentKey( type.getKeyOfOwner(entity, session) ); //TODO: better to pass the id in as an argument?

	if ( log.isDebugEnabled() ) {
		log.debug(
				"Collection found: " +
				MessageHelper.collectionInfoString( persister, ce.getCurrentKey(), factory ) +
				", was: " +
				MessageHelper.collectionInfoString( ce.getLoadedPersister(), ce.getLoadedKey(), factory ) +
				( collection.wasInitialized() ? " (initialized)" : " (uninitialized)" )
		);
	}

	prepareCollectionForUpdate( collection, ce, session.getEntityMode(), factory );

}
 
Example 8
Source File: DotNode.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void dereferenceCollection(CollectionType collectionType, boolean implicitJoin, boolean indexed, String classAlias, AST parent)
throws SemanticException {
	
	dereferenceType = DEREF_COLLECTION;
	String role = collectionType.getRole();
	
	//foo.bars.size (also handles deprecated stuff like foo.bars.maxelement for backwardness)
	boolean isSizeProperty = getNextSibling()!=null && 
		CollectionProperties.isAnyCollectionProperty( getNextSibling().getText() );

	if ( isSizeProperty ) indexed = true; //yuck!

	QueryableCollection queryableCollection = getSessionFactoryHelper().requireQueryableCollection( role );
	String propName = getPath();
	FromClause currentFromClause = getWalker().getCurrentFromClause();

	if ( getWalker().getStatementType() != SqlTokenTypes.SELECT && indexed && classAlias == null ) {
		// should indicate that we are processing an INSERT/UPDATE/DELETE
		// query with a subquery implied via a collection property
		// function. Here, we need to use the table name itself as the
		// qualification alias.
		// TODO : verify this works for all databases...
		// TODO : is this also the case in non-"indexed" scenarios?
		String alias = getLhs().getFromElement().getQueryable().getTableName();
		columns = getFromElement().toColumns( alias, propertyPath, false, true );
	}

	//We do not look for an existing join on the same path, because
	//it makes sense to join twice on the same collection role
	FromElementFactory factory = new FromElementFactory(
	        currentFromClause,
	        getLhs().getFromElement(),
	        propName,
			classAlias,
	        getColumns(),
	        implicitJoin
	);
	FromElement elem = factory.createCollection( queryableCollection, role, joinType, fetch, indexed );
	
	if ( log.isDebugEnabled() ) {
		log.debug( "dereferenceCollection() : Created new FROM element for " + propName + " : " + elem );
	}
	
	setImpliedJoin( elem );
	setFromElement( elem );	// This 'dot' expression now refers to the resulting from element.
	
	if ( isSizeProperty ) {
		elem.setText("");
		elem.setUseWhereFragment(false);
	}
	
	if ( !implicitJoin ) {
		EntityPersister entityPersister = elem.getEntityPersister();
		if ( entityPersister != null ) {
			getWalker().addQuerySpaces( entityPersister.getQuerySpaces() );
		}
	}
	getWalker().addQuerySpaces( queryableCollection.getCollectionSpaces() );	// Always add the collection's query spaces.
}
 
Example 9
Source File: FromElementFactory.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
FromElement createElementJoin(QueryableCollection queryableCollection) throws SemanticException {
		FromElement elem;

		implied = true; //TODO: always true for now, but not if we later decide to support elements() in the from clause
		inElementsFunction = true;
		Type elementType = queryableCollection.getElementType();
		if ( !elementType.isEntityType() ) {
			throw new IllegalArgumentException( "Cannot create element join for a collection of non-entities!" );
		}
		this.queryableCollection = queryableCollection;
		SessionFactoryHelper sfh = fromClause.getSessionFactoryHelper();
		FromElement destination = null;
		String tableAlias = null;
		EntityPersister entityPersister = queryableCollection.getElementPersister();
		tableAlias = fromClause.getAliasGenerator().createName( entityPersister.getEntityName() );
		String associatedEntityName = entityPersister.getEntityName();
		EntityPersister targetEntityPersister = sfh.requireClassPersister( associatedEntityName );
		// Create the FROM element for the target (the elements of the collection).
		destination = createAndAddFromElement( 
				associatedEntityName,
				classAlias,
				targetEntityPersister,
				( EntityType ) queryableCollection.getElementType(),
				tableAlias
			);
		// If the join is implied, then don't include sub-classes on the element.
		if ( implied ) {
			destination.setIncludeSubclasses( false );
		}
		fromClause.addCollectionJoinFromElementByPath( path, destination );
//		origin.addDestination(destination);
		// Add the query spaces.
		fromClause.getWalker().addQuerySpaces( entityPersister.getQuerySpaces() );

		CollectionType type = queryableCollection.getCollectionType();
		String role = type.getRole();
		String roleAlias = origin.getTableAlias();

		String[] targetColumns = sfh.getCollectionElementColumns( role, roleAlias );
		AssociationType elementAssociationType = sfh.getElementAssociationType( type );

		// Create the join element under the from element.
		int joinType = JoinFragment.INNER_JOIN;
		JoinSequence joinSequence = sfh.createJoinSequence( implied, elementAssociationType, tableAlias, joinType, targetColumns );
		elem = initializeJoin( path, destination, joinSequence, targetColumns, origin, false );
		elem.setUseFromFragment( true );	// The associated entity is implied, but it must be included in the FROM.
		elem.setCollectionTableAlias( roleAlias );	// The collection alias is the role.
		return elem;
	}