Java Code Examples for org.hibernate.type.Type

The following are top voted examples for showing how to use org.hibernate.type.Type. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: lams   File: PersistentIndexedElementHolder.java   View source code 6 votes vote down vote up
@Override
@SuppressWarnings({"deprecation", "unchecked"})
public Iterator getDeletes(CollectionPersister persister, boolean indexIsFormula) throws HibernateException {
	final Type indexType = persister.getIndexType();
	final HashMap snapshot = (HashMap) getSnapshot();
	final HashMap deletes = (HashMap) snapshot.clone();
	deletes.keySet().removeAll( ( (HashMap) getSnapshot( persister ) ).keySet() );
	final ArrayList deleteList = new ArrayList( deletes.size() );
	for ( Object o : deletes.entrySet() ) {
		final Map.Entry me = (Map.Entry) o;
		final Object object = indexIsFormula
				? me.getValue()
				: ( (XmlRepresentableType) indexType ).fromXMLString( (String) me.getKey(), persister.getFactory() );
		if ( object != null ) {
			deleteList.add( object );
		}
	}
	return deleteList.iterator();
}
 
Example 2
Project: lams   File: Cascade.java   View source code 6 votes vote down vote up
/**
 * Cascade an action to a to-one association or any type
 */
private void cascadeToOne(
		final Object parent,
		final Object child,
		final Type type,
		final CascadeStyle style,
		final Object anything,
		final boolean isCascadeDeleteEnabled) {
	final String entityName = type.isEntityType()
			? ( (EntityType) type ).getAssociatedEntityName()
			: null;
	if ( style.reallyDoCascade( action ) ) {
		//not really necessary, but good for consistency...
		eventSource.getPersistenceContext().addChildParent( child, parent );
		try {
			action.cascade( eventSource, child, entityName, anything, isCascadeDeleteEnabled );
		}
		finally {
			eventSource.getPersistenceContext().removeChildParent( child );
		}
	}
}
 
Example 3
Project: lams   File: CriteriaLoader.java   View source code 6 votes vote down vote up
@Override
protected Object[] getResultRow(Object[] row, ResultSet rs, SessionImplementor session)
		throws SQLException, HibernateException {
	final Object[] result;
	if ( translator.hasProjection() ) {
		Type[] types = translator.getProjectedTypes();
		result = new Object[types.length];
		String[] columnAliases = translator.getProjectedColumnAliases();
		for ( int i=0, pos=0; i<result.length; i++ ) {
			int numColumns = types[i].getColumnSpan( session.getFactory() );
			if ( numColumns > 1 ) {
		    	String[] typeColumnAliases = ArrayHelper.slice( columnAliases, pos, numColumns );
				result[i] = types[i].nullSafeGet(rs, typeColumnAliases, session, null);
			}
			else {
				result[i] = types[i].nullSafeGet(rs, columnAliases[pos], session, null);
			}
			pos += numColumns;
		}
	}
	else {
		result = toResultRow( row );
	}
	return result;
}
 
Example 4
Project: lams   File: AbstractCollectionPersister.java   View source code 6 votes vote down vote up
private void initCollectionPropertyMap(String aliasName, Type type, String[] columnAliases, String[] columnNames) {

		collectionPropertyColumnAliases.put( aliasName, columnAliases );
		collectionPropertyColumnNames.put( aliasName, columnNames );

		if ( type.isComponentType() ) {
			CompositeType ct = (CompositeType) type;
			String[] propertyNames = ct.getPropertyNames();
			for ( int i = 0; i < propertyNames.length; i++ ) {
				String name = propertyNames[i];
				collectionPropertyColumnAliases.put( aliasName + "." + name, columnAliases[i] );
				collectionPropertyColumnNames.put( aliasName + "." + name, columnNames[i] );
			}
		}

	}
 
Example 5
Project: lams   File: PersistentListElementHolder.java   View source code 6 votes vote down vote up
@Override
@SuppressWarnings("deprecation")
public Serializable disassemble(CollectionPersister persister) throws HibernateException {
	final Type elementType = persister.getElementType();
	final String indexNodeName = getIndexAttributeName( persister );
	final List elements =  element.elements( persister.getElementNodeName() );
	final int length = elements.size();
	final Serializable[] result = new Serializable[length];
	for ( int i=0; i<length; i++ ) {
		final Element elem = (Element) elements.get( i );
		final Object object = elementType.fromXMLNode( elem, persister.getFactory() );
		final Integer index = IntegerType.INSTANCE.fromString( getIndex( elem, indexNodeName, i ) );
		result[index] = elementType.disassemble( object, getSession(), null );
	}
	return result;
}
 
Example 6
Project: lams   File: PersistentElementHolder.java   View source code 6 votes vote down vote up
@Override
@SuppressWarnings("deprecation")
public boolean equalsSnapshot(CollectionPersister persister) throws HibernateException {
	final Type elementType = persister.getElementType();
	final ArrayList snapshot = (ArrayList) getSnapshot();
	final List elements = element.elements( persister.getElementNodeName() );
	if ( snapshot.size() != elements.size() ) {
		return false;
	}
	for ( int i=0; i<snapshot.size(); i++ ) {
		final Object old = snapshot.get( i );
		final Element elem = (Element) elements.get( i );
		final Object current = elementType.fromXMLNode( elem, persister.getFactory() );
		if ( elementType.isDirty( old, current, getSession() ) ) {
			return false;
		}
	}
	return true;
}
 
Example 7
Project: lams   File: ForeignKeys.java   View source code 6 votes vote down vote up
/**
 * Find all non-nullable references to entities that have not yet
 * been inserted in the database, where the foreign key
 * is a reference to an unsaved transient entity. .
 *
 * @param entityName - the entity name
 * @param entity - the entity instance
 * @param values - insertable properties of the object (including backrefs),
 * possibly with substitutions
 * @param isEarlyInsert - true if the entity needs to be executed as soon as possible
 * (e.g., to generate an ID)
 * @param session - the session
 *
 * @return the transient unsaved entity dependencies that are non-nullable,
 *         or null if there are none.
 */
public static NonNullableTransientDependencies findNonNullableTransientEntities(
		String entityName,
		Object entity,
		Object[] values,
		boolean isEarlyInsert,
		SessionImplementor session) {
	final Nullifier nullifier = new Nullifier( entity, false, isEarlyInsert, session );
	final EntityPersister persister = session.getEntityPersister( entityName, entity );
	final String[] propertyNames = persister.getPropertyNames();
	final Type[] types = persister.getPropertyTypes();
	final boolean[] nullability = persister.getPropertyNullability();
	final NonNullableTransientDependencies nonNullableTransientEntities = new NonNullableTransientDependencies();
	for ( int i = 0; i < types.length; i++ ) {
		collectNonNullableTransientEntities(
				nullifier,
				values[i],
				propertyNames[i],
				types[i],
				nullability[i],
				session,
				nonNullableTransientEntities
		);
	}
	return nonNullableTransientEntities.isEmpty() ? null : nonNullableTransientEntities;
}
 
Example 8
Project: lams   File: PersistentElementHolder.java   View source code 5 votes vote down vote up
@Override
@SuppressWarnings("deprecation")
public Object readFrom(ResultSet rs, CollectionPersister persister, CollectionAliases descriptor, Object owner)
		throws HibernateException, SQLException {
	final Object object = persister.readElement( rs, owner, descriptor.getSuffixedElementAliases(), getSession() );
	final Type elementType = persister.getElementType();
	final Element subElement = element.addElement( persister.getElementNodeName() );
	elementType.setToXMLNode( subElement, object, persister.getFactory() );
	return object;
}
 
Example 9
Project: lams   File: BinaryArithmeticOperatorNode.java   View source code 5 votes vote down vote up
private Type resolveDateTimeArithmeticResultType(Type lhType, Type rhType) {
	// here, we work under the following assumptions:
	//      ------------ valid cases --------------------------------------
	//      1) datetime + {something other than datetime} : always results
	//              in a datetime ( db will catch invalid conversions )
	//      2) datetime - datetime : always results in a DOUBLE
	//      3) datetime - {something other than datetime} : always results
	//              in a datetime ( db will catch invalid conversions )
	//      ------------ invalid cases ------------------------------------
	//      4) datetime + datetime
	//      5) {something other than datetime} - datetime
	//      6) datetime * {any type}
	//      7) datetime / {any type}
	//      8) {any type} / datetime
	// doing so allows us to properly handle parameters as either the left
	// or right side here in the majority of cases
	boolean lhsIsDateTime = isDateTimeType( lhType );
	boolean rhsIsDateTime = isDateTimeType( rhType );

	// handle the (assumed) valid cases:
	// #1 - the only valid datetime addition synatx is one or the other is a datetime (but not both)
	if ( getType() == HqlSqlTokenTypes.PLUS ) {
		// one or the other needs to be a datetime for us to get into this method in the first place...
		return lhsIsDateTime ? lhType : rhType;
	}
	else if ( getType() == HqlSqlTokenTypes.MINUS ) {
		// #3 - note that this is also true of "datetime - :param"...
		if ( lhsIsDateTime && !rhsIsDateTime ) {
			return lhType;
		}
		// #2
		if ( lhsIsDateTime && rhsIsDateTime ) {
			return StandardBasicTypes.DOUBLE;
		}
	}
	return null;
}
 
Example 10
Project: lams   File: AbstractQueryImpl.java   View source code 5 votes vote down vote up
@Override
public Query setParameterList(String name, Collection vals, Type type) throws HibernateException {
	if ( !parameterMetadata.getNamedParameterNames().contains( name ) ) {
		throw new IllegalArgumentException("Parameter " + name + " does not exist as a named parameter in [" + getQueryString() + "]");
	}
	namedParameterLists.put( name, new TypedValue( type, vals ) );
	return this;
}
 
Example 11
Project: lams   File: DotNode.java   View source code 5 votes vote down vote up
@Override
public Type getDataType() {
	if ( super.getDataType() == null ) {
		FromElement fromElement = getLhs().getFromElement();
		if ( fromElement == null ) {
			return null;
		}
		// If the lhs is a collection, use CollectionPropertyMapping
		Type propertyType = fromElement.getPropertyType( propertyName, propertyPath );
		LOG.debugf( "getDataType() : %s -> %s", propertyPath, propertyType );
		super.setDataType( propertyType );
	}
	return super.getDataType();
}
 
Example 12
Project: lams   File: AbstractVisitor.java   View source code 5 votes vote down vote up
/**
 * Dispatch each property value to processValue().
 *
 * @param values
 * @param types
 * @throws HibernateException
 */
void processValues(Object[] values, Type[] types) throws HibernateException {
	for ( int i=0; i<types.length; i++ ) {
		if ( includeProperty(values, i) ) {
			processValue( i, values, types );
		}
	}
}
 
Example 13
Project: lams   File: AbstractEntityPersister.java   View source code 5 votes vote down vote up
private DiscriminatorMetadata buildTypeDiscriminatorMetadata() {
	return new DiscriminatorMetadata() {
		public String getSqlFragment(String sqlQualificationAlias) {
			return toColumns( sqlQualificationAlias, ENTITY_CLASS )[0];
		}

		public Type getResolutionType() {
			return new DiscriminatorType( getDiscriminatorType(), AbstractEntityPersister.this );
		}
	};
}
 
Example 14
Project: lams   File: DefaultDeleteEventListener.java   View source code 5 votes vote down vote up
private Object[] createDeletedState(EntityPersister persister, Object[] currentState, EventSource session) {
		Type[] propTypes = persister.getPropertyTypes();
		final Object[] deletedState = new Object[propTypes.length];
//		TypeFactory.deepCopy( currentState, propTypes, persister.getPropertyUpdateability(), deletedState, session );
		boolean[] copyability = new boolean[propTypes.length];
		java.util.Arrays.fill( copyability, true );
		TypeHelper.deepCopy( currentState, propTypes, copyability, deletedState, session );
		return deletedState;
	}
 
Example 15
Project: lams   File: EntityPrinter.java   View source code 5 votes vote down vote up
public String toString(Type[] types, Object[] values) throws HibernateException {
	StringBuilder buffer = new StringBuilder();
	for ( int i=0; i<types.length; i++ ) {
		if ( types[i]!=null ) {
			buffer.append( types[i].toLoggableString( values[i], factory ) ).append( ", " );
		}
	}
	return buffer.toString();
}
 
Example 16
Project: lams   File: Any.java   View source code 5 votes vote down vote up
public Type getType() throws MappingException {
	final Type metaType = getMappings().getTypeResolver().heuristicType( metaTypeName );

	return getMappings().getTypeResolver().getTypeFactory().any(
			metaValues == null ? metaType : new MetaType( metaValues, metaType ),
			getMappings().getTypeResolver().heuristicType( identifierTypeName )
	);
}
 
Example 17
Project: lams   File: EmptyInterceptor.java   View source code 5 votes vote down vote up
@Override
public int[] findDirty(
		Object entity,
		Serializable id,
		Object[] currentState,
		Object[] previousState,
		String[] propertyNames,
		Type[] types) {
	return null;
}
 
Example 18
Project: lams   File: HibernateMappingProcessor.java   View source code 5 votes vote down vote up
private void processFilterDefinitions() {
	if ( mappingRoot().getFilterDef() == null ) {
		return;
	}

	for ( JaxbHibernateMapping.JaxbFilterDef filterDefinition : mappingRoot().getFilterDef() ) {
		final String name = filterDefinition.getName();
		final Map<String,Type> parameters = new HashMap<String, Type>();
		String condition = null;
		for ( Object o : filterDefinition.getContent() ) {
			if ( o instanceof String ) {
				// represents the condition
				if ( condition != null ) {
					// log?
				}
				condition = (String) o;
			}
			else if ( o instanceof JaxbHibernateMapping.JaxbFilterDef.JaxbFilterParam ) {
				final JaxbHibernateMapping.JaxbFilterDef.JaxbFilterParam paramElement =
						JaxbHibernateMapping.JaxbFilterDef.JaxbFilterParam.class.cast( o );
				// todo : should really delay this resolution until later to allow typedef names
				parameters.put(
						paramElement.getName(),
						metadata.getTypeResolver().heuristicType( paramElement.getType() )
				);
			}
			else {
				throw new MappingException( "Unrecognized nested filter content", origin() );
			}
		}
		if ( condition == null ) {
			condition = filterDefinition.getCondition();
		}
		metadata.addFilterDefinition( new FilterDefinition( name, condition, parameters ) );
	}
}
 
Example 19
Project: lams   File: HibernateTypeResolver.java   View source code 5 votes vote down vote up
private void resolveDiscriminatorTypeInformation(EntityDiscriminator discriminator) {
	// perform any needed type resolutions for discriminator
	Type resolvedHibernateType = determineSingularTypeFromDescriptor( discriminator.getExplicitHibernateTypeDescriptor() );
	if ( resolvedHibernateType != null ) {
		pushHibernateTypeInformationDownIfNeeded(
				discriminator.getExplicitHibernateTypeDescriptor(),
				discriminator.getBoundValue(),
				resolvedHibernateType
		);
	}
}
 
Example 20
Project: lams   File: SimpleCaseNode.java   View source code 5 votes vote down vote up
public Type getDataType() {
	final AST expression = getFirstChild();
	// option is used to hold each WHEN/ELSE in turn
	AST option = expression.getNextSibling();
	while ( option != null ) {
		final AST result;
		if ( option.getType() == HqlSqlTokenTypes.WHEN ) {
			result = option.getFirstChild().getNextSibling();
		}
		else if ( option.getType() == HqlSqlTokenTypes.ELSE ) {
			result = option.getFirstChild();
		}
		else {
			throw new QueryException(
					"Unexpected node type :" +
							ASTUtil.getTokenTypeName( HqlSqlTokenTypes.class, option.getType() ) +
							"; expecting WHEN or ELSE"
			);
		}

		if ( SqlNode.class.isInstance( result ) ) {
			final Type nodeDataType = ( (SqlNode) result ).getDataType();
			if ( nodeDataType != null ) {
				return nodeDataType;
			}
		}

		option = option.getNextSibling();
	}

	throw new QueryException( "Could not determine data type for simple case statement" );
}
 
Example 21
Project: lams   File: HibernateTypeResolver.java   View source code 5 votes vote down vote up
private Type getHeuristicType(String typeName, Properties typeParameters) {
	if ( typeName != null ) {
		try {
			return metadata.getTypeResolver().heuristicType( typeName, typeParameters );
		}
		catch (Exception ignore) {
		}
	}

	return null;
}
 
Example 22
Project: lams   File: EntityUniqueKey.java   View source code 5 votes vote down vote up
public EntityUniqueKey(
		final String entityName,
		final String uniqueKeyName,
		final Object semiResolvedKey,
		final Type keyType,
		final EntityMode entityMode,
		final SessionFactoryImplementor factory) {
	this.uniqueKeyName = uniqueKeyName;
	this.entityName = entityName;
	this.key = semiResolvedKey;
	this.keyType = keyType.getSemiResolvedType( factory );
	this.entityMode = entityMode;
	this.hashCode = generateHashCode( factory );
}
 
Example 23
Project: lams   File: QueryParameters.java   View source code 5 votes vote down vote up
public QueryParameters(
		final Type[] positionalParameterTypes,
		final Object[] positionalParameterValues,
		final LockOptions lockOptions,
		final RowSelection rowSelection,
		final boolean isReadOnlyInitialized,
		final boolean readOnly,
		final boolean cacheable,
		final String cacheRegion,
		//final boolean forceCacheRefresh,
		final String comment,
		final List<String> queryHints,
		final boolean isLookupByNaturalKey,
		final ResultTransformer transformer) {
	this(
			positionalParameterTypes,
			positionalParameterValues,
			null,
			lockOptions,
			rowSelection,
			isReadOnlyInitialized,
			readOnly,
			cacheable,
			cacheRegion,
			comment,
			queryHints,
			null,
			transformer
	);
	isNaturalKeyLookup = isLookupByNaturalKey;
}
 
Example 24
Project: lams   File: MethodNode.java   View source code 5 votes vote down vote up
private void collectionProperty(AST path, AST name) throws SemanticException {
	if ( path == null ) {
		throw new SemanticException( "Collection function " + name.getText() + " has no path!" );
	}

	SqlNode expr = (SqlNode) path;
	Type type = expr.getDataType();
	LOG.debugf( "collectionProperty() :  name=%s type=%s", name, type );

	resolveCollectionProperty( expr );
}
 
Example 25
Project: gitplex-mit   File: HibernateInterceptor.java   View source code 5 votes vote down vote up
@Override
public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames,
		Type[] types) throws CallbackException {
	boolean changed = false;
	for (PersistListener listener: listeners) {
		if (listener.onLoad(entity, id, state, propertyNames, types))
			changed = true;
	}
		
	return changed;
}
 
Example 26
Project: lams   File: AbstractQueryImpl.java   View source code 5 votes vote down vote up
protected Type determineType(int paramPosition, Object paramValue, Type defaultType) {
	Type type = parameterMetadata.getOrdinalParameterExpectedType( paramPosition + 1 );
	if ( type == null ) {
		type = defaultType;
	}
	return type;
}
 
Example 27
Project: lams   File: NamedParameterRegistration.java   View source code 5 votes vote down vote up
NamedParameterRegistration(
		ProcedureCallImpl procedureCall,
		String name,
		ParameterMode mode,
		Class<T> type,
		Type hibernateType) {
	super( procedureCall, name, mode, type, hibernateType );
}
 
Example 28
Project: lams   File: AbstractParameterRegistrationImpl.java   View source code 5 votes vote down vote up
@Override
public void setHibernateType(Type type) {
	if ( type == null ) {
		throw new IllegalArgumentException( "Type cannot be null" );
	}
	this.hibernateType = type;
	this.sqlTypes = hibernateType.sqlTypes( session().getFactory() );
}
 
Example 29
Project: lams   File: NameGenerator.java   View source code 5 votes vote down vote up
public static String[][] generateColumnNames(Type[] types, SessionFactoryImplementor f) throws MappingException {
	String[][] columnNames = new String[types.length][];
	for ( int i = 0; i < types.length; i++ ) {
		int span = types[i].getColumnSpan( f );
		columnNames[i] = new String[span];
		for ( int j = 0; j < span; j++ ) {
			columnNames[i][j] = NameGenerator.scalarName( i, j );
		}
	}
	return columnNames;
}
 
Example 30
Project: lams   File: SessionFactoryHelper.java   View source code 5 votes vote down vote up
public Type findFunctionReturnType(String functionName, SQLFunction sqlFunction, AST firstArgument) {
	// determine the type of the first argument...
	Type argumentType = null;
	if ( firstArgument != null ) {
		if ( "cast".equals( functionName ) ) {
			argumentType = sfi.getTypeResolver().heuristicType( firstArgument.getNextSibling().getText() );
		}
		else if ( SqlNode.class.isInstance( firstArgument ) ) {
			argumentType = ( (SqlNode) firstArgument ).getDataType();
		}
	}

	return sqlFunction.getReturnType( argumentType, sfi );
}
 
Example 31
Project: lams   File: PersistentBag.java   View source code 5 votes vote down vote up
private int countOccurrences(Object element, List list, Type elementType)
		throws HibernateException {
	final Iterator iter = list.iterator();
	int result = 0;
	while ( iter.hasNext() ) {
		if ( elementType.isSame( element, iter.next() ) ) {
			result++;
		}
	}
	return result;
}
 
Example 32
Project: lams   File: AbstractEntityBasedAttribute.java   View source code 5 votes vote down vote up
protected AbstractEntityBasedAttribute(
		EntityPersister source,
		SessionFactoryImplementor sessionFactory,
		int attributeNumber,
		String attributeName,
		Type attributeType,
		BaselineAttributeInformation attributeInformation) {
	super( source, sessionFactory, attributeNumber, attributeName, attributeType, attributeInformation );
}
 
Example 33
Project: lams   File: PersistentElementHolder.java   View source code 5 votes vote down vote up
@Override
@SuppressWarnings({"deprecation", "unchecked"})
public Iterator entries(CollectionPersister persister) {
	final Type elementType = persister.getElementType();
	final List subElements =  element.elements( persister.getElementNodeName() );
	final int length = subElements.size();
	final List result = new ArrayList(length);
	for ( Object subElementO : subElements ) {
		final Element subElement = (Element) subElementO;
		final Object object = elementType.fromXMLNode( subElement, persister.getFactory() );
		result.add( object );
	}
	return result.iterator();
}
 
Example 34
Project: lams   File: EntityPrinter.java   View source code 5 votes vote down vote up
/**
 * Renders an entity to a string.
 *
 * @param entityName the entity name
 * @param entity an actual entity object, not a proxy!
 * @return the entity rendered to a string
 */
public String toString(String entityName, Object entity) throws HibernateException {
	EntityPersister entityPersister = factory.getEntityPersister( entityName );

	if ( entityPersister == null ) {
		return entity.getClass().getName();
	}

	Map<String,String> result = new HashMap<String,String>();

	if ( entityPersister.hasIdentifierProperty() ) {
		result.put(
			entityPersister.getIdentifierPropertyName(),
			entityPersister.getIdentifierType().toLoggableString( entityPersister.getIdentifier( entity ), factory )
		);
	}

	Type[] types = entityPersister.getPropertyTypes();
	String[] names = entityPersister.getPropertyNames();
	Object[] values = entityPersister.getPropertyValues( entity );
	for ( int i=0; i<types.length; i++ ) {
		if ( !names[i].startsWith("_") ) {
			String strValue = values[i]==LazyPropertyInitializer.UNFETCHED_PROPERTY ?
				values[i].toString() :
				types[i].toLoggableString( values[i], factory );
			result.put( names[i], strValue );
		}
	}
	return entityName + result.toString();
}
 
Example 35
Project: lams   File: EntityMetamodel.java   View source code 5 votes vote down vote up
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 36
Project: lams   File: AbstractParameterRegistrationImpl.java   View source code 5 votes vote down vote up
protected AbstractParameterRegistrationImpl(
		ProcedureCallImpl procedureCall,
		String name,
		ParameterMode mode,
		Class<T> type,
		Type hibernateType) {
	this( procedureCall, null, name, mode, type, hibernateType );
}
 
Example 37
Project: lams   File: AbstractScrollableResults.java   View source code 5 votes vote down vote up
/**
 * Check that the requested type is compatible with the result type, and
 * return the column value.  This version makes sure the the classes
 * are "assignable".
 *
 * @param col the column
 * @param returnType any type
 */
protected final Object getNonFinal(int col, Type returnType) throws HibernateException {
	if ( holderInstantiator!=null ) {
		throw new HibernateException("query specifies a holder class");
	}

	if ( returnType.getReturnedClass().isAssignableFrom( types[col].getReturnedClass() ) ) {
		return get(col);
	}
	else {
		return throwInvalidColumnTypeException(col, types[col], returnType);
	}
}
 
Example 38
Project: lams   File: SimpleExpression.java   View source code 5 votes vote down vote up
@Override
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
	final String[] columns = criteriaQuery.findColumns( propertyName, criteria );
	final Type type = criteriaQuery.getTypeUsingProjection( criteria, propertyName );
	final StringBuilder fragment = new StringBuilder();

	if ( columns.length > 1 ) {
		fragment.append( '(' );
	}
	final SessionFactoryImplementor factory = criteriaQuery.getFactory();
	final int[] sqlTypes = type.sqlTypes( factory );
	for ( int i = 0; i < columns.length; i++ ) {
		final boolean lower = ignoreCase && (sqlTypes[i] == Types.VARCHAR || sqlTypes[i] == Types.CHAR);
		if ( lower ) {
			fragment.append( factory.getDialect().getLowercaseFunction() ).append( '(' );
		}
		fragment.append( columns[i] );
		if ( lower ) {
			fragment.append( ')' );
		}

		fragment.append( getOp() ).append( "?" );
		if ( i < columns.length - 1 ) {
			fragment.append( " and " );
		}
	}
	if ( columns.length > 1 ) {
		fragment.append( ')' );
	}
	return fragment.toString();
}
 
Example 39
Project: lams   File: AbstractLoadPlanBuildingAssociationVisitationStrategy.java   View source code 5 votes vote down vote up
@Override
public void startingCollectionElements(CollectionElementDefinition elementDefinition) {
	final Type elementType = elementDefinition.getType();
	log.tracef(
			"%s Starting collection element graph : %s",
			StringHelper.repeat( ">>", fetchSourceStack.size() ),
			elementDefinition.getCollectionDefinition().getCollectionPersister().getRole()
	);

	final CollectionReference collectionReference = currentCollection();
	final CollectionFetchableElement elementGraph = collectionReference.getElementGraph();

	if ( elementType.isAssociationType() || elementType.isComponentType() ) {
		if ( elementGraph == null ) {
			throw new IllegalStateException(
					"CollectionReference did not return an expected element graph : " +
							elementDefinition.getCollectionDefinition().getCollectionPersister().getRole()
			);
		}
		if ( !elementType.isAnyType() ) {
			pushToStack( (ExpandingFetchSource) elementGraph );
		}
	}
	else {
		if ( elementGraph != null ) {
			throw new IllegalStateException(
					"CollectionReference returned an unexpected element graph : " +
							elementDefinition.getCollectionDefinition().getCollectionPersister().getRole()
			);
		}
	}
}
 
Example 40
Project: lams   File: CriteriaQueryTranslator.java   View source code 5 votes vote down vote up
@Override
public Type getTypeUsingProjection(Criteria subcriteria, String propertyName)
		throws HibernateException {

	//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];
	}
}