Search in sources :

Example 16 with QueryException

use of org.hibernate.QueryException in project hibernate-orm by hibernate.

the class SessionImpl method getFilterQueryPlan.

private FilterQueryPlan getFilterQueryPlan(Object collection, String filter, QueryParameters parameters, boolean shallow) throws HibernateException {
    if (collection == null) {
        throw new NullPointerException("null collection passed to filter");
    }
    CollectionEntry entry = persistenceContext.getCollectionEntryOrNull(collection);
    final CollectionPersister roleBeforeFlush = (entry == null) ? null : entry.getLoadedPersister();
    FilterQueryPlan plan = null;
    if (roleBeforeFlush == null) {
        // if it was previously unreferenced, we need to flush in order to
        // get its state into the database in order to execute query
        flush();
        entry = persistenceContext.getCollectionEntryOrNull(collection);
        CollectionPersister roleAfterFlush = (entry == null) ? null : entry.getLoadedPersister();
        if (roleAfterFlush == null) {
            throw new QueryException("The collection was unreferenced");
        }
        plan = getFactory().getQueryPlanCache().getFilterQueryPlan(filter, roleAfterFlush.getRole(), shallow, getLoadQueryInfluencers().getEnabledFilters());
    } else {
        // otherwise, we only need to flush if there are in-memory changes
        // to the queried tables
        plan = getFactory().getQueryPlanCache().getFilterQueryPlan(filter, roleBeforeFlush.getRole(), shallow, getLoadQueryInfluencers().getEnabledFilters());
        if (autoFlushIfRequired(plan.getQuerySpaces())) {
            // might need to run a different filter entirely afterQuery the flush
            // because the collection role may have changed
            entry = persistenceContext.getCollectionEntryOrNull(collection);
            CollectionPersister roleAfterFlush = (entry == null) ? null : entry.getLoadedPersister();
            if (roleBeforeFlush != roleAfterFlush) {
                if (roleAfterFlush == null) {
                    throw new QueryException("The collection was dereferenced");
                }
                plan = getFactory().getQueryPlanCache().getFilterQueryPlan(filter, roleAfterFlush.getRole(), shallow, getLoadQueryInfluencers().getEnabledFilters());
            }
        }
    }
    if (parameters != null) {
        parameters.getPositionalParameterValues()[0] = entry.getLoadedKey();
        parameters.getPositionalParameterTypes()[0] = entry.getLoadedPersister().getKeyType();
    }
    return plan;
}
Also used : FilterQueryPlan(org.hibernate.engine.query.spi.FilterQueryPlan) QueryException(org.hibernate.QueryException) CollectionEntry(org.hibernate.engine.spi.CollectionEntry) CollectionPersister(org.hibernate.persister.collection.CollectionPersister)

Example 17 with QueryException

use of org.hibernate.QueryException in project hibernate-orm by hibernate.

the class CriteriaQueryTranslator method getTypedValue.

/**
	 * Get the a typed value for the given property value.
	 */
@Override
public TypedValue getTypedValue(Criteria subcriteria, String propertyName, Object value) throws HibernateException {
    // Detect discriminator values...
    if (value instanceof Class) {
        final Class entityClass = (Class) value;
        final Queryable q = SessionFactoryHelper.findQueryableUsingImports(sessionFactory, entityClass.getName());
        if (q != null) {
            final Type type = q.getDiscriminatorType();
            String stringValue = q.getDiscriminatorSQLValue();
            if (stringValue != null && stringValue.length() > 2 && stringValue.startsWith("'") && stringValue.endsWith("'")) {
                // remove the single quotes
                stringValue = stringValue.substring(1, stringValue.length() - 1);
            }
            // Convert the string value into the proper type.
            if (type instanceof StringRepresentableType) {
                final StringRepresentableType nullableType = (StringRepresentableType) type;
                value = nullableType.fromStringValue(stringValue);
            } else {
                throw new QueryException("Unsupported discriminator type " + type);
            }
            return new TypedValue(type, value);
        }
    }
    // Otherwise, this is an ordinary value.
    return new TypedValue(getTypeUsingProjection(subcriteria, propertyName), value);
}
Also used : StringRepresentableType(org.hibernate.type.StringRepresentableType) CollectionType(org.hibernate.type.CollectionType) JoinType(org.hibernate.sql.JoinType) AssociationType(org.hibernate.type.AssociationType) Type(org.hibernate.type.Type) QueryException(org.hibernate.QueryException) StringRepresentableType(org.hibernate.type.StringRepresentableType) Queryable(org.hibernate.persister.entity.Queryable) TypedValue(org.hibernate.engine.spi.TypedValue)

Example 18 with QueryException

use of org.hibernate.QueryException in project hibernate-orm by hibernate.

the class SQLQueryParser method resolveCollectionProperties.

private String resolveCollectionProperties(String aliasName, String propertyName) {
    Map fieldResults = context.getPropertyResultsMapByAlias(aliasName);
    SQLLoadableCollection collectionPersister = context.getCollectionPersisterByAlias(aliasName);
    String collectionSuffix = context.getCollectionSuffixByAlias(aliasName);
    if ("*".equals(propertyName)) {
        if (!fieldResults.isEmpty()) {
            throw new QueryException("Using return-propertys together with * syntax is not supported.");
        }
        String selectFragment = collectionPersister.selectFragment(aliasName, collectionSuffix);
        aliasesFound++;
        return selectFragment + ", " + resolveProperties(aliasName, propertyName);
    } else if ("element.*".equals(propertyName)) {
        return resolveProperties(aliasName, "*");
    } else {
        String[] columnAliases;
        // Let return-propertys override whatever the persister has for aliases.
        columnAliases = (String[]) fieldResults.get(propertyName);
        if (columnAliases == null) {
            columnAliases = collectionPersister.getCollectionPropertyColumnAliases(propertyName, collectionSuffix);
        }
        if (columnAliases == null || columnAliases.length == 0) {
            throw new QueryException("No column name found for property [" + propertyName + "] for alias [" + aliasName + "]", originalQueryString);
        }
        if (columnAliases.length != 1) {
            // TODO: better error message since we actually support composites if names are explicitly listed.
            throw new QueryException("SQL queries only support properties mapped to a single column - property [" + propertyName + "] is mapped to " + columnAliases.length + " columns.", originalQueryString);
        }
        aliasesFound++;
        return columnAliases[0];
    }
}
Also used : QueryException(org.hibernate.QueryException) SQLLoadableCollection(org.hibernate.persister.collection.SQLLoadableCollection) Map(java.util.Map) HashMap(java.util.HashMap)

Example 19 with QueryException

use of org.hibernate.QueryException in project hibernate-orm by hibernate.

the class QueryLoader method iterate.

public Iterator iterate(QueryParameters queryParameters, EventSource session) throws HibernateException {
    checkQuery(queryParameters);
    final boolean stats = session.getFactory().getStatistics().isStatisticsEnabled();
    long startTime = 0;
    if (stats) {
        startTime = System.nanoTime();
    }
    try {
        if (queryParameters.isCallable()) {
            throw new QueryException("iterate() not supported for callable statements");
        }
        final SqlStatementWrapper wrapper = executeQueryStatement(queryParameters, false, Collections.emptyList(), session);
        final ResultSet rs = wrapper.getResultSet();
        final PreparedStatement st = (PreparedStatement) wrapper.getStatement();
        final Iterator result = new IteratorImpl(rs, st, session, queryParameters.isReadOnly(session), queryReturnTypes, queryTranslator.getColumnNames(), buildHolderInstantiator(queryParameters.getResultTransformer()));
        if (stats) {
            final long endTime = System.nanoTime();
            final long milliseconds = TimeUnit.MILLISECONDS.convert(endTime - startTime, TimeUnit.NANOSECONDS);
            session.getFactory().getStatistics().queryExecuted(//						"HQL: " + queryTranslator.getQueryString(),
            getQueryIdentifier(), 0, milliseconds);
        }
        return result;
    } catch (SQLException sqle) {
        throw session.getJdbcServices().getSqlExceptionHelper().convert(sqle, "could not execute query using iterate", getSQLString());
    }
}
Also used : QueryException(org.hibernate.QueryException) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) Iterator(java.util.Iterator) PreparedStatement(java.sql.PreparedStatement) IteratorImpl(org.hibernate.internal.IteratorImpl)

Example 20 with QueryException

use of org.hibernate.QueryException in project hibernate-orm by hibernate.

the class ProcedureCallImpl method prepareForNamedParameters.

private void prepareForNamedParameters() {
    if (parameterStrategy == ParameterStrategy.POSITIONAL) {
        throw new QueryException("Cannot mix named and positional parameters");
    }
    if (parameterStrategy == ParameterStrategy.UNKNOWN) {
        // protect to only do this check once
        final ExtractedDatabaseMetaData databaseMetaData = getSession().getJdbcCoordinator().getJdbcSessionOwner().getJdbcSessionContext().getServiceRegistry().getService(JdbcEnvironment.class).getExtractedDatabaseMetaData();
        if (!databaseMetaData.supportsNamedParameters()) {
            LOG.unsupportedNamedParameters();
        }
        parameterStrategy = ParameterStrategy.NAMED;
    }
}
Also used : QueryException(org.hibernate.QueryException) JdbcEnvironment(org.hibernate.engine.jdbc.env.spi.JdbcEnvironment) ExtractedDatabaseMetaData(org.hibernate.engine.jdbc.env.spi.ExtractedDatabaseMetaData)

Aggregations

QueryException (org.hibernate.QueryException)77 Type (org.hibernate.type.Type)20 Test (org.junit.Test)19 Session (org.hibernate.Session)18 Transaction (org.hibernate.Transaction)12 JoinType (org.hibernate.sql.JoinType)12 Queryable (org.hibernate.persister.entity.Queryable)10 CollectionType (org.hibernate.type.CollectionType)10 MappingException (org.hibernate.MappingException)9 QueryableCollection (org.hibernate.persister.collection.QueryableCollection)9 AssociationType (org.hibernate.type.AssociationType)8 HashMap (java.util.HashMap)6 HibernateException (org.hibernate.HibernateException)6 JoinSequence (org.hibernate.engine.internal.JoinSequence)6 EntityType (org.hibernate.type.EntityType)6 AST (antlr.collections.AST)5 Map (java.util.Map)5 SemanticException (antlr.SemanticException)4 ArrayList (java.util.ArrayList)4 FromElement (org.hibernate.hql.internal.ast.tree.FromElement)4