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

The following examples show how to use org.hibernate.type.Type#getReturnedClass() . 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: MultipleHiLoPerTableGenerator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings({"StatementWithEmptyBody", "deprecation"})
public void configure(Type type, Properties params, ServiceRegistry serviceRegistry) throws MappingException {
	returnClass = type.getReturnedClass();

	final JdbcEnvironment jdbcEnvironment = serviceRegistry.getService( JdbcEnvironment.class );

	qualifiedTableName = determineGeneratorTableName( params, jdbcEnvironment );

	segmentColumnName = determineSegmentColumnName( params, jdbcEnvironment );
	keySize = ConfigurationHelper.getInt( PK_LENGTH_NAME, params, DEFAULT_PK_LENGTH );
	segmentName = ConfigurationHelper.getString( PK_VALUE_NAME, params, params.getProperty( TABLE ) );

	valueColumnName = determineValueColumnName( params, jdbcEnvironment );

	//hilo config
	maxLo = ConfigurationHelper.getInt( MAX_LO, params, Short.MAX_VALUE );

	if ( maxLo >= 1 ) {
		hiloOptimizer = new LegacyHiLoAlgorithmOptimizer( returnClass, maxLo );
	}
}
 
Example 2
Source File: AbstractScrollableResults.java    From lams with GNU General Public License v2.0 6 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 identical.
 *
 * @param col the column
 * @param returnType a "final" type
 */
protected final Object getFinal(int col, Type returnType) throws HibernateException {
	if ( closed ) {
		throw new IllegalStateException( "ScrollableResults is closed" );
	}

	if ( holderInstantiator != null ) {
		throw new HibernateException( "query specifies a holder class" );
	}

	if ( returnType.getReturnedClass() == types[col].getReturnedClass() ) {
		return get( col );
	}
	else {
		return throwInvalidColumnTypeException( col, types[col], returnType );
	}
}
 
Example 3
Source File: IdentifierGeneratorFactory.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static Serializable get(ResultSet rs, Type type) 
throws SQLException, IdentifierGenerationException {

	Class clazz = type.getReturnedClass();
	if ( clazz==Long.class ) {
		return new Long( rs.getLong(1) );
	}
	else if ( clazz==Integer.class ) {
		return new Integer( rs.getInt(1) );
	}
	else if ( clazz==Short.class ) {
		return new Short( rs.getShort(1) );
	}
	else if ( clazz==String.class ) {
		return rs.getString(1);
	}
	else {
		throw new IdentifierGenerationException("this id generator generates long, integer, short or string");
	}
	
}
 
Example 4
Source File: QueryParameterBindingValidator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public <P> void validate(Type paramType, Object bind, TemporalType temporalType) {
	if ( bind == null || paramType == null ) {
		// nothing we can check
		return;
	}
	final Class parameterType = paramType.getReturnedClass();
	if ( parameterType == null ) {
		// nothing we can check
		return;
	}

	if ( Collection.class.isInstance( bind ) && !Collection.class.isAssignableFrom( parameterType ) ) {
		// we have a collection passed in where we are expecting a non-collection.
		// 		NOTE : this can happen in Hibernate's notion of "parameter list" binding
		// 		NOTE2 : the case of a collection value and an expected collection (if that can even happen)
		//			will fall through to the main check.
		validateCollectionValuedParameterBinding( parameterType, (Collection) bind, temporalType );
	}
	else if ( bind.getClass().isArray() ) {
		validateArrayValuedParameterBinding( parameterType, bind, temporalType );
	}
	else {
		if ( !isValidBindValue( parameterType, bind, temporalType ) ) {
			throw new IllegalArgumentException(
					String.format(
							"Parameter value [%s] did not match expected type [%s (%s)]",
							bind,
							parameterType.getName(),
							extractName( temporalType )
					)
			);
		}
	}
}
 
Example 5
Source File: SequenceStyleGenerator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected DatabaseStructure buildSequenceStructure(
		Type type,
		Properties params,
		JdbcEnvironment jdbcEnvironment,
		QualifiedName sequenceName,
		int initialValue,
		int incrementSize) {
	return new SequenceStructure( jdbcEnvironment, sequenceName, initialValue, incrementSize, type.getReturnedClass() );
}
 
Example 6
Source File: SequenceStyleGenerator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("WeakerAccess")
protected DatabaseStructure buildTableStructure(
		Type type,
		Properties params,
		JdbcEnvironment jdbcEnvironment,
		QualifiedName sequenceName,
		int initialValue,
		int incrementSize) {
	final Identifier valueColumnName = determineValueColumnName( params, jdbcEnvironment );
	return new TableStructure( jdbcEnvironment, sequenceName, valueColumnName, initialValue, incrementSize, type.getReturnedClass() );
}
 
Example 7
Source File: IgniteCacheInitializer.java    From hibernate-ogm-ignite with GNU Lesser General Public License v2.1 5 votes vote down vote up
private String fieldType(Column currentColumn) {
	Value value = currentColumn.getValue();
	Type type = value.getType();
	while ( type.isEntityType() || type.isComponentType() ) {
		if ( type.isEntityType() ) {
			type = ( (SimpleValue) value ).getMetadata().getIdentifierType( type.getName() );
		}
		if ( type.isComponentType() ) {
			int i = 0;
			boolean columnFound = false;
			// search which nested property is mapped to the given column
			for ( Iterator<Selectable> ci = value.getColumnIterator(); ci.hasNext(); ++i ) {
				if ( currentColumn.getName().equals( ci.next().getText() ) ) {
					type = ( (ComponentType) type ).getSubtypes()[i];
					columnFound = true;
					break;
				}
			}
			if ( !columnFound ) {
				throw new IllegalArgumentException( "Cannot determine type for column " + currentColumn );
			}
		}
	}
	GridType gridType = serviceRegistry.getService( TypeTranslator.class ).getType( type );
	if ( gridType instanceof EnumType ) {
		return enumFieldType( (EnumType) gridType );
	}
	if ( gridType instanceof YesNoType ) {
		return STRING_CLASS_NAME;
	}
	if ( gridType instanceof NumericBooleanType ) {
		return INTEGER_CLASS_NAME;
	}
	Class<?> returnedClass = type.getReturnedClass();
	if ( Character.class.equals( returnedClass ) ) {
		return STRING_CLASS_NAME;
	}
	return returnedClass.getName();
}
 
Example 8
Source File: IncrementGenerator.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void configure(Type type, Properties params, Dialect dialect)
throws MappingException {

	String tableList = params.getProperty("tables");
	if (tableList==null) tableList = params.getProperty(PersistentIdentifierGenerator.TABLES);
	String[] tables = StringHelper.split(", ", tableList);
	String column = params.getProperty("column");
	if (column==null) column = params.getProperty(PersistentIdentifierGenerator.PK);
	String schema = params.getProperty(PersistentIdentifierGenerator.SCHEMA);
	String catalog = params.getProperty(PersistentIdentifierGenerator.CATALOG);
	returnClass = type.getReturnedClass();
	

	StringBuffer buf = new StringBuffer();
	for ( int i=0; i<tables.length; i++ ) {
		if (tables.length>1) {
			buf.append("select ").append(column).append(" from ");
		}
		buf.append( Table.qualify( catalog, schema, tables[i] ) );
		if ( i<tables.length-1) buf.append(" union ");
	}
	if (tables.length>1) {
		buf.insert(0, "( ").append(" ) ids_");
		column = "ids_." + column;
	}
	
	sql = "select max(" + column + ") from " + buf.toString();
}
 
Example 9
Source File: AbstractScrollableResults.java    From cacheonix-core with GNU Lesser General Public License v2.1 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 identical.
 *
 * @param col the column
 * @param returnType a "final" type
 */
protected final Object getFinal(int col, Type returnType) throws HibernateException {
	if ( holderInstantiator!=null ) {
		throw new HibernateException("query specifies a holder class");
	}
	
	if ( returnType.getReturnedClass()==types[col].getReturnedClass() ) {
		return get(col);
	}
	else {
		return throwInvalidColumnTypeException(col, types[col], returnType);
	}
}
 
Example 10
Source File: HibernateMetadataExtractor.java    From mPaaS with Apache License 2.0 4 votes vote down vote up
/**
 * 根据Hbm的配置构造数据字典字段
 */
private void fillProperty(Class<?> clazz, MetaEntityImpl entity,
                          Property attr) throws Exception {
    // 读取或创建字段
    MetaPropertyImpl prop = (MetaPropertyImpl) entity
            .getProperty(attr.getName());
    if (prop == null) {
        prop = new MetaPropertyImpl();
        prop.setName(attr.getName());
        entity.getProperties().put(attr.getName(), prop);
    }

    Type type;
    Value value = attr.getValue();
    if (value instanceof org.hibernate.mapping.Collection) {
        prop.setCollection(true);
        prop.setMappedBy(((org.hibernate.mapping.Collection) value).getMappedByProperty());
        type = ((org.hibernate.mapping.Collection) value).getElement().getType();
    } else {
        type = value.getType();
    }
    Class<?> javaType = type.getReturnedClass();
    if (javaType != null && IEnum.class.isAssignableFrom(javaType)) {
        // 枚举信息
        fillPropEnumList(prop, javaType);
        Class<?> valueClass = ReflectUtil.getActualClass(javaType,
                IEnum.class, "V");
        prop.setType(valueClass.getSimpleName());
    } else {
        prop.setType(formatHbmType(type));
    }
    // 级联、延迟加载、非空
    prop.setCascade(attr.getCascade());
    if (value instanceof Fetchable) {
        prop.setLazy(((Fetchable) value).isLazy());
    } else {
        prop.setLazy(attr.isLazy());
    }
    prop.setNotNull(prop.isNotNull() || !value.isNullable());
    // 长度精度
    Iterator<Selectable> columns = value.getColumnIterator();
    if (columns.hasNext()) {
        Selectable selectable = columns.next();
        if (selectable instanceof Column) {
            Column column = (Column) selectable;
            if (TYPE_STRING.equals(prop.getType())) {
                prop.setLength(column.getLength());
            } else if (MetaConstant.isNumber(prop.getType())) {
                prop.setPrecision(column.getPrecision());
                prop.setScale(column.getScale());
            }
        }
    }
    // 处理动态
    if (DynamicPropertyAccessStrategy.class.getName()
            .equals(attr.getPropertyAccessorName())
            && BeanUtils.getPropertyDescriptor(clazz,
            prop.getName()) == null) {
        prop.setDynamic(true);
    }
}
 
Example 11
Source File: BindingTypeHelper.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public BasicType determineTypeForTemporalType(TemporalType temporalType, Type baseType, Object bindValue) {
	// todo : for 6.0 make TemporalType part of org.hibernate.type.descriptor.java.JdbcRecommendedSqlTypeMappingContext
	//		then we can just ask the org.hibernate.type.basic.BasicTypeFactory to handle this based on its registry
	//
	//   - or for 6.0 make TemporalType part of the state for those BasicType impls dealing with date/time types
	//
	// 	 - or for 6.0 make TemporalType part of Binder contract
	//
	//   - or add a org.hibernate.type.TemporalType#getVariant(TemporalType)
	//
	//	 - or ...

	// todo : (5.2) review Java type handling for sanity.  This part was done quickly ;)

	final Class javaType;

	// Determine the "value java type" :
	// 		prefer to leverage the bindValue java type (if bindValue not null),
	// 		followed by the java type reported by the baseType,
	// 		fallback to java.sql.Timestamp

	if ( bindValue != null ) {
		javaType = bindValue.getClass();
	}
	else if ( baseType != null ) {
		javaType = baseType.getReturnedClass();
	}
	else {
		javaType = java.sql.Timestamp.class;
	}

	switch ( temporalType ) {
		case TIMESTAMP: {
			return resolveTimestampTemporalTypeVariant( javaType, baseType );
		}
		case DATE: {
			return resolveDateTemporalTypeVariant( javaType, baseType );
		}
		case TIME: {
			return resolveTimeTemporalTypeVariant( javaType, baseType );
		}
		default: {
			throw new IllegalArgumentException( "Unexpected TemporalType [" + temporalType + "]; expecting TIMESTAMP, DATE or TIME" );
		}
	}
}
 
Example 12
Source File: IncrementGenerator.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void configure(Type type, Properties params, ServiceRegistry serviceRegistry) throws MappingException {
	returnClass = type.getReturnedClass();

	final JdbcEnvironment jdbcEnvironment = serviceRegistry.getService( JdbcEnvironment.class );
	final ObjectNameNormalizer normalizer =
			(ObjectNameNormalizer) params.get( PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER );

	String column = params.getProperty( "column" );
	if ( column == null ) {
		column = params.getProperty( PersistentIdentifierGenerator.PK );
	}
	column = normalizer.normalizeIdentifierQuoting( column ).render( jdbcEnvironment.getDialect() );

	String tableList = params.getProperty( "tables" );
	if ( tableList == null ) {
		tableList = params.getProperty( PersistentIdentifierGenerator.TABLES );
	}
	String[] tables = StringHelper.split( ", ", tableList );

	final String schema = normalizer.toDatabaseIdentifierText(
			params.getProperty( PersistentIdentifierGenerator.SCHEMA )
	);
	final String catalog = normalizer.toDatabaseIdentifierText(
			params.getProperty( PersistentIdentifierGenerator.CATALOG )
	);

	StringBuilder buf = new StringBuilder();
	for ( int i = 0; i < tables.length; i++ ) {
		final String tableName = normalizer.toDatabaseIdentifierText( tables[i] );
		if ( tables.length > 1 ) {
			buf.append( "select max(" ).append( column ).append( ") as mx from " );
		}
		buf.append( Table.qualify( catalog, schema, tableName ) );
		if ( i < tables.length - 1 ) {
			buf.append( " union " );
		}
	}
	if ( tables.length > 1 ) {
		buf.insert( 0, "( " ).append( " ) ids_" );
		column = "ids_.mx";
	}

	sql = "select max(" + column + ") from " + buf.toString();
}
 
Example 13
Source File: AbstractSharedSessionContract.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings({"unchecked", "WeakerAccess", "StatementWithEmptyBody"})
protected void resultClassChecking(Class resultClass, org.hibernate.Query hqlQuery) {
	// make sure the query is a select -> HHH-7192
	final HQLQueryPlan queryPlan = getFactory().getQueryPlanCache().getHQLQueryPlan(
			hqlQuery.getQueryString(),
			false,
			getLoadQueryInfluencers().getEnabledFilters()
	);
	if ( queryPlan.getTranslators()[0].isManipulationStatement() ) {
		throw new IllegalArgumentException( "Update/delete queries cannot be typed" );
	}

	// do some return type validation checking
	if ( Object[].class.equals( resultClass ) ) {
		// no validation needed
	}
	else if ( Tuple.class.equals( resultClass ) ) {
		TupleBuilderTransformer tupleTransformer = new TupleBuilderTransformer( hqlQuery );
		hqlQuery.setResultTransformer( tupleTransformer  );
	}
	else {
		final Class dynamicInstantiationClass = queryPlan.getDynamicInstantiationResultType();
		if ( dynamicInstantiationClass != null ) {
			if ( ! resultClass.isAssignableFrom( dynamicInstantiationClass ) ) {
				throw new IllegalArgumentException(
						"Mismatch in requested result type [" + resultClass.getName() +
								"] and actual result type [" + dynamicInstantiationClass.getName() + "]"
				);
			}
		}
		else if ( queryPlan.getTranslators()[0].getReturnTypes().length == 1 ) {
			// if we have only a single return expression, its java type should match with the requested type
			final Type queryResultType = queryPlan.getTranslators()[0].getReturnTypes()[0];
			if ( !resultClass.isAssignableFrom( queryResultType.getReturnedClass() ) ) {
				throw new IllegalArgumentException(
						"Type specified for TypedQuery [" +
								resultClass.getName() +
								"] is incompatible with query return type [" +
								queryResultType.getReturnedClass() + "]"
				);
			}
		}
		else {
			throw new IllegalArgumentException(
					"Cannot create TypedQuery for query with more than one return using requested result type [" +
							resultClass.getName() + "]"
			);
		}
	}
}
 
Example 14
Source File: MultipleHiLoPerTableGenerator.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void configure(Type type, Properties params, Dialect dialect) throws MappingException {
	tableName = PropertiesHelper.getString(ID_TABLE, params, DEFAULT_TABLE);
	pkColumnName = PropertiesHelper.getString(PK_COLUMN_NAME, params, DEFAULT_PK_COLUMN);
	valueColumnName = PropertiesHelper.getString(VALUE_COLUMN_NAME, params, DEFAULT_VALUE_COLUMN);
	String schemaName = params.getProperty(SCHEMA);
	String catalogName = params.getProperty(CATALOG);
	keySize = PropertiesHelper.getInt(PK_LENGTH_NAME, params, DEFAULT_PK_LENGTH);
	String keyValue = PropertiesHelper.getString(PK_VALUE_NAME, params, params.getProperty(TABLE) );

	if ( tableName.indexOf( '.' )<0 ) {
		tableName = Table.qualify( catalogName, schemaName, tableName );
	}

	query = "select " +
		valueColumnName +
		" from " +
		dialect.appendLockHint(LockMode.UPGRADE, tableName) +
		" where " + pkColumnName + " = '" + keyValue + "'" +
		dialect.getForUpdateString();

	update = "update " +
		tableName +
		" set " +
		valueColumnName +
		" = ? where " +
		valueColumnName +
		" = ? and " +
		pkColumnName +
		" = '" + 
		keyValue 
		+ "'";
	
	insert = "insert into " + tableName +
		"(" + pkColumnName + ", " +	valueColumnName + ") " +
		"values('"+ keyValue +"', ?)";


	//hilo config
	maxLo = PropertiesHelper.getInt(MAX_LO, params, Short.MAX_VALUE);
	lo = maxLo + 1; // so we "clock over" on the first invocation
	returnClass = type.getReturnedClass();
}
 
Example 15
Source File: SequenceHiLoGenerator.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void configure(Type type, Properties params, Dialect d) throws MappingException {
	super.configure(type, params, d);
	maxLo = PropertiesHelper.getInt(MAX_LO, params, 9);
	lo = maxLo + 1; // so we "clock over" on the first invocation
	returnClass = type.getReturnedClass();
}
 
Example 16
Source File: TableHiLoGenerator.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void configure(Type type, Properties params, Dialect d) {
	super.configure(type, params, d);
	maxLo = PropertiesHelper.getInt(MAX_LO, params, Short.MAX_VALUE);
	lo = maxLo + 1; // so we "clock over" on the first invocation
	returnClass = type.getReturnedClass();
}