Java Code Examples for org.hibernate.type.Type

The following examples show how to use org.hibernate.type.Type. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
@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 2
Source Project: lams   Source File: NaturalIdXrefDelegate.java    License: 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 3
/**
 * 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 4
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 5
Source Project: lams   Source File: IntoClause.java    License: 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 Project: lams   Source File: Loader.java    License: 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 7
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 8
@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 9
Source Project: olat   Source File: DBManager.java    License: 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 10
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 11
Source Project: olat   Source File: DBManager.java    License: 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 12
public QueryParameters(
	final Type[] positionalParameterTypes,
	final Object[] postionalParameterValues
) {
	this(
		positionalParameterTypes,
		postionalParameterValues, 
		null, 
		null, 
		false, 
		null, 
		null,
		false,
		null
	);
}
 
Example 13
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
@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 15
/**
 * 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 16
public int[] findDirty(Object entity,
		Serializable id,
		Object[] currentState,
		Object[] previousState,
		String[] propertyNames,
		Type[] types) {
	return null;
}
 
Example 17
@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;
}
 
Example 18
/**
 * @see org.hibernate.id.Configurable#configure(org.hibernate.type.Type, java.util.Properties, org.hibernate.dialect.Dialect)
 */
public void configure(Type type, Properties params, Dialect d)
	throws MappingException {

	propertyName = params.getProperty("property");
	entityName = params.getProperty(ENTITY_NAME);
	if (propertyName==null) throw new MappingException(
		"param named \"property\" is required for foreign id generation strategy"
	);
}
 
Example 19
Source Project: lams   Source File: Example.java    License: 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 20
public final CompletionStage<Void> doBatchedCollectionLoad(
		final SessionImplementor session,
		final Serializable[] ids,
		final Type type) throws HibernateException {

	if ( LOG.isDebugEnabled() ) {
		LOG.debugf(
				"Batch loading collection: %s",
				collectionInfoString( getCollectionPersisters()[0], ids, getFactory() )
		);
	}

	final Type[] idTypes = new Type[ids.length];
	Arrays.fill( idTypes, type );
	final QueryParameters queryParameters = new QueryParameters( idTypes, ids, ids );

	final String sql = StringHelper.expandBatchIdPlaceholder(
			sqlTemplate,
			ids,
			alias,
			collectionPersister().getKeyColumnNames(),
			session.getJdbcServices().getJdbcEnvironment().getDialect()
	);

	return doReactiveQueryAndInitializeNonLazyCollections( sql, session, queryParameters )
			.handle( (list, err) -> {
				CompletionStages.logSqlException( err,
						() -> "could not initialize a collection batch: " +
								collectionInfoString( getCollectionPersisters()[0], ids, getFactory() ),
						getSQLString()
				);
				LOG.debug("Done batch load");
				return CompletionStages.returnNullorRethrow( err );
			} );

}
 
Example 21
Source Project: lams   Source File: NvlFunction.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public String render(Type argumentType, List args, SessionFactoryImplementor factory) throws QueryException {
	final int lastIndex = args.size()-1;
	final Object last = args.remove( lastIndex );
	if ( lastIndex==0 ) {
		return last.toString();
	}
	final Object secondLast = args.get( lastIndex-1 );
	final String nvl = "nvl(" + secondLast + ", " + last + ")";
	args.set( lastIndex-1, nvl );
	return render( argumentType, args, factory );
}
 
Example 22
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 23
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 24
Source Project: lams   Source File: Property.java    License: 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 25
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 26
/**
 * 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 27
Source Project: lams   Source File: ConvertFunction.java    License: 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 28
private Object throwInvalidColumnTypeException(
        int i,
        Type type,
        Type returnType) throws HibernateException {
	throw new HibernateException( 
			"incompatible column types: " + 
			type.getName() + 
			", " + 
			returnType.getName() 
	);
}
 
Example 29
Source Project: lams   Source File: StandardSQLFunction.java    License: 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 30
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;
}