Java Code Examples for org.hibernate.QueryException

The following examples show how to use org.hibernate.QueryException. 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 check out the related API usage on the sidebar.
Example 1
Source Project: lams   Source File: QueryTranslatorImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Compile a filter. This method may be called multiple
 * times. Subsequent invocations are no-ops.
 */
public synchronized void compile(
		String collectionRole,
		Map replacements,
		boolean scalar) throws QueryException, MappingException {

	if ( !isCompiled() ) {
		addFromAssociation( "this", collectionRole );
		paramValueBinders.add(
				new CollectionFilterKeyParameterSpecification(
						collectionRole,
						getFactory().getMetamodel().collectionPersister( collectionRole ).getKeyType()
				)
		);
		compile( replacements, scalar );
	}
}
 
Example 2
Source Project: lams   Source File: FromElementType.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public String[] toColumns(String alias, String propertyName) throws QueryException {
	validate( propertyName );
	final String joinTableAlias = joinSequence.getFirstJoin().getAlias();
	if ( CollectionPropertyNames.COLLECTION_INDEX.equals( propertyName ) ) {
		return queryableCollection.toColumns( joinTableAlias, propertyName );
	}

	final String[] cols = queryableCollection.getIndexColumnNames( joinTableAlias );
	if ( CollectionPropertyNames.COLLECTION_MIN_INDEX.equals( propertyName ) ) {
		if ( cols.length != 1 ) {
			throw new QueryException( "composite collection index in minIndex()" );
		}
		return new String[] {"min(" + cols[0] + ')'};
	}
	else {
		if ( cols.length != 1 ) {
			throw new QueryException( "composite collection index in maxIndex()" );
		}
		return new String[] {"max(" + cols[0] + ')'};
	}
}
 
Example 3
public String[] toColumns(String alias, String propertyName) throws QueryException {

		if ( ENTITY_CLASS.equals(propertyName) ) {
			// This doesn't actually seem to work but it *might*
			// work on some dbs. Also it doesn't work if there
			// are multiple columns of results because it
			// is not accounting for the suffix:
			// return new String[] { getDiscriminatorColumnName() };

			return new String[] { discriminatorFragment(alias).toFragmentString() };
		}
		else {
			return super.toColumns(alias, propertyName);
		}

	}
 
Example 4
Source Project: lams   Source File: CriteriaQueryTranslator.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void createAssociationPathCriteriaMap() {
	final Iterator<CriteriaImpl.Subcriteria> iter = rootCriteria.iterateSubcriteria();
	while ( iter.hasNext() ) {
		CriteriaImpl.Subcriteria crit = iter.next();
		String wholeAssociationPath = getWholeAssociationPath( crit );
		Object old = associationPathCriteriaMap.put( wholeAssociationPath, crit );
		if ( old != null ) {
			throw new QueryException( "duplicate association path: " + wholeAssociationPath );
		}
		JoinType joinType = crit.getJoinType();
		old = associationPathJoinTypesMap.put( wholeAssociationPath, joinType );
		if ( old != null ) {
			// TODO : not so sure this is needed...
			throw new QueryException( "duplicate association path: " + wholeAssociationPath );
		}
		if ( crit.getWithClause() != null ) {
			this.withClauseMap.put( wholeAssociationPath, crit.getWithClause() );
		}
	}
}
 
Example 5
Source Project: lams   Source File: QueryLoader.java    License: GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected List getResultList(List results, ResultTransformer resultTransformer) throws QueryException {
	// meant to handle dynamic instantiation queries...
	HolderInstantiator holderInstantiator = buildHolderInstantiator( resultTransformer );
	if ( holderInstantiator.isRequired() ) {
		for ( int i = 0; i < results.size(); i++ ) {
			Object[] row = (Object[]) results.get( i );
			Object result = holderInstantiator.instantiate( row );
			results.set( i, result );
		}

		if ( !hasSelectNew() && resultTransformer != null ) {
			return resultTransformer.transformList( results );
		}
		else {
			return results;
		}
	}
	else {
		return results;
	}
}
 
Example 6
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 7
protected List getResultList(List results, ResultTransformer resultTransformer) throws QueryException {
	// meant to handle dynamic instantiation queries...
	HolderInstantiator holderInstantiator = HolderInstantiator.getHolderInstantiator(selectNewTransformer, resultTransformer, queryReturnAliases);
	if ( holderInstantiator.isRequired() ) {
		for ( int i = 0; i < results.size(); i++ ) {
			Object[] row = ( Object[] ) results.get( i );
			Object result = holderInstantiator.instantiate(row);
			results.set( i, result );
		}

		if(!hasSelectNew() && resultTransformer!=null) {
			return resultTransformer.transformList(results);
		} else {
			return results;
		}
	} else {
		return results;
	}
}
 
Example 8
Source Project: lams   Source File: QueryTranslatorImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void generate(AST sqlAst) throws QueryException, RecognitionException {
	if ( sql == null ) {
		final SqlGenerator gen = new SqlGenerator( factory );
		gen.statement( sqlAst );
		sql = gen.getSQL();
		if ( LOG.isDebugEnabled() ) {
			LOG.debugf( "HQL: %s", hql );
			LOG.debugf( "SQL: %s", sql );
		}
		gen.getParseErrorHandler().throwQueryException();
		if ( collectedParameterSpecifications == null ) {
			collectedParameterSpecifications = gen.getCollectedParameters();
		}
		else {
			collectedParameterSpecifications.addAll( gen.getCollectedParameters() );
		}
	}
}
 
Example 9
protected List getResultList(List results, ResultTransformer resultTransformer) throws QueryException {
	// meant to handle dynamic instantiation queries...(Copy from QueryLoader)
	HolderInstantiator holderInstantiator = HolderInstantiator.getHolderInstantiator(
			null,
			resultTransformer,
			getReturnAliasesForTransformer()
	);
	if ( holderInstantiator.isRequired() ) {
		for ( int i = 0; i < results.size(); i++ ) {
			Object[] row = ( Object[] ) results.get( i );
			Object result = holderInstantiator.instantiate(row);
			results.set( i, result );
		}
		
		return resultTransformer.transformList(results);
	}
	else {
		return results;
	}
}
 
Example 10
private String getElementName(PathExpressionParser.CollectionElement element, QueryTranslatorImpl q) throws QueryException {
	String name;
	if ( element.isOneToMany ) {
		name = element.alias;
	}
	else {
		Type type = element.elementType;
		if ( type.isEntityType() ) { //ie. a many-to-many
			String entityName = ( ( EntityType ) type ).getAssociatedEntityName();
			name = pathExpressionParser.continueFromManyToMany( entityName, element.elementColumns, q );
		}
		else {
			throw new QueryException( "illegally dereferenced collection element" );
		}
	}
	return name;
}
 
Example 11
@Override
public String[] toColumns(String propertyName) throws QueryException {
	if ( "index".equals( propertyName ) ) {
		if ( indexFragments == null ) {
			String[] tmp = new String[indexColumnNames.length];
			for ( int i = 0; i < indexColumnNames.length; i++ ) {
				tmp[i] = indexColumnNames[i] == null
						? indexFormulas[i]
						: indexColumnNames[i];
				indexFragments = tmp;
			}
		}
		return indexFragments;
	}

	return elementPropertyMapping.toColumns( propertyName );
}
 
Example 12
Source Project: lams   Source File: HQLQueryPlan.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Coordinates the efforts to perform a scroll across all the included query translators.
 *
 * @param queryParameters The query parameters
 * @param session The session
 *
 * @return The query result iterator
 *
 * @throws HibernateException Indicates a problem performing the query
 */
public ScrollableResultsImplementor performScroll(
		QueryParameters queryParameters,
		SharedSessionContractImplementor session) throws HibernateException {
	if ( traceEnabled ) {
		LOG.tracev( "Iterate: {0}", getSourceQuery() );
		queryParameters.traceParameters( session.getFactory() );
	}
	if ( translators.length != 1 ) {
		throw new QueryException( "implicit polymorphism not supported for scroll() queries" );
	}
	if ( queryParameters.getRowSelection().definesLimits() && translators[0].containsCollectionFetches() ) {
		throw new QueryException( "firstResult/maxResults not supported in conjunction with scroll() of a query containing collection fetches" );
	}

	return translators[0].scroll( queryParameters, session );
}
 
Example 13
public String[] toColumns(String alias, String propertyName) throws QueryException {
	//TODO: *two* hashmap lookups here is one too many...
	String[] columns = (String[]) columnsByPropertyPath.get(propertyName);
	if ( columns == null ) {
		throw propertyException( propertyName );
	}
	String[] templates = (String[]) formulaTemplatesByPropertyPath.get(propertyName);
	String[] result = new String[columns.length];
	for ( int i=0; i<columns.length; i++ ) {
		if ( columns[i]==null ) {
			result[i] = StringHelper.replace( templates[i], Template.TEMPLATE, alias );
		}
		else {
			result[i] = StringHelper.qualify( alias, columns[i] );
		}
	}
	return result;
}
 
Example 14
protected boolean isNonQualifiedPropertyRef(AST ident) {
	final String identText = ident.getText();
	if ( currentFromClause.isFromElementAlias( identText ) ) {
		return false;
	}

	List fromElements = currentFromClause.getExplicitFromElements();
	if ( fromElements.size() == 1 ) {
		final FromElement fromElement = ( FromElement ) fromElements.get( 0 );
		try {
			log.trace( "attempting to resolve property [" + identText + "] as a non-qualified ref" );
			return fromElement.getPropertyMapping( identText ).toType( identText ) != null;
		}
		catch( QueryException e ) {
			// Should mean that no such property was found
		}
	}

	return false;
}
 
Example 15
Source Project: lams   Source File: CharIndexFunction.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public String render(Type columnType, List args, SessionFactoryImplementor factory) throws QueryException {
	final boolean threeArgs = args.size() > 2;
	final Object pattern = args.get( 0 );
	final Object string = args.get( 1 );
	final Object start = threeArgs ? args.get( 2 ) : null;

	final StringBuilder buf = new StringBuilder();
	buf.append( "charindex(" ).append( pattern ).append( ", " );
	if (threeArgs) {
		buf.append( "right(" );
	}
	buf.append( string );
	if (threeArgs) {
		buf.append( ", char_length(" ).append( string ).append( ")-(" ).append( start ).append( "-1))" );
	}
	buf.append( ')' );
	return buf.toString();
}
 
Example 16
void addFromClass(String name, Queryable classPersister)
		throws QueryException {
	JoinSequence joinSequence = new JoinSequence( getFactory() )
			.setRoot( classPersister, name );
	//crossJoins.add(name);
	addFrom( name, classPersister.getEntityName(), joinSequence );
}
 
Example 17
Source Project: lams   Source File: PreprocessingParser.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void end(QueryTranslatorImpl q) throws QueryException {
	if ( lastToken != null ) {
		parser.token( lastToken, q );
	}
	parser.end( q );
	lastToken = null;
	currentCollectionProp = null;
}
 
Example 18
Source Project: blog-tutorials   Source File: PostgreSQLFTSFunction.java    License: MIT License 5 votes vote down vote up
@Override
public String render(Type type, List args, SessionFactoryImplementor factory) throws QueryException {

	if (args == null || args.size() != 3) {
		throw new IllegalArgumentException("The function must be passed 2 arguments");
	}

	String language = (String) args.get(0);
	String field = (String) args.get(1);
	String searchString = (String) args.get(2);
	return field + " @@ to_tsquery('" + language + "', " + searchString + ")";
}
 
Example 19
public Type toType(String propertyName) throws QueryException {
	if ( propertyName.equals(CollectionPropertyNames.COLLECTION_ELEMENTS) ) {
		return memberPersister.getElementType();
	}
	else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_INDICES) ) {
		if ( !memberPersister.hasIndex() ) throw new QueryException("unindexed collection before indices()");
		return memberPersister.getIndexType();
	}
	else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_SIZE) ) {
		return Hibernate.INTEGER;
	}
	else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_MAX_INDEX) ) {
		return memberPersister.getIndexType();
	}
	else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_MIN_INDEX) ) {
		return memberPersister.getIndexType();
	}
	else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_MAX_ELEMENT) ) {
		return memberPersister.getElementType();
	}
	else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_MIN_ELEMENT) ) {
		return memberPersister.getElementType();
	}
	else {
		//return memberPersister.getPropertyType(propertyName);
		throw new QueryException("illegal syntax near collection: " + propertyName);
	}
}
 
Example 20
public String[] toColumns(String alias, String propertyName)
		throws QueryException {

	if ( "index".equals( propertyName ) ) {
		if ( isManyToMany() ) {
			throw new QueryException( "index() function not supported for many-to-many association" );
		}
		return StringHelper.qualify( alias, indexColumnNames );
	}

	return elementPropertyMapping.toColumns( alias, propertyName );
}
 
Example 21
Source Project: lams   Source File: PathExpressionParser.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void prepareForIndex(QueryTranslatorImpl q) throws QueryException {

		QueryableCollection collPersister = q.getCollectionPersister( collectionRole );

		if ( !collPersister.hasIndex() ) {
			throw new QueryException( "unindexed collection before []: " + path );
		}

		String[] indexCols = collPersister.getIndexColumnNames();
		if ( indexCols.length != 1 ) {
			throw new QueryException( "composite-index appears in []: " + path );
		}
		//String[] keyCols = collPersister.getKeyColumnNames();

		JoinSequence fromJoins = new JoinSequence( q.getFactory() )
				.setUseThetaStyle( useThetaStyleJoin )
				.setRoot( collPersister, collectionName )
				.setNext( joinSequence.copy() );

		if ( !continuation ) {
			addJoin( collectionName, collPersister.getCollectionType() );
		}

		joinSequence.addCondition( collectionName + '.' + indexCols[0] + " = " ); //TODO: get SQL rendering out of here

		CollectionElement elem = new CollectionElement();
		elem.elementColumns = collPersister.getElementColumnNames(collectionName);
		elem.elementType = collPersister.getElementType();
		elem.isOneToMany = collPersister.isOneToMany();
		elem.alias = collectionName;
		elem.joinSequence = joinSequence;
		collectionElements.addLast( elem );
		setExpectingCollectionIndex();

		q.addCollection( collectionName, collectionRole );
		q.addFromJoinOnly( collectionName, fromJoins );
	}
 
Example 22
/**
 * Returns the locations of all occurrences of the named parameter.
 */
public int[] getNamedParameterLocations(String name) throws QueryException {
	Object o = namedParameters.get( name );
	if ( o == null ) {
		QueryException qe = new QueryException( QueryTranslator.ERROR_NAMED_PARAMETER_DOES_NOT_APPEAR + name );
		qe.setQueryString( queryTranslatorImpl.getQueryString() );
		throw qe;
	}
	if ( o instanceof Integer ) {
		return new int[]{( ( Integer ) o ).intValue()};
	}
	else {
		return ArrayHelper.toIntArray( ( ArrayList ) o );
	}
}
 
Example 23
/**
 * Determine the name of the property for the entity encapsulated by the
 * given type which represents the id or unique-key.
 *
 * @param entityType The type representing the entity.
 * @return The corresponding property name
 * @throws QueryException Indicates such a property could not be found.
 */
public String getIdentifierOrUniqueKeyPropertyName(EntityType entityType) {
	try {
		return entityType.getIdentifierOrUniqueKeyPropertyName( sfi );
	}
	catch ( MappingException me ) {
		throw new QueryException( me );
	}
}
 
Example 24
private void endChild(QueryTranslatorImpl q) throws QueryException {
	if ( child == null ) {
		//null child could occur for no from clause in a filter
		cacheSelectTokens = false;
	}
	else {
		child.end( q );
	}
}
 
Example 25
public void testInsertIntoSuperclassPropertiesFails() {
	TestData data = new TestData();
	data.prepare();

	Session s = openSession();
	Transaction t = s.beginTransaction();

	try {
		s.createQuery( "insert into Human (id, bodyWeight) select id, bodyWeight from Lizard" ).executeUpdate();
		fail( "superclass prop insertion did not error" );
	}
	catch( QueryException e ) {
		// expected result
	}

	t.commit();
	t = s.beginTransaction();

	s.createQuery( "delete Animal where mother is not null" ).executeUpdate();
	s.createQuery( "delete Animal where father is not null" ).executeUpdate();
	s.createQuery( "delete Animal" ).executeUpdate();

	t.commit();
	s.close();

	data.cleanup();
}
 
Example 26
public String getRenderText(SessionFactoryImplementor sessionFactory) {
	try {
		return getTypeInternal().objectToSQLString( getValue(), sessionFactory.getDialect() );
	}
	catch( Throwable t ) {
		throw new QueryException( "Unable to render boolean literal value", t );
	}
}
 
Example 27
public void testFetchInSubqueryFails() {
	Session s = openSession();
	try {
		s.createQuery( "from Animal a where a.mother in (select m from Animal a1 inner join a1.mother as m join fetch m.mother)" ).list();
		fail( "fetch join allowed in subquery" );
	}
	catch( QueryException expected ) {
		// expected behavior
	}
	s.close();
}
 
Example 28
Source Project: lams   Source File: WhereParser.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void end(QueryTranslatorImpl q) throws QueryException {
	if ( expectingPathContinuation ) {
		expectingPathContinuation = false;
		PathExpressionParser.CollectionElement element = pathExpressionParser.lastCollectionElement();
		if ( element.elementColumns.length != 1 ) {
			throw new QueryException( "path expression ended in composite collection element" );
		}
		appendToken( q, element.elementColumns[0] );
		addToCurrentJoin( element );
	}
	token( ")", q );
}
 
Example 29
protected void prepareTest() throws Exception {
	super.prepareTest();
	SelectClause.VERSION2_SQL = true;
	DotNode.REGRESSION_STYLE_JOIN_SUPPRESSION = true;
	DotNode.ILLEGAL_COLL_DEREF_EXCP_BUILDER = new DotNode.IllegalCollectionDereferenceExceptionBuilder() {
		public QueryException buildIllegalCollectionDereferenceException(String propertyName, FromReferenceNode lhs) {
			throw new QueryException( "illegal syntax near collection: " + propertyName );
		}
	};
}
 
Example 30
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 ) + ")";
	}
}