Search in sources :

Example 1 with QueryOptions

use of org.hibernate.query.spi.QueryOptions in project hibernate-orm by hibernate.

the class DeferredResultSetAccess method executeQuery.

private void executeQuery() {
    final LogicalConnectionImplementor logicalConnection = getPersistenceContext().getJdbcCoordinator().getLogicalConnection();
    final QueryOptions queryOptions = executionContext.getQueryOptions();
    try {
        LOG.tracef("Executing query to retrieve ResultSet : %s", finalSql);
        // prepare the query
        preparedStatement = statementCreator.apply(finalSql);
        // set options
        if (queryOptions != null) {
            if (queryOptions.getFetchSize() != null) {
                preparedStatement.setFetchSize(queryOptions.getFetchSize());
            }
            if (queryOptions.getTimeout() != null) {
                preparedStatement.setQueryTimeout(queryOptions.getTimeout());
            }
        }
        // bind parameters
        // todo : validate that all query parameters were bound?
        int paramBindingPosition = 1;
        paramBindingPosition += limitHandler.bindLimitParametersAtStartOfQuery(limit, preparedStatement, paramBindingPosition);
        for (JdbcParameterBinder parameterBinder : jdbcSelect.getParameterBinders()) {
            parameterBinder.bindParameterValue(preparedStatement, paramBindingPosition++, jdbcParameterBindings, executionContext);
        }
        paramBindingPosition += limitHandler.bindLimitParametersAtEndOfQuery(limit, preparedStatement, paramBindingPosition);
        if (!jdbcSelect.usesLimitParameters() && limit != null && limit.getMaxRows() != null) {
            limitHandler.setMaxRows(limit, preparedStatement);
        } else {
            final int maxRows = jdbcSelect.getMaxRows();
            if (maxRows != Integer.MAX_VALUE) {
                preparedStatement.setMaxRows(maxRows);
            }
        }
        final SessionEventListenerManager eventListenerManager = executionContext.getSession().getEventListenerManager();
        long executeStartNanos = 0;
        if (this.sqlStatementLogger.getLogSlowQuery() > 0) {
            executeStartNanos = System.nanoTime();
        }
        try {
            eventListenerManager.jdbcExecuteStatementStart();
            resultSet = wrapResultSet(preparedStatement.executeQuery());
        } finally {
            eventListenerManager.jdbcExecuteStatementEnd();
            sqlStatementLogger.logSlowQuery(preparedStatement, executeStartNanos);
        }
        // For dialects that don't support an offset clause
        final int rowsToSkip;
        if (!jdbcSelect.usesLimitParameters() && limit != null && limit.getFirstRow() != null && !limitHandler.supportsLimitOffset()) {
            rowsToSkip = limit.getFirstRow();
        } else {
            rowsToSkip = jdbcSelect.getRowsToSkip();
        }
        if (rowsToSkip != 0) {
            try {
                resultSet.absolute(rowsToSkip);
            } catch (SQLException ex) {
                // To avoid throwing a wrong exception in case this was some other error, check if we can advance to next
                try {
                    resultSet.next();
                } catch (SQLException ex2) {
                    throw ex;
                }
                // Traverse to the actual row
                for (int i = 1; i < rowsToSkip && resultSet.next(); i++) {
                }
            }
        }
        logicalConnection.getResourceRegistry().register(resultSet, preparedStatement);
    } catch (SQLException e) {
        throw executionContext.getSession().getJdbcServices().getSqlExceptionHelper().convert(e, "JDBC exception executing SQL [" + finalSql + "]");
    } finally {
        logicalConnection.afterStatement();
    }
}
Also used : SQLException(java.sql.SQLException) LogicalConnectionImplementor(org.hibernate.resource.jdbc.spi.LogicalConnectionImplementor) JdbcParameterBinder(org.hibernate.sql.exec.spi.JdbcParameterBinder) QueryOptions(org.hibernate.query.spi.QueryOptions) SessionEventListenerManager(org.hibernate.engine.spi.SessionEventListenerManager)

Example 2 with QueryOptions

use of org.hibernate.query.spi.QueryOptions in project hibernate-orm by hibernate.

the class JdbcSelectExecutorStandardImpl method getScrollContext.

/*
		When `Query#scroll()` is call the query is not executed immediately, a new ExecutionContext with the values of the `persistenceContext.isDefaultReadOnly()` and of the `queryOptions.isReadOnly()`
		set at the moment of the Query#scroll() call is created in order to use it when the query will be executed.
	 */
private ExecutionContext getScrollContext(ExecutionContext context, PersistenceContext persistenceContext) {
    final QueryOptions queryOptions = context.getQueryOptions();
    final Boolean readOnly;
    if (queryOptions.isReadOnly() == null) {
        readOnly = persistenceContext.isDefaultReadOnly();
    } else {
        readOnly = queryOptions.isReadOnly();
    }
    final Integer timeout = queryOptions.getTimeout();
    final FlushMode flushMode = queryOptions.getFlushMode();
    final AppliedGraph appliedGraph = queryOptions.getAppliedGraph();
    final TupleTransformer<?> tupleTransformer = queryOptions.getTupleTransformer();
    final ResultListTransformer<?> resultListTransformer = queryOptions.getResultListTransformer();
    final Boolean resultCachingEnabled = queryOptions.isResultCachingEnabled();
    final CacheRetrieveMode cacheRetrieveMode = queryOptions.getCacheRetrieveMode();
    final CacheStoreMode cacheStoreMode = queryOptions.getCacheStoreMode();
    final String resultCacheRegionName = queryOptions.getResultCacheRegionName();
    final LockOptions lockOptions = queryOptions.getLockOptions();
    final String comment = queryOptions.getComment();
    final List<String> databaseHints = queryOptions.getDatabaseHints();
    final Integer fetchSize = queryOptions.getFetchSize();
    final Limit limit = queryOptions.getLimit();
    return new ExecutionContext() {

        @Override
        public QueryOptions getQueryOptions() {
            return new QueryOptions() {

                @Override
                public Integer getTimeout() {
                    return timeout;
                }

                @Override
                public FlushMode getFlushMode() {
                    return flushMode;
                }

                @Override
                public Boolean isReadOnly() {
                    return readOnly;
                }

                @Override
                public AppliedGraph getAppliedGraph() {
                    return appliedGraph;
                }

                @Override
                public TupleTransformer<?> getTupleTransformer() {
                    return tupleTransformer;
                }

                @Override
                public ResultListTransformer<?> getResultListTransformer() {
                    return resultListTransformer;
                }

                @Override
                public Boolean isResultCachingEnabled() {
                    return resultCachingEnabled;
                }

                @Override
                public CacheRetrieveMode getCacheRetrieveMode() {
                    return cacheRetrieveMode;
                }

                @Override
                public CacheStoreMode getCacheStoreMode() {
                    return cacheStoreMode;
                }

                @Override
                public String getResultCacheRegionName() {
                    return resultCacheRegionName;
                }

                @Override
                public LockOptions getLockOptions() {
                    return lockOptions;
                }

                @Override
                public String getComment() {
                    return comment;
                }

                @Override
                public List<String> getDatabaseHints() {
                    return databaseHints;
                }

                @Override
                public Integer getFetchSize() {
                    return fetchSize;
                }

                @Override
                public Limit getLimit() {
                    return limit;
                }
            };
        }

        @Override
        public QueryParameterBindings getQueryParameterBindings() {
            return context.getQueryParameterBindings();
        }

        @Override
        public Callback getCallback() {
            return context.getCallback();
        }

        @Override
        public SharedSessionContractImplementor getSession() {
            return context.getSession();
        }
    };
}
Also used : CacheRetrieveMode(jakarta.persistence.CacheRetrieveMode) LockOptions(org.hibernate.LockOptions) CacheStoreMode(jakarta.persistence.CacheStoreMode) QueryOptions(org.hibernate.query.spi.QueryOptions) AppliedGraph(org.hibernate.graph.spi.AppliedGraph) FlushMode(org.hibernate.FlushMode) ExecutionContext(org.hibernate.sql.exec.spi.ExecutionContext) Limit(org.hibernate.query.spi.Limit)

Example 3 with QueryOptions

use of org.hibernate.query.spi.QueryOptions in project hibernate-orm by hibernate.

the class StandardJdbcMutationExecutor method execute.

@Override
public int execute(JdbcMutation jdbcMutation, JdbcParameterBindings jdbcParameterBindings, Function<String, PreparedStatement> statementCreator, BiConsumer<Integer, PreparedStatement> expectationCheck, ExecutionContext executionContext) {
    final SharedSessionContractImplementor session = executionContext.getSession();
    session.autoFlushIfRequired(jdbcMutation.getAffectedTableNames());
    final LogicalConnectionImplementor logicalConnection = session.getJdbcCoordinator().getLogicalConnection();
    final JdbcServices jdbcServices = session.getJdbcServices();
    final QueryOptions queryOptions = executionContext.getQueryOptions();
    final String finalSql;
    if (queryOptions == null) {
        finalSql = jdbcMutation.getSql();
    } else {
        finalSql = jdbcServices.getDialect().addSqlHintOrComment(jdbcMutation.getSql(), queryOptions, executionContext.getSession().getFactory().getSessionFactoryOptions().isCommentsEnabled());
    }
    try {
        // prepare the query
        final PreparedStatement preparedStatement = statementCreator.apply(finalSql);
        try {
            if (executionContext.getQueryOptions().getTimeout() != null) {
                preparedStatement.setQueryTimeout(executionContext.getQueryOptions().getTimeout());
            }
            // bind parameters
            // todo : validate that all query parameters were bound?
            int paramBindingPosition = 1;
            for (JdbcParameterBinder parameterBinder : jdbcMutation.getParameterBinders()) {
                parameterBinder.bindParameterValue(preparedStatement, paramBindingPosition++, jdbcParameterBindings, executionContext);
            }
            session.getEventListenerManager().jdbcExecuteStatementStart();
            try {
                int rows = preparedStatement.executeUpdate();
                expectationCheck.accept(rows, preparedStatement);
                return rows;
            } finally {
                session.getEventListenerManager().jdbcExecuteStatementEnd();
            }
        } finally {
            logicalConnection.getResourceRegistry().release(preparedStatement);
        }
    } catch (SQLException e) {
        throw jdbcServices.getSqlExceptionHelper().convert(e, "JDBC exception executing SQL [" + finalSql + "]");
    } finally {
        executionContext.afterStatement(logicalConnection);
    }
}
Also used : SQLException(java.sql.SQLException) LogicalConnectionImplementor(org.hibernate.resource.jdbc.spi.LogicalConnectionImplementor) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) JdbcServices(org.hibernate.engine.jdbc.spi.JdbcServices) PreparedStatement(java.sql.PreparedStatement) JdbcParameterBinder(org.hibernate.sql.exec.spi.JdbcParameterBinder) QueryOptions(org.hibernate.query.spi.QueryOptions)

Example 4 with QueryOptions

use of org.hibernate.query.spi.QueryOptions in project hibernate-orm by hibernate.

the class SingleIdLoadPlan method load.

public T load(Object restrictedValue, Object entityInstance, Boolean readOnly, Boolean singleResultExpected, SharedSessionContractImplementor session) {
    final int jdbcTypeCount = restrictivePart.getJdbcTypeCount();
    assert jdbcParameters.size() % jdbcTypeCount == 0;
    final JdbcParameterBindings jdbcParameterBindings = new JdbcParameterBindingsImpl(jdbcTypeCount);
    jdbcSelect.bindFilterJdbcParameters(jdbcParameterBindings);
    int offset = 0;
    while (offset < jdbcParameters.size()) {
        offset += jdbcParameterBindings.registerParametersForEachJdbcValue(restrictedValue, Clause.WHERE, offset, restrictivePart, jdbcParameters, session);
    }
    assert offset == jdbcParameters.size();
    final QueryOptions queryOptions = new SimpleQueryOptions(lockOptions, readOnly);
    final Callback callback = new CallbackImpl();
    final List<T> list = JdbcSelectExecutorStandardImpl.INSTANCE.list(jdbcSelect, jdbcParameterBindings, new ExecutionContext() {

        @Override
        public SharedSessionContractImplementor getSession() {
            return session;
        }

        @Override
        public Object getEntityInstance() {
            return entityInstance;
        }

        @Override
        public Object getEntityId() {
            return restrictedValue;
        }

        @Override
        public QueryOptions getQueryOptions() {
            return queryOptions;
        }

        @Override
        public String getQueryIdentifier(String sql) {
            return sql;
        }

        @Override
        public QueryParameterBindings getQueryParameterBindings() {
            return QueryParameterBindings.NO_PARAM_BINDINGS;
        }

        @Override
        public Callback getCallback() {
            return callback;
        }
    }, getRowTransformer(), singleResultExpected ? ListResultsConsumer.UniqueSemantic.ASSERT : ListResultsConsumer.UniqueSemantic.FILTER);
    if (list.isEmpty()) {
        return null;
    }
    final T entity = list.get(0);
    if (persister != null) {
        callback.invokeAfterLoadActions(session, entity, persister);
    }
    return entity;
}
Also used : CallbackImpl(org.hibernate.sql.exec.internal.CallbackImpl) JdbcParameterBindingsImpl(org.hibernate.sql.exec.internal.JdbcParameterBindingsImpl) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) QueryOptions(org.hibernate.query.spi.QueryOptions) SimpleQueryOptions(org.hibernate.query.internal.SimpleQueryOptions) Callback(org.hibernate.sql.exec.spi.Callback) ExecutionContext(org.hibernate.sql.exec.spi.ExecutionContext) SimpleQueryOptions(org.hibernate.query.internal.SimpleQueryOptions) QueryParameterBindings(org.hibernate.query.spi.QueryParameterBindings) JdbcParameterBindings(org.hibernate.sql.exec.spi.JdbcParameterBindings)

Example 5 with QueryOptions

use of org.hibernate.query.spi.QueryOptions in project hibernate-orm by hibernate.

the class SingleUniqueKeyEntityLoaderStandard method resolveId.

@Override
public Object resolveId(Object ukValue, SharedSessionContractImplementor session) {
    final SessionFactoryImplementor sessionFactory = session.getFactory();
    // todo (6.0) : cache the SQL AST and JdbcParameters
    final List<JdbcParameter> jdbcParameters = new ArrayList<>();
    final SelectStatement sqlAst = LoaderSelectBuilder.createSelectByUniqueKey(entityDescriptor, Collections.singletonList(entityDescriptor.getIdentifierMapping()), uniqueKeyAttribute, null, 1, LoadQueryInfluencers.NONE, LockOptions.NONE, jdbcParameters::add, sessionFactory);
    final JdbcServices jdbcServices = sessionFactory.getJdbcServices();
    final JdbcEnvironment jdbcEnvironment = jdbcServices.getJdbcEnvironment();
    final SqlAstTranslatorFactory sqlAstTranslatorFactory = jdbcEnvironment.getSqlAstTranslatorFactory();
    final JdbcParameterBindings jdbcParameterBindings = new JdbcParameterBindingsImpl(jdbcParameters.size());
    int offset = jdbcParameterBindings.registerParametersForEachJdbcValue(ukValue, Clause.WHERE, uniqueKeyAttribute, jdbcParameters, session);
    assert offset == jdbcParameters.size();
    final JdbcSelect jdbcSelect = sqlAstTranslatorFactory.buildSelectTranslator(sessionFactory, sqlAst).translate(jdbcParameterBindings, QueryOptions.NONE);
    final List<Object> list = sessionFactory.getJdbcServices().getJdbcSelectExecutor().list(jdbcSelect, jdbcParameterBindings, new ExecutionContext() {

        @Override
        public SharedSessionContractImplementor getSession() {
            return session;
        }

        @Override
        public QueryOptions getQueryOptions() {
            return QueryOptions.NONE;
        }

        @Override
        public String getQueryIdentifier(String sql) {
            return sql;
        }

        @Override
        public QueryParameterBindings getQueryParameterBindings() {
            return QueryParameterBindings.NO_PARAM_BINDINGS;
        }

        @Override
        public Callback getCallback() {
            throw new UnsupportedOperationException("Follow-on locking not supported yet");
        }
    }, row -> row[0], ListResultsConsumer.UniqueSemantic.FILTER);
    assert list.size() == 1;
    return list.get(0);
}
Also used : JdbcSelect(org.hibernate.sql.exec.spi.JdbcSelect) JdbcParameterBindingsImpl(org.hibernate.sql.exec.internal.JdbcParameterBindingsImpl) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) JdbcParameter(org.hibernate.sql.ast.tree.expression.JdbcParameter) ArrayList(java.util.ArrayList) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) JdbcServices(org.hibernate.engine.jdbc.spi.JdbcServices) JdbcEnvironment(org.hibernate.engine.jdbc.env.spi.JdbcEnvironment) QueryOptions(org.hibernate.query.spi.QueryOptions) SqlAstTranslatorFactory(org.hibernate.sql.ast.SqlAstTranslatorFactory) SelectStatement(org.hibernate.sql.ast.tree.select.SelectStatement) ExecutionContext(org.hibernate.sql.exec.spi.ExecutionContext) Callback(org.hibernate.sql.exec.spi.Callback) QueryParameterBindings(org.hibernate.query.spi.QueryParameterBindings) JdbcParameterBindings(org.hibernate.sql.exec.spi.JdbcParameterBindings)

Aggregations

QueryOptions (org.hibernate.query.spi.QueryOptions)17 SharedSessionContractImplementor (org.hibernate.engine.spi.SharedSessionContractImplementor)13 ExecutionContext (org.hibernate.sql.exec.spi.ExecutionContext)13 QueryParameterBindings (org.hibernate.query.spi.QueryParameterBindings)12 Callback (org.hibernate.sql.exec.spi.Callback)12 JdbcServices (org.hibernate.engine.jdbc.spi.JdbcServices)11 JdbcParameterBindingsImpl (org.hibernate.sql.exec.internal.JdbcParameterBindingsImpl)11 JdbcParameterBindings (org.hibernate.sql.exec.spi.JdbcParameterBindings)11 JdbcEnvironment (org.hibernate.engine.jdbc.env.spi.JdbcEnvironment)10 SqlAstTranslatorFactory (org.hibernate.sql.ast.SqlAstTranslatorFactory)10 JdbcSelect (org.hibernate.sql.exec.spi.JdbcSelect)10 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)8 ArrayList (java.util.ArrayList)7 HibernateException (org.hibernate.HibernateException)5 JdbcParameter (org.hibernate.sql.ast.tree.expression.JdbcParameter)5 SelectStatement (org.hibernate.sql.ast.tree.select.SelectStatement)5 EntityKey (org.hibernate.engine.spi.EntityKey)4 SubselectFetch (org.hibernate.engine.spi.SubselectFetch)4 LoadingEntityEntry (org.hibernate.sql.results.graph.entity.LoadingEntityEntry)4 CollectionKey (org.hibernate.engine.spi.CollectionKey)3