Search in sources :

Example 11 with RowSelection

use of org.hibernate.engine.spi.RowSelection in project hibernate-orm by hibernate.

the class NativeSQLQueryPlan method performExecuteUpdate.

/**
 * Performs the execute query
 *
 * @param queryParameters The query parameters
 * @param session The session
 *
 * @return The number of affected rows as returned by the JDBC driver
 *
 * @throws HibernateException Indicates a problem performing the query execution
 */
public int performExecuteUpdate(QueryParameters queryParameters, SharedSessionContractImplementor session) throws HibernateException {
    coordinateSharedCacheCleanup(session);
    if (queryParameters.isCallable()) {
        throw new IllegalArgumentException("callable not yet supported for native queries");
    }
    int result = 0;
    PreparedStatement ps;
    RowSelection selection = queryParameters.getRowSelection();
    try {
        queryParameters.processFilters(this.customQuery.getSQL(), session);
        final String sql = session.getJdbcServices().getDialect().addSqlHintOrComment(queryParameters.getFilteredSQL(), queryParameters, session.getFactory().getSessionFactoryOptions().isCommentsEnabled());
        ps = session.getJdbcCoordinator().getStatementPreparer().prepareStatement(sql, false);
        try {
            int col = 1;
            for (ParameterBinder binder : this.customQuery.getParameterValueBinders()) {
                col += binder.bind(ps, queryParameters, session, col);
            }
            if (selection != null && selection.getTimeout() != null) {
                ps.setQueryTimeout(selection.getTimeout());
            }
            result = session.getJdbcCoordinator().getResultSetReturn().executeUpdate(ps);
        } finally {
            if (ps != null) {
                session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release(ps);
                session.getJdbcCoordinator().afterStatementExecution();
            }
        }
    } catch (SQLException sqle) {
        throw session.getFactory().getSQLExceptionHelper().convert(sqle, "could not execute native bulk manipulation query", this.sourceQuery);
    }
    return result;
}
Also used : ParameterBinder(org.hibernate.param.ParameterBinder) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) RowSelection(org.hibernate.engine.spi.RowSelection)

Example 12 with RowSelection

use of org.hibernate.engine.spi.RowSelection in project hibernate-orm by hibernate.

the class CriteriaQueryTranslator method getQueryParameters.

public QueryParameters getQueryParameters() {
    final RowSelection selection = new RowSelection();
    selection.setFirstRow(rootCriteria.getFirstResult());
    selection.setMaxRows(rootCriteria.getMaxResults());
    selection.setTimeout(rootCriteria.getTimeout());
    selection.setFetchSize(rootCriteria.getFetchSize());
    final LockOptions lockOptions = new LockOptions();
    final Map<String, LockMode> lockModeMap = rootCriteria.getLockModes();
    for (final String key : lockModeMap.keySet()) {
        final Criteria subcriteria = getAliasedCriteria(key);
        lockOptions.setAliasSpecificLockMode(getSQLAlias(subcriteria), lockModeMap.get(key));
    }
    final List<Object> values = new ArrayList<Object>();
    final List<Type> types = new ArrayList<Type>();
    final Iterator<CriteriaImpl.Subcriteria> subcriteriaIterator = rootCriteria.iterateSubcriteria();
    while (subcriteriaIterator.hasNext()) {
        final CriteriaImpl.Subcriteria subcriteria = subcriteriaIterator.next();
        final LockMode lm = subcriteria.getLockMode();
        if (lm != null) {
            lockOptions.setAliasSpecificLockMode(getSQLAlias(subcriteria), lm);
        }
        if (subcriteria.getWithClause() != null) {
            final TypedValue[] tv = subcriteria.getWithClause().getTypedValues(subcriteria, this);
            for (TypedValue aTv : tv) {
                values.add(aTv.getValue());
                types.add(aTv.getType());
            }
        }
    }
    // Type and value gathering for the WHERE clause needs to come AFTER lock mode gathering,
    // because the lock mode gathering loop now contains join clauses which can contain
    // parameter bindings (as in the HQL WITH clause).
    final Iterator<CriteriaImpl.CriterionEntry> iter = rootCriteria.iterateExpressionEntries();
    while (iter.hasNext()) {
        final CriteriaImpl.CriterionEntry ce = iter.next();
        final TypedValue[] tv = ce.getCriterion().getTypedValues(ce.getCriteria(), this);
        for (TypedValue aTv : tv) {
            values.add(aTv.getValue());
            types.add(aTv.getType());
        }
    }
    final Object[] valueArray = values.toArray();
    final Type[] typeArray = ArrayHelper.toTypeArray(types);
    return new QueryParameters(typeArray, valueArray, lockOptions, selection, rootCriteria.isReadOnlyInitialized(), (rootCriteria.isReadOnlyInitialized() && rootCriteria.isReadOnly()), rootCriteria.getCacheable(), rootCriteria.getCacheRegion(), rootCriteria.getComment(), rootCriteria.getQueryHints(), rootCriteria.isLookupByNaturalKey(), rootCriteria.getResultTransformer());
}
Also used : LockOptions(org.hibernate.LockOptions) CriteriaImpl(org.hibernate.internal.CriteriaImpl) ArrayList(java.util.ArrayList) LockMode(org.hibernate.LockMode) Criteria(org.hibernate.Criteria) QueryParameters(org.hibernate.engine.spi.QueryParameters) RowSelection(org.hibernate.engine.spi.RowSelection) 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) TypedValue(org.hibernate.engine.spi.TypedValue)

Example 13 with RowSelection

use of org.hibernate.engine.spi.RowSelection in project hibernate-orm by hibernate.

the class InformixLimitHandlerTestCase method toRowSelection.

private RowSelection toRowSelection(int firstRow, int maxRows) {
    RowSelection selection = new RowSelection();
    selection.setFirstRow(firstRow);
    selection.setMaxRows(maxRows);
    return selection;
}
Also used : RowSelection(org.hibernate.engine.spi.RowSelection)

Example 14 with RowSelection

use of org.hibernate.engine.spi.RowSelection in project hibernate-orm by hibernate.

the class ResultSetProcessorImpl method extractResults.

@Override
public List extractResults(ResultSet resultSet, final SharedSessionContractImplementor session, QueryParameters queryParameters, NamedParameterContext namedParameterContext, boolean returnProxies, boolean readOnly, ResultTransformer forcedResultTransformer, List<AfterLoadAction> afterLoadActionList) throws SQLException {
    handlePotentiallyEmptyCollectionRootReturns(loadPlan, queryParameters.getCollectionKeys(), resultSet, session);
    final int maxRows;
    final RowSelection selection = queryParameters.getRowSelection();
    if (LimitHelper.hasMaxRows(selection)) {
        maxRows = selection.getMaxRows();
        LOG.tracef("Limiting ResultSet processing to just %s rows", maxRows);
    } else {
        maxRows = Integer.MAX_VALUE;
    }
    // Handles the "FETCH ALL PROPERTIES" directive in HQL
    final boolean forceFetchLazyAttributes = false;
    final ResultSetProcessingContextImpl context = new ResultSetProcessingContextImpl(resultSet, session, loadPlan, aliasResolutionContext, readOnly, shouldUseOptionalEntityInstance, forceFetchLazyAttributes, returnProxies, queryParameters, namedParameterContext, hadSubselectFetches);
    final List loadResults = new ArrayList();
    LOG.trace("Processing result set");
    int count;
    for (count = 0; count < maxRows && resultSet.next(); count++) {
        LOG.debugf("Starting ResultSet row #%s", count);
        Object logicalRow = rowReader.readRow(resultSet, context);
        // todo : apply transformers here?
        loadResults.add(logicalRow);
        context.finishUpRow();
    }
    LOG.tracev("Done processing result set ({0} rows)", count);
    rowReader.finishUp(context, afterLoadActionList);
    context.wrapUp();
    session.getPersistenceContext().initializeNonLazyCollections();
    return loadResults;
}
Also used : ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) RowSelection(org.hibernate.engine.spi.RowSelection)

Example 15 with RowSelection

use of org.hibernate.engine.spi.RowSelection in project hibernate-orm by hibernate.

the class HQLQueryPlan method performList.

/**
 * Coordinates the efforts to perform a list across all the included query translators.
 *
 * @param queryParameters The query parameters
 * @param session The session
 *
 * @return The query result list
 *
 * @throws HibernateException Indicates a problem performing the query
 */
@SuppressWarnings("unchecked")
public List performList(QueryParameters queryParameters, SharedSessionContractImplementor session) throws HibernateException {
    if (traceEnabled) {
        LOG.tracev("Find: {0}", getSourceQuery());
        queryParameters.traceParameters(session.getFactory());
    }
    final RowSelection rowSelection = queryParameters.getRowSelection();
    final boolean hasLimit = rowSelection != null && rowSelection.definesLimits();
    final boolean needsLimit = hasLimit && translators.length > 1;
    final QueryParameters queryParametersToUse;
    if (needsLimit) {
        LOG.needsLimit();
        final RowSelection selection = new RowSelection();
        selection.setFetchSize(queryParameters.getRowSelection().getFetchSize());
        selection.setTimeout(queryParameters.getRowSelection().getTimeout());
        queryParametersToUse = queryParameters.createCopyUsing(selection);
    } else {
        queryParametersToUse = queryParameters;
    }
    // fast path to avoid unnecessary allocation and copying
    if (translators.length == 1) {
        return translators[0].list(session, queryParametersToUse);
    }
    final int guessedResultSize = guessResultSize(rowSelection);
    final List combinedResults = new ArrayList(guessedResultSize);
    final IdentitySet distinction;
    if (needsLimit) {
        distinction = new IdentitySet(guessedResultSize);
    } else {
        distinction = null;
    }
    int includedCount = -1;
    translator_loop: for (QueryTranslator translator : translators) {
        final List tmp = translator.list(session, queryParametersToUse);
        if (needsLimit) {
            // NOTE : firstRow is zero-based
            final int first = queryParameters.getRowSelection().getFirstRow() == null ? 0 : queryParameters.getRowSelection().getFirstRow();
            final int max = queryParameters.getRowSelection().getMaxRows() == null ? -1 : queryParameters.getRowSelection().getMaxRows();
            for (final Object result : tmp) {
                if (!distinction.add(result)) {
                    continue;
                }
                includedCount++;
                if (includedCount < first) {
                    continue;
                }
                combinedResults.add(result);
                if (max >= 0 && includedCount > max) {
                    // break the outer loop !!!
                    break translator_loop;
                }
            }
        } else {
            combinedResults.addAll(tmp);
        }
    }
    return combinedResults;
}
Also used : IdentitySet(org.hibernate.internal.util.collections.IdentitySet) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) QueryParameters(org.hibernate.engine.spi.QueryParameters) RowSelection(org.hibernate.engine.spi.RowSelection) QueryTranslator(org.hibernate.hql.spi.QueryTranslator)

Aggregations

RowSelection (org.hibernate.engine.spi.RowSelection)19 PreparedStatement (java.sql.PreparedStatement)5 ArrayList (java.util.ArrayList)5 SQLException (java.sql.SQLException)4 CallableStatement (java.sql.CallableStatement)3 List (java.util.List)3 HibernateException (org.hibernate.HibernateException)3 LockOptions (org.hibernate.LockOptions)3 QueryParameters (org.hibernate.engine.spi.QueryParameters)3 TestForIssue (org.hibernate.testing.TestForIssue)3 Test (org.junit.Test)3 SQLQuery (org.hibernate.SQLQuery)2 ScrollMode (org.hibernate.ScrollMode)2 Dialect (org.hibernate.dialect.Dialect)2 LimitHandler (org.hibernate.dialect.pagination.LimitHandler)2 TypedValue (org.hibernate.engine.spi.TypedValue)2 IdentitySet (org.hibernate.internal.util.collections.IdentitySet)2 Type (org.hibernate.type.Type)2 ResultSet (java.sql.ResultSet)1 Statement (java.sql.Statement)1