org.hibernate.type.Type Java Examples

The following examples show how to use org.hibernate.type.Type. 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: FilterImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Set the named parameter's value list for this filter.  Used
 * in conjunction with IN-style filter criteria.
 *
 * @param name   The parameter's name.
 * @param values The values to be expanded into an SQL IN list.
 * @return This FilterImpl instance (for method chaining).
 */
public Filter setParameterList(String name, Collection values) throws HibernateException  {
	// Make sure this is a defined parameter and check the incoming value type
	if ( values == null ) {
		throw new IllegalArgumentException( "Collection must be not null!" );
	}
	Type type = definition.getParameterType( name );
	if ( type == null ) {
		throw new HibernateException( "Undefined filter parameter [" + name + "]" );
	}
	if ( values.size() > 0 ) {
		Class elementClass = values.iterator().next().getClass();
		if ( !type.getReturnedClass().isAssignableFrom( elementClass ) ) {
			throw new HibernateException( "Incorrect type for parameter [" + name + "]" );
		}
	}
	parameters.put( name, values );
	return this;
}
 
Example #2
Source File: AbstractEntityPersister.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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 #3
Source File: AuditInterceptor.java    From MogwaiERDesignerNG with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean onFlushDirty(Object aEntity, Serializable aID, Object[] aCurrentState, Object[] aPreviousState,
		String[] aPropertyNames, Type[] aTypes) {

	String theCurrentUser = getCurrentUserId();

	if (theCurrentUser != null) {

		for (int i = 0; i < aPropertyNames.length; i++) {

			String thePropertyName = aPropertyNames[i];
			if ("lastModificationDate".equals(thePropertyName)) {
				aCurrentState[i] = new Timestamp(System.currentTimeMillis());
			}
			if ("lastModificationUser".equals(thePropertyName)) {
				aCurrentState[i] = theCurrentUser;
			}

		}

		return true;
	}

	return false;
}
 
Example #4
Source File: NaturalIdXrefDelegate.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public CachedNaturalId(EntityPersister persister, Object[] values) {
	this.persister = persister;
	this.values = values;

	final int prime = 31;
	int hashCodeCalculation = 1;
	hashCodeCalculation = prime * hashCodeCalculation + persister.hashCode();

	final int[] naturalIdPropertyIndexes = persister.getNaturalIdentifierProperties();
	naturalIdTypes = new Type[ naturalIdPropertyIndexes.length ];
	int i = 0;
	for ( int naturalIdPropertyIndex : naturalIdPropertyIndexes ) {
		final Type type = persister.getPropertyType( persister.getPropertyNames()[ naturalIdPropertyIndex ] );
		naturalIdTypes[i] = type;
		final int elementHashCode = values[i] == null ? 0 :type.getHashCode( values[i], persister.getFactory() );
		hashCodeCalculation = prime * hashCodeCalculation + elementHashCode;
		i++;
	}

	this.hashCode = hashCodeCalculation;
}
 
Example #5
Source File: IntoClause.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public void validateTypes(SelectClause selectClause) throws QueryException {
	Type[] selectTypes = selectClause.getQueryReturnTypes();
	if ( selectTypes.length + selectClause.getTotalParameterCount() != types.length ) {
		throw new QueryException( "number of select types did not match those for insert" );
	}

	int parameterCount = 0;
	for ( int i = 0; i < types.length; i++ ) {
		if ( selectClause.getParameterPositions().contains( i ) ) {
			parameterCount++;
		}
		else if ( !areCompatible( types[i], selectTypes[i - parameterCount] ) ) {
			throw new QueryException(
					"insertion type [" + types[i] + "] and selection type [" +
							selectTypes[i - parameterCount] + "] at position " + i + " are not compatible"
			);
		}
	}

	// otherwise, everything ok.
}
 
Example #6
Source File: IteratorImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public IteratorImpl(
        ResultSet rs,
        PreparedStatement ps,
        EventSource sess,
        Type[] types,
        String[][] columnNames,
        HolderInstantiator holderInstantiator)
throws HibernateException, SQLException {

	this.rs=rs;
	this.ps=ps;
	this.session = sess;
	this.types = types;
	this.names = columnNames;
	this.holderInstantiator = holderInstantiator;

	single = types.length==1;

	postNext();
}
 
Example #7
Source File: Loader.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Return the query results, using the query cache, called
 * by subclasses that implement cacheable queries
 */
protected List list(
		final SharedSessionContractImplementor session,
		final QueryParameters queryParameters,
		final Set<Serializable> querySpaces,
		final Type[] resultTypes) throws HibernateException {
	final boolean cacheable = factory.getSessionFactoryOptions().isQueryCacheEnabled() &&
			queryParameters.isCacheable();

	if ( cacheable ) {
		return listUsingQueryCache( session, queryParameters, querySpaces, resultTypes );
	}
	else {
		return listIgnoreQueryCache( session, queryParameters );
	}
}
 
Example #8
Source File: FunctionTemplateRegistrator.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void register(Dialect dialect) {
	logger.debug("IN");
	try {
		if (function.getCode() != null || !function.getCode().equals("")) {
			dialect.registerFunction(function.getName(),
					new SQLFunctionTemplate((Type) StandardBasicTypes.class.getField(function.getType()).get(null), function.getCode()));
		}

	} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
		logger.error("Error while registering function", e);
		throw new SpagoBIEngineRuntimeException("Error while registering function", e);
	} finally {
		logger.debug("OUT");
	}

}
 
Example #9
Source File: IntoClause.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void validateTypes(SelectClause selectClause) throws QueryException {
	Type[] selectTypes = selectClause.getQueryReturnTypes();
	if ( selectTypes.length != types.length ) {
		throw new QueryException( "number of select types did not match those for insert" );
	}

	for ( int i = 0; i < types.length; i++ ) {
		if ( !areCompatible( types[i], selectTypes[i] ) ) {
			throw new QueryException(
			        "insertion type [" + types[i] + "] and selection type [" +
			        selectTypes[i] + "] at position " + i + " are not compatible"
			);
		}
	}

	// otherwise, everything ok.
}
 
Example #10
Source File: InExpressionIgnoringCase.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
	List<TypedValue> list = new ArrayList<>();
	Type type = criteriaQuery.getTypeUsingProjection(criteria, propertyName);
	if (type.isComponentType()) {
		CompositeType actype = (CompositeType) type;
		Type[] types = actype.getSubtypes();
		for (int j = 0; j < values.length; j++) {
			for (int i = 0; i < types.length; i++) {
				Object subval = values[j] == null ? null : actype.getPropertyValues(values[j], EntityMode.POJO)[i];
				list.add(new TypedValue(types[i], subval, EntityMode.POJO));
			}
		}
	} else {
		for (int j = 0; j < values.length; j++) {
			list.add(new TypedValue(type, values[j], EntityMode.POJO));
		}
	}
	return list.toArray(new TypedValue[list.size()]);
}
 
Example #11
Source File: DBManager.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Hibernate Find method. Use this in a transactional context by using your current transaction object.
 * 
 * @param trx
 *            The current db transaction
 * @param query
 *            The HQL query
 * @param values
 *            The object array containing all search values
 * @param types
 *            The object array containing all Hibernate datatype of the search values
 */
List find(DBTransaction trx, String query, Object[] values, Type[] types) {
    List li = null;
    try {
        long start = 0;
        if (log.isDebugEnabled())
            start = System.currentTimeMillis();
        // old: li = getSession().find(query, values, types);
        Query qu = this.getSession().createQuery(query);
        qu.setParameters(values, types);
        li = qu.list();

        if (log.isDebugEnabled()) {
            long time = (System.currentTimeMillis() - start);
            logQuery("find (time " + time + ", res " + (li == null ? "null" : "" + li.size()) + ")(trans " + trx.hashCode() + ")", values, types, query);
        }

    } catch (HibernateException e) {
        trx.setErrorAndRollback(e);
        String msg = "Find failed in transaction. Query: " + query + " " + e;
        setError(e);
        throw new DBRuntimeException(msg, e);
    }
    return li;
}
 
Example #12
Source File: PathExpressionParser.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #13
Source File: PersistentIndexedElementHolder.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public Object readFrom(ResultSet rs, CollectionPersister persister, CollectionAliases descriptor, Object owner)
throws HibernateException, SQLException {
	Object object = persister.readElement( rs, owner, descriptor.getSuffixedElementAliases(), getSession() );
	final Type elementType = persister.getElementType();
	final SessionFactoryImplementor factory = persister.getFactory();
	String indexNode = getIndexAttributeName(persister);

	Element elem = element.addElement( persister.getElementNodeName() );
	elementType.setToXMLNode( elem, object, factory ); 
	
	final Type indexType = persister.getIndexType();
	final Object indexValue = persister.readIndex( rs, descriptor.getSuffixedIndexAliases(), getSession() );
	final String index = ( (NullableType) indexType ).toXMLString( indexValue, factory );
	setIndex(elem, indexNode, index);
	return object;
}
 
Example #14
Source File: DBManager.java    From olat with Apache License 2.0 6 votes vote down vote up
int delete(String query, Object value, Type type) {
    int deleted = 0;
    try {
        // old: deleted = getSession().delete(query, value, type);
        Session si = getSession();
        Query qu = si.createQuery(query);
        qu.setParameter(0, value, type);
        List foundToDel = qu.list();
        int deletionCount = foundToDel.size();
        for (int i = 0; i < deletionCount; i++) {
            si.delete(foundToDel.get(i));
        }
        // //
        getSession().flush();

        if (log.isDebugEnabled()) {
            logQuery("delete", new Object[] { value }, new Type[] { type }, query);
        }
    } catch (HibernateException e) {
        setError(e);
        throw new DBRuntimeException("Delete error. Query" + query + " Object: " + value, e);
    }
    return deleted;
}
 
Example #15
Source File: QueryParameters.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public QueryParameters(
	final Type[] positionalParameterTypes,
	final Object[] postionalParameterValues
) {
	this(
		positionalParameterTypes,
		postionalParameterValues, 
		null, 
		null, 
		false, 
		null, 
		null,
		false,
		null
	);
}
 
Example #16
Source File: Example.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected void addPropertyTypedValue(Object value, Type type, List<TypedValue> list) {
	if ( value != null ) {
		if ( value instanceof String ) {
			String string = (String) value;
			if ( isIgnoreCaseEnabled ) {
				string = string.toLowerCase(Locale.ROOT);
			}
			if ( isLikeEnabled ) {
				string = matchMode.toMatchString( string );
			}
			value = string;
		}
		list.add( new TypedValue( type, value ) );
	}
}
 
Example #17
Source File: Printer.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public String toString(Type[] types, Object[] values) throws HibernateException {
	List list = new ArrayList( types.length * 5 );
	for ( int i=0; i<types.length; i++ ) {
		if ( types[i]!=null ) list.add( types[i].toLoggableString( values[i], factory ) );
	}
	return list.toString();
}
 
Example #18
Source File: DotNode.java    From lams with GNU General Public License v2.0 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 #19
Source File: PersistentSet.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public boolean needsInserting(Object entry, int i, Type elemType) throws HibernateException {
	final java.util.Map sn = (java.util.Map) getSnapshot();
	Object oldValue = sn.get(entry);
	// note that it might be better to iterate the snapshot but this is safe,
	// assuming the user implements equals() properly, as required by the Set
	// contract!
	return oldValue==null || elemType.isDirty( oldValue, entry, getSession() );
}
 
Example #20
Source File: Property.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
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 #21
Source File: SimpleProjection.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Count the number of columns this projection uses.
 *
 * @param criteria The criteria
 * @param criteriaQuery The query
 *
 * @return The number of columns
 */
public int getColumnCount(Criteria criteria, CriteriaQuery criteriaQuery) {
	final Type[] types = getTypes( criteria, criteriaQuery );
	int count = 0;
	for ( Type type : types ) {
		count += type.getColumnSpan( criteriaQuery.getFactory() );
	}
	return count;
}
 
Example #22
Source File: SelectParser.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public Type aggregateType(List funcTokenList, Type type, QueryTranslatorImpl q) throws QueryException {
	Type retType = type;
	Type argType;
	for ( int i = funcTokenList.size() - 1; i >= 0; i-- ) {
		argType = retType;
		String funcToken = ( String ) funcTokenList.get( i );
		retType = getFunction( funcToken, q ).getReturnType( argType, q.getFactory() );
	}
	return retType;
}
 
Example #23
Source File: ReactiveIdentifierGeneratorFactory.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static IdentifierGenerator augmentWithReactiveGenerator(IdentifierGenerator generator, Type type, Properties params, ServiceRegistryImplementor serviceRegistry) {
	ReactiveIdentifierGenerator<?> reactiveGenerator;
	if (generator instanceof SequenceStyleGenerator) {
		DatabaseStructure structure = ((SequenceStyleGenerator) generator).getDatabaseStructure();
		if (structure instanceof TableStructure) {
			reactiveGenerator = new TableReactiveIdentifierGenerator(true);
		}
		else if (structure instanceof SequenceStructure) {
			reactiveGenerator = new SequenceReactiveIdentifierGenerator();
		}
		else {
			throw new IllegalStateException("unknown structure type");
		}
	}
	else if (generator instanceof TableGenerator) {
		reactiveGenerator = new TableReactiveIdentifierGenerator(false);
	}
	else if (generator instanceof SequenceGenerator) {
		reactiveGenerator = new SequenceReactiveIdentifierGenerator();
	}
	else if (generator instanceof SelectGenerator) {
		//TODO: this is easy to fix!
		throw new HibernateException("SelectGenerator is not yet supported in Hibernate Reactive");
	}
	else {
		//nothing to do
		return generator;
	}

	((Configurable) reactiveGenerator).configure( type, params, serviceRegistry );

	return new ReactiveGeneratorWrapper<>( reactiveGenerator, generator );
}
 
Example #24
Source File: BinaryArithmeticOperatorNode.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Figure out the type of the binary expression by looking at
 * the types of the operands. Sometimes we don't know both types,
 * if, for example, one is a parameter.
 */
public Type getDataType() {
	if ( super.getDataType() == null ) {
		super.setDataType( resolveDataType() );
	}
	return super.getDataType();
}
 
Example #25
Source File: StandardSQLFunction.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String render(Type firstArgumentType, List arguments, SessionFactoryImplementor sessionFactory) {
	final StringBuilder buf = new StringBuilder();
	buf.append( getRenderedName( arguments) ).append( '(' );
	for ( int i = 0; i < arguments.size(); i++ ) {
		buf.append( arguments.get( i ) );
		if ( i < arguments.size() - 1 ) {
			buf.append( ", " );
		}
	}
	return buf.append( ')' ).toString();
}
 
Example #26
Source File: CriteriaQueryTypeQueryAdapter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public QueryImplementor<X> setParameter(int position, Object val, Type type) {
	entityManager.checkOpen( false );
	locateParameterByPosition( position );
	jpqlQuery.setParameter( position, val, type );
	return this;
}
 
Example #27
Source File: AbstractScrollableResults.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Object throwInvalidColumnTypeException(
        int i,
        Type type,
        Type returnType) throws HibernateException {
	throw new HibernateException( 
			"incompatible column types: " + 
			type.getName() + 
			", " + 
			returnType.getName() 
	);
}
 
Example #28
Source File: ConvertFunction.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String render(Type firstArgumentType, List args, SessionFactoryImplementor factory) throws QueryException {
	if ( args.size() != 2 && args.size() != 3 ) {
		throw new QueryException( "convert() requires two or three arguments" );
	}

	final String type = (String) args.get( 1 );

	if ( args.size() == 2 ) {
		return "{fn convert(" + args.get( 0 ) + " , " + type + ")}";
	}
	else {
		return "convert(" + args.get( 0 ) + " , " + type + "," + args.get( 2 ) + ")";
	}
}
 
Example #29
Source File: EmptyInterceptor.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public int[] findDirty(Object entity,
		Serializable id,
		Object[] currentState,
		Object[] previousState,
		String[] propertyNames,
		Type[] types) {
	return null;
}
 
Example #30
Source File: CriteriaQueryTypeQueryAdapter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public QueryImplementor<X> setParameter(String name, Object val, Type type) {
	entityManager.checkOpen( false );
	ExplicitParameterInfo<?> parameterInfo = locateParameterByName( name );
	parameterInfo.validateBindValue( val );
	jpqlQuery.setParameter( name, val, type );
	return this;
}