FileDocCategorySizeDatePackage
CriteriaQueryTranslator.javaAPI DocHibernate 3.2.517885Thu Mar 16 07:14:48 GMT 2006org.hibernate.loader.criteria

CriteriaQueryTranslator

public class CriteriaQueryTranslator extends Object implements org.hibernate.criterion.CriteriaQuery
author
Gavin King

Fields Summary
public static final String
ROOT_SQL_ALIAS
private org.hibernate.criterion.CriteriaQuery
outerQueryTranslator
private final org.hibernate.impl.CriteriaImpl
rootCriteria
private final String
rootEntityName
private final String
rootSQLAlias
private int
aliasCount
private final Map
criteriaEntityNames
private final Map
criteriaSQLAliasMap
private final Map
aliasCriteriaMap
private final Map
associationPathCriteriaMap
private final Map
associationPathJoinTypesMap
private final org.hibernate.engine.SessionFactoryImplementor
sessionFactory
Constructors Summary
public CriteriaQueryTranslator(org.hibernate.engine.SessionFactoryImplementor factory, org.hibernate.impl.CriteriaImpl criteria, String rootEntityName, String rootSQLAlias, org.hibernate.criterion.CriteriaQuery outerQuery)


	 
			  
	          
	          
	          
	            
		this( factory, criteria, rootEntityName, rootSQLAlias );
		outerQueryTranslator = outerQuery;
	
public CriteriaQueryTranslator(org.hibernate.engine.SessionFactoryImplementor factory, org.hibernate.impl.CriteriaImpl criteria, String rootEntityName, String rootSQLAlias)

		this.rootCriteria = criteria;
		this.rootEntityName = rootEntityName;
		this.sessionFactory = factory;
		this.rootSQLAlias = rootSQLAlias;
		createAliasCriteriaMap();
		createAssociationPathCriteriaMap();
		createCriteriaEntityNameMap();
		createCriteriaSQLAliasMap();
	
Methods Summary
private voidcreateAliasCriteriaMap()

		aliasCriteriaMap.put( rootCriteria.getAlias(), rootCriteria );
		Iterator iter = rootCriteria.iterateSubcriteria();
		while ( iter.hasNext() ) {
			Criteria subcriteria = ( Criteria ) iter.next();
			if ( subcriteria.getAlias() != null ) {
				Object old = aliasCriteriaMap.put( subcriteria.getAlias(), subcriteria );
				if ( old != null ) {
					throw new QueryException( "duplicate alias: " + subcriteria.getAlias() );
				}
			}
		}
	
private voidcreateAssociationPathCriteriaMap()

		Iterator iter = rootCriteria.iterateSubcriteria();
		while ( iter.hasNext() ) {
			CriteriaImpl.Subcriteria crit = ( CriteriaImpl.Subcriteria ) iter.next();
			String wholeAssociationPath = getWholeAssociationPath( crit );
			Object old = associationPathCriteriaMap.put( wholeAssociationPath, crit );
			if ( old != null ) {
				throw new QueryException( "duplicate association path: " + wholeAssociationPath );
			}
			int joinType = crit.getJoinType();
			old = associationPathJoinTypesMap.put( wholeAssociationPath, new Integer( joinType ) );
			if ( old != null ) {
				// TODO : not so sure this is needed...
				throw new QueryException( "duplicate association path: " + wholeAssociationPath );
			}
		}
	
private voidcreateCriteriaEntityNameMap()

		criteriaEntityNames.put( rootCriteria, rootEntityName );
		Iterator iter = associationPathCriteriaMap.entrySet().iterator();
		while ( iter.hasNext() ) {
			Map.Entry me = ( Map.Entry ) iter.next();
			criteriaEntityNames.put(
					me.getValue(), //the criteria instance
			        getPathEntityName( ( String ) me.getKey() )
			);
		}
	
private voidcreateCriteriaSQLAliasMap()

		int i = 0;
		Iterator criteriaIterator = criteriaEntityNames.entrySet().iterator();
		while ( criteriaIterator.hasNext() ) {
			Map.Entry me = ( Map.Entry ) criteriaIterator.next();
			Criteria crit = ( Criteria ) me.getKey();
			String alias = crit.getAlias();
			if ( alias == null ) {
				alias = ( String ) me.getValue(); // the entity name
			}
			criteriaSQLAliasMap.put( crit, StringHelper.generateAlias( alias, i++ ) );
		}
		criteriaSQLAliasMap.put( rootCriteria, rootSQLAlias );
	
public java.lang.StringgenerateSQLAlias()

		return StringHelper.generateAlias( Criteria.ROOT_ALIAS, aliasCount ) + '_";
	
private org.hibernate.CriteriagetAliasedCriteria(java.lang.String alias)

		return ( Criteria ) aliasCriteriaMap.get( alias );
	
public java.lang.StringgetColumn(org.hibernate.Criteria criteria, java.lang.String propertyName)

		String[] cols = getColumns( propertyName, criteria );
		if ( cols.length != 1 ) {
			throw new QueryException( "property does not map to a single column: " + propertyName );
		}
		return cols[0];
	
private java.lang.String[]getColumns(java.lang.String propertyName, org.hibernate.Criteria subcriteria)

		return getPropertyMapping( getEntityName( subcriteria, propertyName ) )
				.toColumns(
						getSQLAlias( subcriteria, propertyName ),
				        getPropertyName( propertyName )
				);
	
public java.lang.String[]getColumnsUsingProjection(org.hibernate.Criteria subcriteria, java.lang.String propertyName)
Get the names of the columns constrained by this criterion.


		//first look for a reference to a projection alias
		final Projection projection = rootCriteria.getProjection();
		String[] projectionColumns = projection == null ?
		                             null :
		                             projection.getColumnAliases( propertyName, 0 );

		if ( projectionColumns == null ) {
			//it does not refer to an alias of a projection,
			//look for a property
			try {
				return getColumns( propertyName, subcriteria );
			}
			catch ( HibernateException he ) {
				//not found in inner query , try the outer query
				if ( outerQueryTranslator != null ) {
					return outerQueryTranslator.getColumnsUsingProjection( subcriteria, propertyName );
				}
				else {
					throw he;
				}
			}
		}
		else {
			//it refers to an alias of a projection
			return projectionColumns;
		}
	
public org.hibernate.CriteriagetCriteria(java.lang.String path)

		return ( Criteria ) associationPathCriteriaMap.get( path );
	
public java.lang.StringgetEntityName(org.hibernate.Criteria criteria)

		return ( String ) criteriaEntityNames.get( criteria );
	
public java.lang.StringgetEntityName(org.hibernate.Criteria subcriteria, java.lang.String propertyName)

		if ( propertyName.indexOf( '." ) > 0 ) {
			String root = StringHelper.root( propertyName );
			Criteria crit = getAliasedCriteria( root );
			if ( crit != null ) {
				return getEntityName( crit );
			}
		}
		return getEntityName( subcriteria );
	
public org.hibernate.engine.SessionFactoryImplementorgetFactory()

		return sessionFactory;
	
public java.lang.StringgetGroupBy()

		if ( rootCriteria.getProjection().isGrouped() ) {
			return rootCriteria.getProjection()
					.toGroupSqlString( rootCriteria.getProjectionCriteria(), this );
		}
		else {
			return "";
		}
	
public java.lang.String[]getIdentifierColumns(org.hibernate.Criteria subcriteria)

		String[] idcols =
				( ( Loadable ) getPropertyMapping( getEntityName( subcriteria ) ) ).getIdentifierColumnNames();
		return StringHelper.qualify( getSQLAlias( subcriteria ), idcols );
	
public org.hibernate.type.TypegetIdentifierType(org.hibernate.Criteria subcriteria)

		return ( ( Loadable ) getPropertyMapping( getEntityName( subcriteria ) ) ).getIdentifierType();
	
public intgetJoinType(java.lang.String path)

		Integer result = ( Integer ) associationPathJoinTypesMap.get( path );
		return ( result == null ? Criteria.INNER_JOIN : result.intValue() );
	
public java.lang.StringgetOrderBy()

		StringBuffer orderBy = new StringBuffer( 30 );
		Iterator criterionIterator = rootCriteria.iterateOrderings();
		while ( criterionIterator.hasNext() ) {
			CriteriaImpl.OrderEntry oe = ( CriteriaImpl.OrderEntry ) criterionIterator.next();
			orderBy.append( oe.getOrder().toSqlString( oe.getCriteria(), this ) );
			if ( criterionIterator.hasNext() ) {
				orderBy.append( ", " );
			}
		}
		return orderBy.toString();
	
private java.lang.StringgetPathEntityName(java.lang.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();
	
public java.lang.String[]getProjectedAliases()

		return rootCriteria.getProjection().getAliases();
	
public java.lang.String[]getProjectedColumnAliases()

		return rootCriteria.getProjection().getColumnAliases( 0 );
	
public org.hibernate.type.Type[]getProjectedTypes()

		return rootCriteria.getProjection().getTypes( rootCriteria, this );
	
private org.hibernate.persister.entity.PropertyMappinggetPropertyMapping(java.lang.String entityName)

		return ( PropertyMapping ) sessionFactory.getEntityPersister( entityName );
	
public java.lang.StringgetPropertyName(java.lang.String propertyName)

		if ( propertyName.indexOf( '." ) > 0 ) {
			String root = StringHelper.root( propertyName );
			Criteria crit = getAliasedCriteria( root );
			if ( crit != null ) {
				return propertyName.substring( root.length() + 1 );
			}
		}
		return propertyName;
	
public org.hibernate.engine.QueryParametersgetQueryParameters()

		List values = new ArrayList();
		List types = new ArrayList();
		Iterator iter = rootCriteria.iterateExpressionEntries();
		while ( iter.hasNext() ) {
			CriteriaImpl.CriterionEntry ce = ( CriteriaImpl.CriterionEntry ) iter.next();
			TypedValue[] tv = ce.getCriterion().getTypedValues( ce.getCriteria(), this );
			for ( int i = 0; i < tv.length; i++ ) {
				values.add( tv[i].getValue() );
				types.add( tv[i].getType() );
			}
		}
		Object[] valueArray = values.toArray();
		Type[] typeArray = ArrayHelper.toTypeArray( types );

		RowSelection selection = new RowSelection();
		selection.setFirstRow( rootCriteria.getFirstResult() );
		selection.setMaxRows( rootCriteria.getMaxResults() );
		selection.setTimeout( rootCriteria.getTimeout() );
		selection.setFetchSize( rootCriteria.getFetchSize() );

		Map lockModes = new HashMap();
		iter = rootCriteria.getLockModes().entrySet().iterator();
		while ( iter.hasNext() ) {
			Map.Entry me = ( Map.Entry ) iter.next();
			final Criteria subcriteria = getAliasedCriteria( ( String ) me.getKey() );
			lockModes.put( getSQLAlias( subcriteria ), me.getValue() );
		}
		iter = rootCriteria.iterateSubcriteria();
		while ( iter.hasNext() ) {
			CriteriaImpl.Subcriteria subcriteria = ( CriteriaImpl.Subcriteria ) iter.next();
			LockMode lm = subcriteria.getLockMode();
			if ( lm != null ) {
				lockModes.put( getSQLAlias( subcriteria ), lm );
			}
		}

		return new QueryParameters(
				typeArray,
		        valueArray,
		        lockModes,
		        selection,
		        rootCriteria.getCacheable(),
		        rootCriteria.getCacheRegion(),
		        rootCriteria.getComment(),
		        rootCriteria.isLookupByNaturalKey(),
		        rootCriteria.getResultTransformer()
		);
	
public java.util.SetgetQuerySpaces()

		Set result = new HashSet();
		Iterator iter = criteriaEntityNames.values().iterator();
		while ( iter.hasNext() ) {
			String entityName = ( String ) iter.next();
			result.addAll( Arrays.asList( getFactory().getEntityPersister( entityName ).getQuerySpaces() ) );
		}
		return result;
	
public org.hibernate.impl.CriteriaImplgetRootCriteria()

		return rootCriteria;
	
public java.lang.StringgetRootSQLALias()

		return rootSQLAlias;
	
public java.lang.StringgetSQLAlias(org.hibernate.Criteria criteria)

		return ( String ) criteriaSQLAliasMap.get( criteria );
	
public java.lang.StringgetSQLAlias(org.hibernate.Criteria criteria, java.lang.String propertyName)

		if ( propertyName.indexOf( '." ) > 0 ) {
			String root = StringHelper.root( propertyName );
			Criteria subcriteria = getAliasedCriteria( root );
			if ( subcriteria != null ) {
				return getSQLAlias( subcriteria );
			}
		}
		return getSQLAlias( criteria );
	
public intgetSQLAliasCount()

		return criteriaSQLAliasMap.size();
	
public java.lang.StringgetSelect()

		return rootCriteria.getProjection().toSqlString(
				rootCriteria.getProjectionCriteria(),
		        0,
		        this
		);
	
public org.hibernate.type.TypegetType(org.hibernate.Criteria subcriteria, java.lang.String propertyName)

		return getPropertyMapping( getEntityName( subcriteria, propertyName ) )
				.toType( getPropertyName( propertyName ) );
	
public org.hibernate.type.TypegetTypeUsingProjection(org.hibernate.Criteria subcriteria, java.lang.String propertyName)


		//first look for a reference to a projection alias
		final Projection projection = rootCriteria.getProjection();
		Type[] projectionTypes = projection == null ?
		                         null :
		                         projection.getTypes( propertyName, subcriteria, this );

		if ( projectionTypes == null ) {
			try {
				//it does not refer to an alias of a projection,
				//look for a property
				return getType( subcriteria, propertyName );
			}
			catch ( HibernateException he ) {
				//not found in inner query , try the outer query
				if ( outerQueryTranslator != null ) {
					return outerQueryTranslator.getType( subcriteria, propertyName );
				}
				else {
					throw he;
				}
			}
		}
		else {
			if ( projectionTypes.length != 1 ) {
				//should never happen, i think
				throw new QueryException( "not a single-length projection: " + propertyName );
			}
			return projectionTypes[0];
		}
	
public org.hibernate.engine.TypedValuegetTypedIdentifierValue(org.hibernate.Criteria subcriteria, java.lang.Object value)

		final Loadable loadable = ( Loadable ) getPropertyMapping( getEntityName( subcriteria ) );
		return new TypedValue(
				loadable.getIdentifierType(),
		        value,
		        EntityMode.POJO
		);
	
public org.hibernate.engine.TypedValuegetTypedValue(org.hibernate.Criteria subcriteria, java.lang.String propertyName, java.lang.Object value)
Get the a typed value for the given property value.

		// Detect discriminator values...
		if ( value instanceof Class ) {
			Class entityClass = ( Class ) value;
			Queryable q = SessionFactoryHelper.findQueryableUsingImports( sessionFactory, entityClass.getName() );
			if ( q != null ) {
				Type type = q.getDiscriminatorType();
				String stringValue = q.getDiscriminatorSQLValue();
				// Convert the string value into the proper type.
				if ( type instanceof NullableType ) {
					NullableType nullableType = ( NullableType ) type;
					value = nullableType.fromStringValue( stringValue );
				}
				else {
					throw new QueryException( "Unsupported discriminator type " + type );
				}
				return new TypedValue(
						type,
				        value,
				        EntityMode.POJO
				);
			}
		}
		// Otherwise, this is an ordinary value.
		return new TypedValue(
				getTypeUsingProjection( subcriteria, propertyName ),
		        value,
		        EntityMode.POJO
		);
	
public java.lang.StringgetWhereCondition()

		StringBuffer condition = new StringBuffer( 30 );
		Iterator criterionIterator = rootCriteria.iterateExpressionEntries();
		while ( criterionIterator.hasNext() ) {
			CriteriaImpl.CriterionEntry entry = ( CriteriaImpl.CriterionEntry ) criterionIterator.next();
			String sqlString = entry.getCriterion().toSqlString( entry.getCriteria(), this );
			condition.append( sqlString );
			if ( criterionIterator.hasNext() ) {
				condition.append( " and " );
			}
		}
		return condition.toString();
	
private java.lang.StringgetWholeAssociationPath(CriteriaImpl.Subcriteria subcriteria)

		String path = subcriteria.getPath();

		// some messy, complex stuff here, since createCriteria() can take an
		// aliased path, or a path rooted at the creating criteria instance
		Criteria parent = null;
		if ( path.indexOf( '." ) > 0 ) {
			// if it is a compound path
			String testAlias = StringHelper.root( path );
			if ( !testAlias.equals( subcriteria.getAlias() ) ) {
				// and the qualifier is not the alias of this criteria
				//      -> check to see if we belong to some criteria other
				//          than the one that created us
				parent = ( Criteria ) aliasCriteriaMap.get( testAlias );
			}
		}
		if ( parent == null ) {
			// otherwise assume the parent is the the criteria that created us
			parent = subcriteria.getParent();
		}
		else {
			path = StringHelper.unroot( path );
		}

		if ( parent.equals( rootCriteria ) ) {
			// if its the root criteria, we are done
			return path;
		}
		else {
			// otherwise, recurse
			return getWholeAssociationPath( ( CriteriaImpl.Subcriteria ) parent ) + '." + path;
		}
	
public booleanhasProjection()

		return rootCriteria.getProjection() != null;
	
public booleanisJoin(java.lang.String path)

		return associationPathCriteriaMap.containsKey( path );