Search in sources :

Example 1 with SqmQueryImplementor

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

the class CriteriaEntityGraphTest method buildSqlSelectAst.

private <T> SelectStatement buildSqlSelectAst(Class<T> entityType, RootGraphImplementor<T> entityGraph, GraphSemantic mode, SessionImplementor session) {
    final LoadQueryInfluencers loadQueryInfluencers = new LoadQueryInfluencers(session.getSessionFactory());
    final CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
    CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(entityType);
    criteriaQuery.select(criteriaQuery.from(entityType));
    final QueryImplementor<T> query = session.createQuery(criteriaQuery);
    final SqmQueryImplementor<String> hqlQuery = (SqmQueryImplementor<String>) query;
    hqlQuery.applyGraph(entityGraph, mode);
    final SqmSelectStatement<String> sqmStatement = (SqmSelectStatement<String>) hqlQuery.getSqmStatement();
    final StandardSqmTranslator<SelectStatement> sqmConverter = new StandardSqmTranslator<>(sqmStatement, hqlQuery.getQueryOptions(), ((QuerySqmImpl<?>) hqlQuery).getDomainParameterXref(), query.getParameterBindings(), loadQueryInfluencers, session.getSessionFactory(), true);
    final SqmTranslation<SelectStatement> sqmInterpretation = sqmConverter.translate();
    return sqmInterpretation.getSqlAst();
}
Also used : CriteriaBuilder(jakarta.persistence.criteria.CriteriaBuilder) SqmSelectStatement(org.hibernate.query.sqm.tree.select.SqmSelectStatement) LoadQueryInfluencers(org.hibernate.engine.spi.LoadQueryInfluencers) SqmSelectStatement(org.hibernate.query.sqm.tree.select.SqmSelectStatement) SelectStatement(org.hibernate.sql.ast.tree.select.SelectStatement) SqmQueryImplementor(org.hibernate.query.hql.spi.SqmQueryImplementor) StandardSqmTranslator(org.hibernate.query.sqm.sql.internal.StandardSqmTranslator)

Example 2 with SqmQueryImplementor

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

the class SmokeTests method testConvertedHqlInterpretation.

@Test
public void testConvertedHqlInterpretation(SessionFactoryScope scope) {
    scope.inTransaction(session -> {
        final JdbcTypeRegistry jdbcTypeRegistry = session.getFactory().getTypeConfiguration().getJdbcTypeRegistry();
        final QueryImplementor<Gender> query = session.createQuery("select e.gender from SimpleEntity e", Gender.class);
        final SqmQueryImplementor<Gender> hqlQuery = (SqmQueryImplementor<Gender>) query;
        final SqmSelectStatement<Gender> sqmStatement = (SqmSelectStatement<Gender>) hqlQuery.getSqmStatement();
        final StandardSqmTranslator<SelectStatement> sqmConverter = new StandardSqmTranslator<>(sqmStatement, hqlQuery.getQueryOptions(), ((QuerySqmImpl<?>) hqlQuery).getDomainParameterXref(), query.getParameterBindings(), session.getLoadQueryInfluencers(), scope.getSessionFactory(), true);
        final SqmTranslation<SelectStatement> sqmInterpretation = sqmConverter.translate();
        final SelectStatement sqlAst = sqmInterpretation.getSqlAst();
        final FromClause fromClause = sqlAst.getQuerySpec().getFromClause();
        assertThat(fromClause.getRoots().size(), is(1));
        final TableGroup rootTableGroup = fromClause.getRoots().get(0);
        assertThat(rootTableGroup.getPrimaryTableReference(), notNullValue());
        assertThat(rootTableGroup.getPrimaryTableReference().getTableId(), is("mapping_simple_entity"));
        assertThat(rootTableGroup.getTableReferenceJoins().size(), is(0));
        assertThat(rootTableGroup.getTableGroupJoins().isEmpty(), is(true));
        // `s` is the "alias stem" for `SimpleEntity` and as it is the first entity with that stem in
        // the query the base becomes `s1`.  The primary table reference is always suffixed as `_0`
        assertThat(rootTableGroup.getPrimaryTableReference().getIdentificationVariable(), is("s1_0"));
        final SelectClause selectClause = sqlAst.getQuerySpec().getSelectClause();
        assertThat(selectClause.getSqlSelections().size(), is(1));
        final SqlSelection sqlSelection = selectClause.getSqlSelections().get(0);
        assertThat(sqlSelection.getJdbcResultSetIndex(), is(1));
        assertThat(sqlSelection.getValuesArrayPosition(), is(0));
        assertThat(sqlSelection.getJdbcValueExtractor(), notNullValue());
        assertThat(sqlSelection, instanceOf(SqlSelectionImpl.class));
        final Expression selectedExpression = sqlSelection.getExpression();
        assertThat(selectedExpression, instanceOf(ColumnReference.class));
        final ColumnReference columnReference = (ColumnReference) selectedExpression;
        assertThat(columnReference.renderSqlFragment(scope.getSessionFactory()), is("s1_0.gender"));
        final JdbcMappingContainer selectedExpressible = selectedExpression.getExpressionType();
        assertThat(selectedExpressible, instanceOf(BasicTypeImpl.class));
        final BasicTypeImpl<?> basicType = (BasicTypeImpl<?>) selectedExpressible;
        assertThat(basicType.getJavaTypeDescriptor().getJavaTypeClass(), AssignableMatcher.assignableTo(Integer.class));
        assertThat(basicType.getJdbcType(), is(jdbcTypeRegistry.getDescriptor(Types.TINYINT)));
        assertThat(sqlAst.getDomainResultDescriptors().size(), is(1));
        final DomainResult<?> domainResult = sqlAst.getDomainResultDescriptors().get(0);
        assertThat(domainResult, instanceOf(BasicResult.class));
        final BasicResult<?> scalarDomainResult = (BasicResult<?>) domainResult;
        assertThat(scalarDomainResult.getAssembler(), instanceOf(BasicResultAssembler.class));
        final BasicResultAssembler<?> assembler = (BasicResultAssembler<?>) scalarDomainResult.getAssembler();
        assertThat(assembler.getValueConverter(), notNullValue());
        assertThat(assembler.getValueConverter(), instanceOf(OrdinalEnumValueConverter.class));
        final NavigablePath expectedSelectedPath = new NavigablePath(SimpleEntity.class.getName(), "e").append("gender");
        assertThat(domainResult.getNavigablePath(), equalTo(expectedSelectedPath));
        assertThat(domainResult, instanceOf(BasicResult.class));
        // ScalarDomainResultImpl creates and caches the assembler at its creation.
        // this just gets access to that cached one
        final DomainResultAssembler<?> resultAssembler = domainResult.createResultAssembler(null, null);
        assertThat(resultAssembler, instanceOf(BasicResultAssembler.class));
        final BasicValueConverter<?, ?> valueConverter = ((BasicResultAssembler<?>) resultAssembler).getValueConverter();
        assertThat(valueConverter, notNullValue());
        assertThat(valueConverter, instanceOf(OrdinalEnumValueConverter.class));
        final JdbcSelect jdbcSelectOperation = new StandardSqlAstTranslator<JdbcSelect>(session.getSessionFactory(), sqlAst).translate(null, QueryOptions.NONE);
        assertThat(jdbcSelectOperation.getSql(), is("select s1_0.gender from mapping_simple_entity s1_0"));
    });
}
Also used : SelectClause(org.hibernate.sql.ast.tree.select.SelectClause) NavigablePath(org.hibernate.query.spi.NavigablePath) BasicTypeImpl(org.hibernate.type.internal.BasicTypeImpl) Gender(org.hibernate.orm.test.mapping.SmokeTests.Gender) SqlSelection(org.hibernate.sql.ast.spi.SqlSelection) SqmSelectStatement(org.hibernate.query.sqm.tree.select.SqmSelectStatement) SelectStatement(org.hibernate.sql.ast.tree.select.SelectStatement) JdbcMappingContainer(org.hibernate.metamodel.mapping.JdbcMappingContainer) SqmQueryImplementor(org.hibernate.query.hql.spi.SqmQueryImplementor) BasicResult(org.hibernate.sql.results.graph.basic.BasicResult) OrdinalEnumValueConverter(org.hibernate.metamodel.model.convert.internal.OrdinalEnumValueConverter) SqmSelectStatement(org.hibernate.query.sqm.tree.select.SqmSelectStatement) JdbcSelect(org.hibernate.sql.exec.spi.JdbcSelect) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) BasicResultAssembler(org.hibernate.sql.results.graph.basic.BasicResultAssembler) FromClause(org.hibernate.sql.ast.tree.from.FromClause) Expression(org.hibernate.sql.ast.tree.expression.Expression) SqlSelectionImpl(org.hibernate.sql.results.internal.SqlSelectionImpl) StandardSqmTranslator(org.hibernate.query.sqm.sql.internal.StandardSqmTranslator) JdbcTypeRegistry(org.hibernate.type.descriptor.jdbc.spi.JdbcTypeRegistry) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference) Test(org.junit.jupiter.api.Test)

Example 3 with SqmQueryImplementor

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

the class SmokeTests method testSimpleHqlInterpretation.

@Test
public void testSimpleHqlInterpretation(SessionFactoryScope scope) {
    scope.inTransaction(session -> {
        final QueryImplementor<String> query = session.createQuery("select e.name from SimpleEntity e", String.class);
        final SqmQueryImplementor<String> hqlQuery = (SqmQueryImplementor<String>) query;
        final SqmSelectStatement<String> sqmStatement = (SqmSelectStatement<String>) hqlQuery.getSqmStatement();
        final StandardSqmTranslator<SelectStatement> sqmConverter = new StandardSqmTranslator<>(sqmStatement, hqlQuery.getQueryOptions(), ((QuerySqmImpl<?>) hqlQuery).getDomainParameterXref(), query.getParameterBindings(), session.getLoadQueryInfluencers(), scope.getSessionFactory(), true);
        final SqmTranslation<SelectStatement> sqmInterpretation = sqmConverter.translate();
        final SelectStatement sqlAst = sqmInterpretation.getSqlAst();
        final FromClause fromClause = sqlAst.getQuerySpec().getFromClause();
        assertThat(fromClause.getRoots().size(), is(1));
        final TableGroup rootTableGroup = fromClause.getRoots().get(0);
        assertThat(rootTableGroup.getPrimaryTableReference(), notNullValue());
        assertThat(rootTableGroup.getPrimaryTableReference().getTableId(), is("mapping_simple_entity"));
        assertThat(rootTableGroup.getTableReferenceJoins().size(), is(0));
        assertThat(rootTableGroup.getTableGroupJoins().isEmpty(), is(true));
        // `s` is the "alias stem" for `SimpleEntity` and as it is the first entity with that stem in
        // the query the base becomes `s1`.  The primary table reference is always suffixed as `_0`
        assertThat(rootTableGroup.getPrimaryTableReference().getIdentificationVariable(), is("s1_0"));
        final SelectClause selectClause = sqlAst.getQuerySpec().getSelectClause();
        assertThat(selectClause.getSqlSelections().size(), is(1));
        final SqlSelection sqlSelection = selectClause.getSqlSelections().get(0);
        assertThat(sqlSelection.getJdbcResultSetIndex(), is(1));
        assertThat(sqlSelection.getValuesArrayPosition(), is(0));
        assertThat(sqlSelection.getJdbcValueExtractor(), notNullValue());
        final JdbcSelect jdbcSelectOperation = new StandardSqlAstTranslator<JdbcSelect>(session.getSessionFactory(), sqlAst).translate(null, QueryOptions.NONE);
        assertThat(jdbcSelectOperation.getSql(), is("select s1_0.name from mapping_simple_entity s1_0"));
    });
}
Also used : SqmSelectStatement(org.hibernate.query.sqm.tree.select.SqmSelectStatement) SelectClause(org.hibernate.sql.ast.tree.select.SelectClause) JdbcSelect(org.hibernate.sql.exec.spi.JdbcSelect) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) SqlSelection(org.hibernate.sql.ast.spi.SqlSelection) SqmSelectStatement(org.hibernate.query.sqm.tree.select.SqmSelectStatement) SelectStatement(org.hibernate.sql.ast.tree.select.SelectStatement) SqmQueryImplementor(org.hibernate.query.hql.spi.SqmQueryImplementor) FromClause(org.hibernate.sql.ast.tree.from.FromClause) StandardSqmTranslator(org.hibernate.query.sqm.sql.internal.StandardSqmTranslator) Test(org.junit.jupiter.api.Test)

Example 4 with SqmQueryImplementor

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

the class SessionFactoryImpl method addNamedQuery.

@Override
public void addNamedQuery(String name, Query query) {
    validateNotClosed();
    // NOTE : we use Query#unwrap here (rather than direct type checking) to account for possibly wrapped
    // query implementations
    // first, handle StoredProcedureQuery
    final NamedObjectRepository namedObjectRepository = getQueryEngine().getNamedObjectRepository();
    try {
        final ProcedureCallImplementor<?> unwrapped = query.unwrap(ProcedureCallImplementor.class);
        if (unwrapped != null) {
            namedObjectRepository.registerCallableQueryMemento(name, unwrapped.toMemento(name));
            return;
        }
    } catch (PersistenceException ignore) {
    // this means 'query' is not a ProcedureCallImplementor
    }
    // then try as a native-SQL or JPQL query
    try {
        QueryImplementor<?> hibernateQuery = query.unwrap(QueryImplementor.class);
        if (hibernateQuery != null) {
            // create and register the proper NamedQueryDefinition...
            if (hibernateQuery instanceof NativeQueryImplementor) {
                namedObjectRepository.registerNativeQueryMemento(name, ((NativeQueryImplementor<?>) hibernateQuery).toMemento(name));
            } else {
                final NamedQueryMemento namedQueryMemento = ((SqmQueryImplementor<?>) hibernateQuery).toMemento(name);
                namedObjectRepository.registerSqmQueryMemento(name, (NamedSqmQueryMemento) namedQueryMemento);
            }
            return;
        }
    } catch (PersistenceException ignore) {
    // this means 'query' is not a native-SQL or JPQL query
    }
    // if we get here, we are unsure how to properly unwrap the incoming query to extract the needed information
    throw new PersistenceException(String.format("Unsure how to properly unwrap given Query [%s] as basis for named query", query));
}
Also used : NativeQueryImplementor(org.hibernate.query.sql.spi.NativeQueryImplementor) SqmQueryImplementor(org.hibernate.query.hql.spi.SqmQueryImplementor) NamedObjectRepository(org.hibernate.query.named.NamedObjectRepository) PersistenceException(jakarta.persistence.PersistenceException) NamedQueryMemento(org.hibernate.query.named.NamedQueryMemento)

Example 5 with SqmQueryImplementor

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

the class AbstractSharedSessionContract method buildNamedQuery.

@SuppressWarnings({ "rawtypes", "unchecked" })
protected <T> QueryImplementor<T> buildNamedQuery(String queryName, Class<T> resultType) {
    try {
        return buildNamedQuery(queryName, (memento) -> {
            final SqmQueryImplementor query = memento.toQuery(this, resultType);
            if (StringHelper.isEmpty(query.getComment())) {
                query.setComment("dynamic query");
            }
            applyQuerySettingsAndHints(query);
            if (memento.getLockOptions() != null) {
                query.setLockOptions(memento.getLockOptions());
            }
            return query;
        }, (memento) -> {
            final NativeQueryImplementor query;
            if (resultType == null) {
                query = memento.toQuery(this);
            } else {
                query = memento.toQuery(this, resultType);
            }
            if (StringHelper.isEmpty(query.getComment())) {
                query.setComment("dynamic native-SQL query");
            }
            applyQuerySettingsAndHints(query);
            return query;
        });
    } catch (UnknownNamedQueryException e) {
        // JPA expects this to mark the transaction for rollback only
        transactionCoordinator.getTransactionDriverControl().markRollbackOnly();
        // it also expects an IllegalArgumentException, so wrap UnknownNamedQueryException
        throw new IllegalArgumentException(e.getMessage(), e);
    } catch (IllegalArgumentException e) {
        throw e;
    } catch (RuntimeException e) {
        throw getExceptionConverter().convert(e);
    }
}
Also used : SqmQueryImplementor(org.hibernate.query.hql.spi.SqmQueryImplementor) NativeQueryImplementor(org.hibernate.query.sql.spi.NativeQueryImplementor) UnknownNamedQueryException(org.hibernate.query.UnknownNamedQueryException)

Aggregations

SqmQueryImplementor (org.hibernate.query.hql.spi.SqmQueryImplementor)6 StandardSqmTranslator (org.hibernate.query.sqm.sql.internal.StandardSqmTranslator)4 SqmSelectStatement (org.hibernate.query.sqm.tree.select.SqmSelectStatement)4 SelectStatement (org.hibernate.sql.ast.tree.select.SelectStatement)4 LoadQueryInfluencers (org.hibernate.engine.spi.LoadQueryInfluencers)2 NativeQueryImplementor (org.hibernate.query.sql.spi.NativeQueryImplementor)2 SqlSelection (org.hibernate.sql.ast.spi.SqlSelection)2 FromClause (org.hibernate.sql.ast.tree.from.FromClause)2 TableGroup (org.hibernate.sql.ast.tree.from.TableGroup)2 SelectClause (org.hibernate.sql.ast.tree.select.SelectClause)2 JdbcSelect (org.hibernate.sql.exec.spi.JdbcSelect)2 Test (org.junit.jupiter.api.Test)2 PersistenceException (jakarta.persistence.PersistenceException)1 CriteriaBuilder (jakarta.persistence.criteria.CriteriaBuilder)1 JdbcMappingContainer (org.hibernate.metamodel.mapping.JdbcMappingContainer)1 OrdinalEnumValueConverter (org.hibernate.metamodel.model.convert.internal.OrdinalEnumValueConverter)1 Gender (org.hibernate.orm.test.mapping.SmokeTests.Gender)1 UnknownNamedQueryException (org.hibernate.query.UnknownNamedQueryException)1 NamedObjectRepository (org.hibernate.query.named.NamedObjectRepository)1 NamedQueryMemento (org.hibernate.query.named.NamedQueryMemento)1