org.hibernate.QueryException Java Examples

The following examples show how to use org.hibernate.QueryException. 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: CharIndexFunction.java    From lams with 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 #2
Source File: QueryTranslatorImpl.java    From lams with 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 #3
Source File: FromElementType.java    From lams with 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 #4
Source File: JoinedSubclassEntityPersister.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #5
Source File: CriteriaQueryTranslator.java    From lams with 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 #6
Source File: QueryLoader.java    From lams with 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 #7
Source File: QueryLoader.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 File: QueryTranslatorImpl.java    From lams with 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
Source File: WhereParser.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #10
Source File: AbstractCollectionPersister.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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 #11
Source File: HQLQueryPlan.java    From lams with 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 #12
Source File: AbstractPropertyMapping.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #13
Source File: CustomLoader.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #14
Source File: HqlSqlWalker.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 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 #16
Source File: WhereParser.java    From lams with 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 #17
Source File: HQLTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 #18
Source File: SQLQueryImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public SQLQuery addJoin(String alias, String path, LockMode lockMode) {
	int loc = path.indexOf('.');
	if ( loc < 0 ) {
		throw new QueryException( "not a property path: " + path );
	}
	String ownerAlias = path.substring(0, loc);
	String role = path.substring(loc+1);
	queryReturns.add( new NativeSQLQueryJoinReturn(alias, ownerAlias, role, CollectionHelper.EMPTY_MAP, lockMode) );
	return this;
}
 
Example #19
Source File: BulkManipulationTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testDeleteNonExistentEntity() {
	Session s = openSession();
	Transaction t = s.beginTransaction();

	try {
		s.createQuery( "delete NonExistentEntity" ).executeUpdate();
		fail( "no exception thrown" );
	}
	catch( QueryException e ) {
		log.debug( "Caught expected error type : " + e.getMessage() );
	}

	t.commit();
	s.close();
}
 
Example #20
Source File: FromElement.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void setFetch(boolean fetch) {
	this.fetch = fetch;
	// Fetch can't be used with scroll() or iterate().
	if ( fetch && getWalker().isShallowQuery() ) {
		throw new QueryException( QueryTranslator.ERROR_CANNOT_FETCH_WITH_ITERATE );
	}
}
 
Example #21
Source File: ElementPropertyMapping.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public Type toType(String propertyName) throws QueryException {
	if ( propertyName==null || "id".equals(propertyName) ) {
		return type;
	}
	else {
		throw new QueryException("cannot dereference scalar collection element: " + propertyName);
	}
}
 
Example #22
Source File: PathExpressionParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected String[] currentColumns() throws QueryException {
	String propertyPath = getPropertyPath();
	String[] propertyColumns = getPropertyMapping().toColumns( currentName, propertyPath );
	if ( propertyColumns == null ) {
		throw new QueryException( "could not resolve property columns: " + propertyPath );
	}
	return propertyColumns;
}
 
Example #23
Source File: PreprocessingParser.java    From lams with 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 #24
Source File: PostgreSQLFTSFunction.java    From blog-tutorials with 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 #25
Source File: QueryTranslatorImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
void setCollectionToFetch(String role, String name, String ownerName, String entityName)
		throws QueryException {
	fetchName = name;
	collectionPersister = getCollectionPersister( role );
	collectionOwnerName = ownerName;
	if ( collectionPersister.getElementType().isEntityType() ) {
		addEntityToFetch( entityName );
	}
}
 
Example #26
Source File: StaticPrecisionFspTimestampFunction.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String render(Type argumentType, List args, SessionFactoryImplementor factory) throws QueryException {
	if ( args.size() > 0 ) {
		throw new QueryException( "function takes no arguments: " + getName() );
	}
	return renderedString == null ?
			super.render( argumentType, args, factory ) :
			renderedString;
}
 
Example #27
Source File: ASTParserLoadingTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 File: BooleanLiteralNode.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 #29
Source File: NativeSQLQueryPlan.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private int[] getNamedParameterLocs(String name) throws QueryException {
	Object loc = customQuery.getNamedParameterBindPoints().get( name );
	if ( loc == null ) {
		throw new QueryException(
				"Named parameter does not appear in Query: " + name,
				customQuery.getSQL() );
	}
	if ( loc instanceof Integer ) {
		return new int[] { ((Integer) loc ).intValue() };
	}
	else {
		return ArrayHelper.toIntArray( (List) loc );
	}
}
 
Example #30
Source File: QueryTranslatorImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
void addFromClass(String name, Queryable classPersister)
		throws QueryException {
	JoinSequence joinSequence = new JoinSequence( getFactory() )
			.setRoot( classPersister, name );
	//crossJoins.add(name);
	addFrom( name, classPersister.getEntityName(), joinSequence );
}