use of org.hibernate.sql.exec.spi.JdbcSelect in project hibernate-orm by hibernate.
the class AbstractNaturalIdLoader method selectByNaturalId.
/**
* Perform a select, restricted by natural-id, based on `domainResultProducer` and `fetchProcessor`
*/
protected <L> L selectByNaturalId(Object bindValue, NaturalIdLoadOptions options, BiFunction<TableGroup, LoaderSqlAstCreationState, DomainResult<?>> domainResultProducer, LoaderSqlAstCreationState.FetchProcessor fetchProcessor, Function<Boolean, Long> statementStartHandler, BiConsumer<Object, Long> statementCompletionHandler, SharedSessionContractImplementor session) {
final SessionFactoryImplementor sessionFactory = session.getFactory();
final JdbcServices jdbcServices = sessionFactory.getJdbcServices();
final JdbcEnvironment jdbcEnvironment = jdbcServices.getJdbcEnvironment();
final SqlAstTranslatorFactory sqlAstTranslatorFactory = jdbcEnvironment.getSqlAstTranslatorFactory();
final LockOptions lockOptions;
if (options.getLockOptions() != null) {
lockOptions = options.getLockOptions();
} else {
lockOptions = LockOptions.NONE;
}
final NavigablePath entityPath = new NavigablePath(entityDescriptor.getRootPathName());
final QuerySpec rootQuerySpec = new QuerySpec(true);
final LoaderSqlAstCreationState sqlAstCreationState = new LoaderSqlAstCreationState(rootQuerySpec, new SqlAliasBaseManager(), new SimpleFromClauseAccessImpl(), lockOptions, fetchProcessor, true, sessionFactory);
final TableGroup rootTableGroup = entityDescriptor.createRootTableGroup(true, entityPath, null, () -> rootQuerySpec::applyPredicate, sqlAstCreationState, sessionFactory);
rootQuerySpec.getFromClause().addRoot(rootTableGroup);
sqlAstCreationState.getFromClauseAccess().registerTableGroup(entityPath, rootTableGroup);
final DomainResult<?> domainResult = domainResultProducer.apply(rootTableGroup, sqlAstCreationState);
final SelectStatement sqlSelect = new SelectStatement(rootQuerySpec, Collections.singletonList(domainResult));
final List<JdbcParameter> jdbcParameters = new ArrayList<>(naturalIdMapping.getJdbcTypeCount());
final JdbcParameterBindings jdbcParamBindings = new JdbcParameterBindingsImpl(jdbcParameters.size());
applyNaturalIdRestriction(bindValue, rootTableGroup, rootQuerySpec::applyPredicate, (jdbcParameter, jdbcParameterBinding) -> {
jdbcParameters.add(jdbcParameter);
jdbcParamBindings.addBinding(jdbcParameter, jdbcParameterBinding);
}, sqlAstCreationState, session);
final QueryOptions queryOptions = new SimpleQueryOptions(lockOptions, false);
final JdbcSelect jdbcSelect = sqlAstTranslatorFactory.buildSelectTranslator(sessionFactory, sqlSelect).translate(jdbcParamBindings, queryOptions);
final StatisticsImplementor statistics = sessionFactory.getStatistics();
final Long startToken = statementStartHandler.apply(statistics.isStatisticsEnabled());
// noinspection unchecked
final List<L> results = session.getFactory().getJdbcServices().getJdbcSelectExecutor().list(jdbcSelect, jdbcParamBindings, new ExecutionContext() {
private final Callback callback = new CallbackImpl();
@Override
public SharedSessionContractImplementor getSession() {
return session;
}
@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;
}
}, row -> (L) row[0], ListResultsConsumer.UniqueSemantic.FILTER);
if (results.size() > 1) {
throw new HibernateException(String.format("Loading by natural-id returned more that one row : %s", entityDescriptor.getEntityName()));
}
final L result;
if (results.isEmpty()) {
result = null;
} else {
result = results.get(0);
}
statementCompletionHandler.accept(result, startToken);
return result;
}
use of org.hibernate.sql.exec.spi.JdbcSelect in project hibernate-orm by hibernate.
the class SingleUniqueKeyEntityLoaderStandard method load.
@Override
public T load(Object ukValue, LockOptions lockOptions, Boolean readOnly, 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.emptyList(), 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() {
private final Callback callback = new CallbackImpl();
@Override
public SharedSessionContractImplementor getSession() {
return session;
}
@Override
public QueryOptions getQueryOptions() {
return new QueryOptionsAdapter() {
@Override
public Boolean isReadOnly() {
return readOnly;
}
};
}
@Override
public String getQueryIdentifier(String sql) {
return sql;
}
@Override
public QueryParameterBindings getQueryParameterBindings() {
return QueryParameterBindings.NO_PARAM_BINDINGS;
}
@Override
public Callback getCallback() {
return callback;
}
}, row -> row[0], ListResultsConsumer.UniqueSemantic.FILTER);
switch(list.size()) {
case 0:
return null;
case 1:
// noinspection unchecked
return (T) list.get(0);
}
throw new HibernateException("More than one row with the given identifier was found: " + ukValue + ", for class: " + entityDescriptor.getEntityName());
}
use of org.hibernate.sql.exec.spi.JdbcSelect in project hibernate-orm by hibernate.
the class CollectionLoaderBatchKey method batchLoad.
private void batchLoad(Object[] batchIds, int numberOfIds, SharedSessionContractImplementor session) {
if (log.isDebugEnabled()) {
log.debugf("Batch loading collection [%s] : %s", getLoadable().getCollectionDescriptor().getRole(), batchIds);
}
int smallBatchStart = 0;
int smallBatchLength = Math.min(numberOfIds, batchSize);
while (true) {
final List<JdbcParameter> jdbcParameters;
final SelectStatement sqlAst;
if (smallBatchLength == batchSize) {
jdbcParameters = this.batchSizeJdbcParameters;
sqlAst = this.batchSizeSqlAst;
} else {
jdbcParameters = new ArrayList<>();
sqlAst = LoaderSelectBuilder.createSelect(getLoadable(), // null here means to select everything
null, getLoadable().getKeyDescriptor(), null, numberOfIds, session.getLoadQueryInfluencers(), LockOptions.NONE, jdbcParameters::add, session.getFactory());
}
final SessionFactoryImplementor sessionFactory = session.getFactory();
final JdbcServices jdbcServices = sessionFactory.getJdbcServices();
final JdbcEnvironment jdbcEnvironment = jdbcServices.getJdbcEnvironment();
final SqlAstTranslatorFactory sqlAstTranslatorFactory = jdbcEnvironment.getSqlAstTranslatorFactory();
final JdbcSelect jdbcSelect = sqlAstTranslatorFactory.buildSelectTranslator(sessionFactory, sqlAst).translate(null, QueryOptions.NONE);
final JdbcParameterBindings jdbcParameterBindings = new JdbcParameterBindingsImpl(keyJdbcCount * smallBatchLength);
jdbcSelect.bindFilterJdbcParameters(jdbcParameterBindings);
int offset = 0;
for (int i = smallBatchStart; i < smallBatchStart + smallBatchLength; i++) {
offset += jdbcParameterBindings.registerParametersForEachJdbcValue(batchIds[i], Clause.WHERE, offset, getLoadable().getKeyDescriptor(), jdbcParameters, session);
}
assert offset == jdbcParameters.size();
final SubselectFetch.RegistrationHandler subSelectFetchableKeysHandler = SubselectFetch.createRegistrationHandler(session.getPersistenceContext().getBatchFetchQueue(), sqlAst, Collections.emptyList(), jdbcParameterBindings);
jdbcServices.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 void registerLoadingEntityEntry(EntityKey entityKey, LoadingEntityEntry entry) {
subSelectFetchableKeysHandler.addKey(entityKey, entry);
}
@Override
public QueryParameterBindings getQueryParameterBindings() {
return QueryParameterBindings.NO_PARAM_BINDINGS;
}
@Override
public Callback getCallback() {
return null;
}
}, RowTransformerPassThruImpl.instance(), ListResultsConsumer.UniqueSemantic.FILTER);
// prepare for the next round...
smallBatchStart += smallBatchLength;
if (smallBatchStart >= numberOfIds) {
break;
}
smallBatchLength = Math.min(numberOfIds - smallBatchStart, batchSize);
}
}
use of org.hibernate.sql.exec.spi.JdbcSelect in project hibernate-orm by hibernate.
the class GeneratedValuesProcessor method processGeneratedValues.
public void processGeneratedValues(Object entity, Object id, Object[] state, SharedSessionContractImplementor session) {
if (selectStatement == null) {
return;
}
final JdbcServices jdbcServices = sessionFactory.getJdbcServices();
final JdbcEnvironment jdbcEnvironment = jdbcServices.getJdbcEnvironment();
final SqlAstTranslatorFactory sqlAstTranslatorFactory = jdbcEnvironment.getSqlAstTranslatorFactory();
final JdbcParameterBindings jdbcParamBindings = new JdbcParameterBindingsImpl(jdbcParameters.size());
int offset = jdbcParamBindings.registerParametersForEachJdbcValue(id, Clause.WHERE, entityDescriptor.getIdentifierMapping(), jdbcParameters, session);
assert offset == jdbcParameters.size();
final JdbcSelect jdbcSelect = sqlAstTranslatorFactory.buildSelectTranslator(sessionFactory, selectStatement).translate(jdbcParamBindings, QueryOptions.NONE);
final List<Object[]> results = session.getFactory().getJdbcServices().getJdbcSelectExecutor().list(jdbcSelect, jdbcParamBindings, 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 UnsupportedMappingException("Follow-on locking not supported yet");
}
}, (row) -> row, ListResultsConsumer.UniqueSemantic.FILTER);
assert results.size() == 1;
final Object[] dbSelectionResults = results.get(0);
for (int i = 0; i < valueDescriptors.size(); i++) {
final GeneratedValueDescriptor descriptor = valueDescriptors.get(i);
final Object generatedValue = descriptor.resolver.resolveGeneratedValue(dbSelectionResults, entity, session);
state[descriptor.attribute.getStateArrayPosition()] = generatedValue;
descriptor.attribute.getAttributeMetadataAccess().resolveAttributeMetadata(entityDescriptor).getPropertyAccess().getSetter().set(entity, generatedValue);
}
}
use of org.hibernate.sql.exec.spi.JdbcSelect in project hibernate-orm by hibernate.
the class NativeSelectQueryPlanImpl method performScroll.
@Override
public ScrollableResultsImplementor<R> performScroll(ScrollMode scrollMode, DomainQueryExecutionContext executionContext) {
if (executionContext.getQueryOptions().getEffectiveLimit().getMaxRowsJpa() == 0) {
return EmptyScrollableResults.INSTANCE;
}
final List<JdbcParameterBinder> jdbcParameterBinders;
final JdbcParameterBindings jdbcParameterBindings;
final QueryParameterBindings queryParameterBindings = executionContext.getQueryParameterBindings();
if (parameterList == null || parameterList.isEmpty()) {
jdbcParameterBinders = Collections.emptyList();
jdbcParameterBindings = JdbcParameterBindings.NO_BINDINGS;
} else {
jdbcParameterBinders = new ArrayList<>(parameterList.size());
jdbcParameterBindings = new JdbcParameterBindingsImpl(parameterList.size());
jdbcParameterBindings.registerNativeQueryParameters(queryParameterBindings, parameterList, jdbcParameterBinders, executionContext.getSession().getFactory());
}
final JdbcSelect jdbcSelect = new JdbcSelect(sql, jdbcParameterBinders, resultSetMapping, affectedTableNames, Collections.emptySet());
final JdbcSelectExecutor executor = JdbcSelectExecutorStandardImpl.INSTANCE;
// return jdbcServices.getJdbcSelectExecutor().scroll(
return executor.scroll(jdbcSelect, scrollMode, jdbcParameterBindings, SqmJdbcExecutionContextAdapter.usingLockingAndPaging(executionContext), null);
}
Aggregations