Search in sources :

Example 31 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 32 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)

Example 33 with QueryException

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

the class QueryParameterBindingsImpl method verifyParametersBound.

public void verifyParametersBound(boolean reserveFirstParameter) {
    // verify named parameters bound
    for (Map.Entry<QueryParameter, QueryParameterBinding> bindEntry : parameterBindingMap.entrySet()) {
        if (!bindEntry.getValue().isBound()) {
            if (bindEntry.getKey().getName() != null) {
                throw new QueryException("Named parameter [" + bindEntry.getKey().getName() + "] not set");
            } else {
                throw new QueryException("Parameter memento [" + bindEntry.getKey() + "] not set");
            }
        }
    }
    // verify position parameters bound
    int startIndex = 0;
    if (!parameterMetadata.isOrdinalParametersZeroBased()) {
        startIndex = 1;
    }
    for (int i = startIndex; i < positionalParameterBindings.size(); i++) {
        QueryParameterBinding binding = null;
        if (parameterMetadata.isOrdinalParametersZeroBased()) {
            binding = positionalParameterBindings.get(i);
        } else {
            binding = positionalParameterBindings.get(i - 1);
        }
        if (binding == null || !binding.isBound()) {
            throw new QueryException("Positional parameter [" + i + "] not set");
        }
    }
    // verify position parameter count is correct
    final int positionalValueSpan = calculatePositionalValueSpan(reserveFirstParameter);
    final int positionCounts = parameterMetadata.getPositionalParameterCount();
    if (positionCounts != positionalValueSpan) {
        if (reserveFirstParameter && positionCounts - 1 != positionalValueSpan) {
            throw new QueryException("Expected positional parameter count: " + (positionCounts - 1) + ", actually detected " + positionalValueSpan);
        } else if (!reserveFirstParameter) {
            throw new QueryException("Expected positional parameter count: " + (positionCounts) + ", actually detected " + positionalValueSpan);
        }
    }
}
Also used : QueryParameter(org.hibernate.query.QueryParameter) QueryException(org.hibernate.QueryException) QueryParameterBinding(org.hibernate.query.spi.QueryParameterBinding) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap)

Example 34 with QueryException

use of org.hibernate.QueryException in project ACS by ACS-Community.

the class TestPojosPersistence method testCriteriaAPI.

public void testCriteriaAPI() throws Exception {
    createDB();
    try {
        createConfigurationComputerAndTwoNetworkDevices();
        Configuration config = (Configuration) hibernateUtil.getList(Configuration.class).iterator().next();
        assertNotNull(config);
        // Now we test that using the criteria API we can find our objects
        Criteria c = hibernateUtil.getSession().createCriteria(NetworkDevice.class);
        c.add(Restrictions.eq("name", "wall-e"));
        assertEquals(2, c.list().size());
        c = hibernateUtil.getSession().createCriteria(NetworkDevice.class);
        c.add(Restrictions.eq("name", "wall-e"));
        c.add(Restrictions.eq("networkName", "wall-e.eso.org"));
        assertEquals(1, c.list().size());
        c = hibernateUtil.getSession().createCriteria(NetworkDevice.class);
        c.add(Restrictions.eq("configuration", config));
        assertEquals(3, c.list().size());
        c = hibernateUtil.getSession().createCriteria(Configuration.class);
        c.add(Restrictions.eq("configurationName", "rtobarConfig"));
        c.add(Restrictions.lt("creationTime", new Date()));
        assertEquals(1, c.list().size());
        try {
            c = hibernateUtil.getSession().createCriteria(Configuration.class);
            // typo: should be configurationName
            c.add(Restrictions.eq("configuratioName", "rtobarConfig"));
            c.list();
            fail("Should fail, property 'configuratioName' doesn't exist for Configuration objects");
        } catch (QueryException e) {
        }
    } finally {
        dropDB();
    }
}
Also used : QueryException(org.hibernate.QueryException) Criteria(org.hibernate.Criteria) Date(java.util.Date)

Example 35 with QueryException

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

the class IndexNode method resolve.

@Override
public void resolve(boolean generateJoin, boolean implicitJoin, String classAlias, AST parent, AST parentPredicate) throws SemanticException {
    if (isResolved()) {
        return;
    }
    FromReferenceNode collectionNode = (FromReferenceNode) getFirstChild();
    SessionFactoryHelper sessionFactoryHelper = getSessionFactoryHelper();
    // Fully resolve the map reference, create implicit joins.
    collectionNode.resolveIndex(this);
    Type type = collectionNode.getDataType();
    if (!type.isCollectionType()) {
        throw new SemanticException("The [] operator cannot be applied to type " + type.toString());
    }
    String collectionRole = ((CollectionType) type).getRole();
    QueryableCollection queryableCollection = sessionFactoryHelper.requireQueryableCollection(collectionRole);
    if (!queryableCollection.hasIndex()) {
        throw new QueryException("unindexed fromElement beforeQuery []: " + collectionNode.getPath());
    }
    // Generate the inner join -- The elements need to be joined to the collection they are in.
    FromElement fromElement = collectionNode.getFromElement();
    String elementTable = fromElement.getTableAlias();
    FromClause fromClause = fromElement.getFromClause();
    String path = collectionNode.getPath();
    FromElement elem = fromClause.findCollectionJoin(path);
    if (elem == null) {
        FromElementFactory factory = new FromElementFactory(fromClause, fromElement, path);
        elem = factory.createCollectionElementsJoin(queryableCollection, elementTable);
        LOG.debugf("No FROM element found for the elements of collection join path %s, created %s", path, elem);
    } else {
        LOG.debugf("FROM element found for collection join path %s", path);
    }
    // The 'from element' that represents the elements of the collection.
    setFromElement(fromElement);
    // Add the condition to the join sequence that qualifies the indexed element.
    AST selector = collectionNode.getNextSibling();
    if (selector == null) {
        throw new QueryException("No index value!");
    }
    // Sometimes use the element table alias, sometimes use the... umm... collection table alias (many to many)
    String collectionTableAlias = elementTable;
    if (elem.getCollectionTableAlias() != null) {
        collectionTableAlias = elem.getCollectionTableAlias();
    }
    // TODO: get SQL rendering out of here, create an AST for the join expressions.
    // Use the SQL generator grammar to generate the SQL text for the index expression.
    JoinSequence joinSequence = fromElement.getJoinSequence();
    String[] indexCols = queryableCollection.getIndexColumnNames();
    if (indexCols.length != 1) {
        throw new QueryException("composite-index appears in []: " + collectionNode.getPath());
    }
    SqlGenerator gen = new SqlGenerator(getSessionFactoryHelper().getFactory());
    try {
        //TODO: used to be exprNoParens! was this needed?
        gen.simpleExpr(selector);
    } catch (RecognitionException e) {
        throw new QueryException(e.getMessage(), e);
    }
    String selectorExpression = gen.getSQL();
    joinSequence.addCondition(collectionTableAlias + '.' + indexCols[0] + " = " + selectorExpression);
    List<ParameterSpecification> paramSpecs = gen.getCollectedParameters();
    if (paramSpecs != null) {
        switch(paramSpecs.size()) {
            case 0:
                // nothing to do
                break;
            case 1:
                ParameterSpecification paramSpec = paramSpecs.get(0);
                paramSpec.setExpectedType(queryableCollection.getIndexType());
                fromElement.setIndexCollectionSelectorParamSpec(paramSpec);
                break;
            default:
                fromElement.setIndexCollectionSelectorParamSpec(new AggregatedIndexCollectionSelectorParameterSpecifications(paramSpecs));
                break;
        }
    }
    // Now, set the text for this node.  It should be the element columns.
    String[] elementColumns = queryableCollection.getElementColumnNames(elementTable);
    setText(elementColumns[0]);
    setResolved();
}
Also used : AST(antlr.collections.AST) ParameterSpecification(org.hibernate.param.ParameterSpecification) SessionFactoryHelper(org.hibernate.hql.internal.ast.util.SessionFactoryHelper) QueryableCollection(org.hibernate.persister.collection.QueryableCollection) CollectionType(org.hibernate.type.CollectionType) Type(org.hibernate.type.Type) QueryException(org.hibernate.QueryException) SqlGenerator(org.hibernate.hql.internal.ast.SqlGenerator) CollectionType(org.hibernate.type.CollectionType) JoinSequence(org.hibernate.engine.internal.JoinSequence) RecognitionException(antlr.RecognitionException) SemanticException(antlr.SemanticException)

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