Search in sources :

Example 1 with BasicTypeImpl

use of org.hibernate.type.internal.BasicTypeImpl in project hibernate-orm by hibernate.

the class AbstractHANADialect method contributeTypes.

@Override
public void contributeTypes(TypeContributions typeContributions, ServiceRegistry serviceRegistry) {
    super.contributeTypes(typeContributions, serviceRegistry);
    final ConnectionProvider connectionProvider = serviceRegistry.getService(ConnectionProvider.class);
    int maxLobPrefetchSizeDefault = MAX_LOB_PREFETCH_SIZE_DEFAULT_VALUE;
    if (connectionProvider != null) {
        Connection conn = null;
        try {
            conn = connectionProvider.getConnection();
            try (Statement statement = conn.createStatement()) {
                try (ResultSet rs = statement.executeQuery("SELECT TOP 1 VALUE,MAP(LAYER_NAME,'DEFAULT',1,'SYSTEM',2,'DATABASE',3,4) AS LAYER FROM SYS.M_INIFILE_CONTENTS WHERE FILE_NAME='indexserver.ini' AND SECTION='session' AND KEY='max_lob_prefetch_size' ORDER BY LAYER DESC")) {
                    // This only works if the current user has the privilege INIFILE ADMIN
                    if (rs.next()) {
                        maxLobPrefetchSizeDefault = rs.getInt(1);
                    }
                }
            }
        } catch (Exception e) {
            LOG.debug("An error occurred while trying to determine the value of the HANA parameter indexserver.ini / session / max_lob_prefetch_size. Using the default value " + maxLobPrefetchSizeDefault, e);
        } finally {
            if (conn != null) {
                try {
                    connectionProvider.closeConnection(conn);
                } catch (SQLException e) {
                // ignore
                }
            }
        }
    }
    final ConfigurationService configurationService = serviceRegistry.getService(ConfigurationService.class);
    int maxLobPrefetchSize = configurationService.getSetting(MAX_LOB_PREFETCH_SIZE_PARAMETER_NAME, value -> Integer.valueOf(value.toString()), maxLobPrefetchSizeDefault);
    if (this.nClobTypeDescriptor.getMaxLobPrefetchSize() != maxLobPrefetchSize) {
        this.nClobTypeDescriptor = new HANANClobJdbcType(maxLobPrefetchSize);
    }
    if (this.blobTypeDescriptor.getMaxLobPrefetchSize() != maxLobPrefetchSize) {
        this.blobTypeDescriptor = new HANABlobType(maxLobPrefetchSize);
    }
    if (supportsAsciiStringTypes()) {
        this.useUnicodeStringTypes = configurationService.getSetting(USE_UNICODE_STRING_TYPES_PARAMETER_NAME, StandardConverters.BOOLEAN, useUnicodeStringTypesDefault());
        if (this.isUseUnicodeStringTypes()) {
            registerColumnType(Types.CHAR, "nvarchar($l)");
            registerColumnType(Types.VARCHAR, 5000, "nvarchar($l)");
            // for longer values map to clob/nclob
            registerColumnType(Types.VARCHAR, "nclob");
            registerColumnType(Types.CLOB, "nclob");
        }
        if (this.clobTypeDescriptor.getMaxLobPrefetchSize() != maxLobPrefetchSize || this.clobTypeDescriptor.isUseUnicodeStringTypes() != this.useUnicodeStringTypes) {
            this.clobTypeDescriptor = new HANAClobJdbcType(maxLobPrefetchSize, this.useUnicodeStringTypes);
        }
    }
    this.useLegacyBooleanType = configurationService.getSetting(USE_LEGACY_BOOLEAN_TYPE_PARAMETER_NAME, StandardConverters.BOOLEAN, USE_LEGACY_BOOLEAN_TYPE_DEFAULT_VALUE);
    if (this.useLegacyBooleanType) {
        registerColumnType(Types.BOOLEAN, "tinyint");
    }
    boolean treatDoubleTypedFieldsAsDecimal = configurationService.getSetting(TREAT_DOUBLE_TYPED_FIELDS_AS_DECIMAL_PARAMETER_NAME, StandardConverters.BOOLEAN, TREAT_DOUBLE_TYPED_FIELDS_AS_DECIMAL_DEFAULT_VALUE);
    final JdbcTypeRegistry jdbcTypeRegistry = typeContributions.getTypeConfiguration().getJdbcTypeRegistry();
    if (treatDoubleTypedFieldsAsDecimal) {
        registerHibernateType(Types.FLOAT, StandardBasicTypes.BIG_DECIMAL.getName());
        registerHibernateType(Types.REAL, StandardBasicTypes.BIG_DECIMAL.getName());
        registerHibernateType(Types.DOUBLE, StandardBasicTypes.BIG_DECIMAL.getName());
        typeContributions.getTypeConfiguration().getBasicTypeRegistry().register(new BasicTypeImpl<>(DoubleJavaType.INSTANCE, NumericJdbcType.INSTANCE), Double.class.getName());
        typeContributions.getTypeConfiguration().getJdbcToHibernateTypeContributionMap().computeIfAbsent(Types.FLOAT, code -> new HashSet<>()).clear();
        typeContributions.getTypeConfiguration().getJdbcToHibernateTypeContributionMap().computeIfAbsent(Types.REAL, code -> new HashSet<>()).clear();
        typeContributions.getTypeConfiguration().getJdbcToHibernateTypeContributionMap().computeIfAbsent(Types.DOUBLE, code -> new HashSet<>()).clear();
        typeContributions.getTypeConfiguration().getJdbcToHibernateTypeContributionMap().get(Types.FLOAT).add(StandardBasicTypes.BIG_DECIMAL.getName());
        typeContributions.getTypeConfiguration().getJdbcToHibernateTypeContributionMap().get(Types.REAL).add(StandardBasicTypes.BIG_DECIMAL.getName());
        typeContributions.getTypeConfiguration().getJdbcToHibernateTypeContributionMap().get(Types.DOUBLE).add(StandardBasicTypes.BIG_DECIMAL.getName());
        jdbcTypeRegistry.addDescriptor(Types.FLOAT, NumericJdbcType.INSTANCE);
        jdbcTypeRegistry.addDescriptor(Types.REAL, NumericJdbcType.INSTANCE);
        jdbcTypeRegistry.addDescriptor(Types.DOUBLE, NumericJdbcType.INSTANCE);
    }
    jdbcTypeRegistry.addDescriptor(Types.CLOB, this.clobTypeDescriptor);
    jdbcTypeRegistry.addDescriptor(Types.NCLOB, this.nClobTypeDescriptor);
    jdbcTypeRegistry.addDescriptor(Types.BLOB, this.blobTypeDescriptor);
    // tinyint is unsigned on HANA
    jdbcTypeRegistry.addDescriptor(Types.TINYINT, SmallIntJdbcType.INSTANCE);
    if (isUseUnicodeStringTypes()) {
        jdbcTypeRegistry.addDescriptor(Types.VARCHAR, NVarcharJdbcType.INSTANCE);
        jdbcTypeRegistry.addDescriptor(Types.CHAR, NCharJdbcType.INSTANCE);
    }
    if (treatDoubleTypedFieldsAsDecimal) {
        jdbcTypeRegistry.addDescriptor(Types.DOUBLE, DecimalJdbcType.INSTANCE);
    }
}
Also used : SQLExceptionConversionDelegate(org.hibernate.exception.spi.SQLExceptionConversionDelegate) BasicTypeImpl(org.hibernate.type.internal.BasicTypeImpl) CallableStatementSupport(org.hibernate.procedure.spi.CallableStatementSupport) Arrays(java.util.Arrays) ValueBinder(org.hibernate.type.descriptor.ValueBinder) StandardConverters(org.hibernate.engine.config.spi.StandardConverters) JdbcTypeRegistry(org.hibernate.type.descriptor.jdbc.spi.JdbcTypeRegistry) CommonFunctionFactory(org.hibernate.dialect.function.CommonFunctionFactory) Identifier(org.hibernate.boot.model.naming.Identifier) DoubleJavaType(org.hibernate.type.descriptor.java.DoubleJavaType) SqlTypes(org.hibernate.type.SqlTypes) Matcher(java.util.regex.Matcher) Duration(java.time.Duration) org.hibernate.engine.jdbc.env.spi(org.hibernate.engine.jdbc.env.spi) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) Exporter(org.hibernate.tool.schema.spi.Exporter) TemporalType(jakarta.persistence.TemporalType) SequenceInformationExtractorHANADatabaseImpl(org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorHANADatabaseImpl) FunctionParameterType(org.hibernate.query.sqm.produce.function.FunctionParameterType) LockOptions(org.hibernate.LockOptions) DialectResolutionInfo(org.hibernate.engine.jdbc.dialect.spi.DialectResolutionInfo) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) DataHelper(org.hibernate.type.descriptor.java.DataHelper) TypeConfiguration(org.hibernate.type.spi.TypeConfiguration) LockTimeoutException(org.hibernate.exception.LockTimeoutException) org.hibernate.engine.jdbc(org.hibernate.engine.jdbc) TemporalUnit(org.hibernate.query.sqm.TemporalUnit) StandardCharsets(java.nio.charset.StandardCharsets) SqlAstTranslatorFactory(org.hibernate.sql.ast.SqlAstTranslatorFactory) JdbcOperation(org.hibernate.sql.exec.spi.JdbcOperation) List(java.util.List) ScrollMode(org.hibernate.ScrollMode) TypeContributions(org.hibernate.boot.model.TypeContributions) IdentityColumnSupport(org.hibernate.dialect.identity.IdentityColumnSupport) SqlAppender(org.hibernate.sql.ast.spi.SqlAppender) StandardTableExporter(org.hibernate.tool.schema.internal.StandardTableExporter) SequenceSupport(org.hibernate.dialect.sequence.SequenceSupport) Pattern(java.util.regex.Pattern) ConnectionProvider(org.hibernate.engine.jdbc.connections.spi.ConnectionProvider) LimitOffsetLimitHandler(org.hibernate.dialect.pagination.LimitOffsetLimitHandler) HANASequenceSupport(org.hibernate.dialect.sequence.HANASequenceSupport) java.sql(java.sql) org.hibernate.type.descriptor.jdbc(org.hibernate.type.descriptor.jdbc) SqlAstNodeRenderingMode(org.hibernate.sql.ast.SqlAstNodeRenderingMode) HANAIdentityColumnSupport(org.hibernate.dialect.identity.HANAIdentityColumnSupport) CoreMessageLogger(org.hibernate.internal.CoreMessageLogger) SqlStringGenerationContext(org.hibernate.boot.model.relational.SqlStringGenerationContext) LockAcquisitionException(org.hibernate.exception.LockAcquisitionException) JdbcExceptionHelper(org.hibernate.internal.util.JdbcExceptionHelper) JavaType(org.hibernate.type.descriptor.java.JavaType) Metadata(org.hibernate.boot.Metadata) HashSet(java.util.HashSet) SequenceInformationExtractor(org.hibernate.tool.schema.extract.spi.SequenceInformationExtractor) StandardCallableStatementSupport(org.hibernate.procedure.internal.StandardCallableStatementSupport) ConfigurationService(org.hibernate.engine.config.spi.ConfigurationService) IntervalType(org.hibernate.query.sqm.IntervalType) WrapperOptions(org.hibernate.type.descriptor.WrapperOptions) NullOrdering(org.hibernate.query.sqm.NullOrdering) LockMode(org.hibernate.LockMode) SqlAstTranslator(org.hibernate.sql.ast.SqlAstTranslator) Table(org.hibernate.mapping.Table) StandardSqlAstTranslatorFactory(org.hibernate.sql.ast.spi.StandardSqlAstTranslatorFactory) ServiceRegistry(org.hibernate.service.ServiceRegistry) LimitHandler(org.hibernate.dialect.pagination.LimitHandler) SQLGrammarException(org.hibernate.exception.SQLGrammarException) CastType(org.hibernate.query.sqm.CastType) QueryEngine(org.hibernate.query.spi.QueryEngine) StandardBasicTypes(org.hibernate.type.StandardBasicTypes) ValueExtractor(org.hibernate.type.descriptor.ValueExtractor) java.io(java.io) IntegralTimestampaddFunction(org.hibernate.dialect.function.IntegralTimestampaddFunction) CoreLogging(org.hibernate.internal.CoreLogging) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) LockTimeoutException(org.hibernate.exception.LockTimeoutException) LockAcquisitionException(org.hibernate.exception.LockAcquisitionException) SQLGrammarException(org.hibernate.exception.SQLGrammarException) ConnectionProvider(org.hibernate.engine.jdbc.connections.spi.ConnectionProvider) ConfigurationService(org.hibernate.engine.config.spi.ConfigurationService) JdbcTypeRegistry(org.hibernate.type.descriptor.jdbc.spi.JdbcTypeRegistry) HashSet(java.util.HashSet)

Example 2 with BasicTypeImpl

use of org.hibernate.type.internal.BasicTypeImpl in project hibernate-orm by hibernate.

the class AnsiTrimEmulationFunctionTest method render.

private String render(Dialect dialect, TrimFunction function, TrimSpec trimSpec, char trimCharacter, String trimSource) {
    SessionFactoryImplementor factory = Mockito.mock(SessionFactoryImplementor.class);
    JdbcServices jdbcServices = Mockito.mock(JdbcServices.class);
    Mockito.doReturn(jdbcServices).when(factory).getJdbcServices();
    Mockito.doReturn(dialect).when(jdbcServices).getDialect();
    StandardSqlAstTranslator<JdbcOperation> walker = new StandardSqlAstTranslator<>(factory, null);
    List<SqlAstNode> sqlAstArguments = new ArrayList<>();
    sqlAstArguments.add(new TrimSpecification(trimSpec));
    sqlAstArguments.add(new QueryLiteral<>(trimCharacter, new BasicTypeImpl<>(CharacterJavaType.INSTANCE, CharJdbcType.INSTANCE)));
    sqlAstArguments.add(new SelfRenderingExpression() {

        @Override
        public void renderToSql(SqlAppender sqlAppender, SqlAstTranslator<?> walker, SessionFactoryImplementor sessionFactory) {
            sqlAppender.appendSql(trimSource);
        }

        @Override
        public JdbcMappingContainer getExpressionType() {
            return null;
        }
    });
    function.render(walker, sqlAstArguments, walker);
    return walker.getSql();
}
Also used : SqlAppender(org.hibernate.sql.ast.spi.SqlAppender) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) BasicTypeImpl(org.hibernate.type.internal.BasicTypeImpl) JdbcOperation(org.hibernate.sql.exec.spi.JdbcOperation) ArrayList(java.util.ArrayList) TrimSpecification(org.hibernate.sql.ast.tree.expression.TrimSpecification) JdbcServices(org.hibernate.engine.jdbc.spi.JdbcServices) SqlAstNode(org.hibernate.sql.ast.tree.SqlAstNode) JdbcMappingContainer(org.hibernate.metamodel.mapping.JdbcMappingContainer) SelfRenderingExpression(org.hibernate.sql.ast.tree.expression.SelfRenderingExpression) StandardSqlAstTranslator(org.hibernate.sql.ast.spi.StandardSqlAstTranslator)

Example 3 with BasicTypeImpl

use of org.hibernate.type.internal.BasicTypeImpl in project hibernate-orm by hibernate.

the class AbstractQueryCacheResultTransformerTest method testSelectNewEntityConstructorList.

@Test
public void testSelectNewEntityConstructorList(SessionFactoryScope scope) throws Exception {
    CriteriaExecutor criteriaExecutor = new CriteriaExecutor() {

        @Override
        protected ResultTransformer getResultTransformer() {
            return new AliasToBeanConstructorResultTransformer(getConstructor());
        }

        @Override
        protected JpaCriteriaQuery getCriteria(Session s) {
            CriteriaBuilder builder = s.getCriteriaBuilder();
            JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery();
            Root<Student> root = criteria.from(Student.class);
            criteria.multiselect(root.get("studentNumber").alias("sNumber"), root.get("name").alias("name"));
            criteria.orderBy(builder.asc(root.get("studentNumber")));
            return criteria;
        // return s.createCriteria( Student.class, "s" )
        // .setProjection(
        // Projections.projectionList()
        // .add( Property.forName( "s.studentNumber" ).as( "studentNumber" ) )
        // .add( Property.forName( "s.name" ).as( "name" ) )
        // )
        // .addOrder( Order.asc( "s.studentNumber" ) )
        // .setResultTransformer( new AliasToBeanConstructorResultTransformer( getConstructor() ) );
        }

        private Constructor getConstructor() {
            Type studentNametype = scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor(Student.class.getName()).getPropertyType("name");
            return ReflectHelper.getConstructor(Student.class, new Type[] { new BasicTypeImpl<>(LongJavaType.INSTANCE, BigIntJdbcType.INSTANCE), studentNametype });
        }
    };
    HqlExecutor hqlExecutor = new HqlExecutor() {

        @Override
        public Query getQuery(Session s) {
            return s.createQuery("select new Student(s.studentNumber, s.name) from Student s order by s.studentNumber");
        }
    };
    ResultChecker checker = results -> {
        List resultList = (List) results;
        assertEquals(2, resultList.size());
        Student yogi = (Student) resultList.get(0);
        assertEquals(yogiExpected.getStudentNumber(), yogi.getStudentNumber());
        assertEquals(yogiExpected.getName(), yogi.getName());
        Student sherman = (Student) resultList.get(1);
        assertEquals(shermanExpected.getStudentNumber(), sherman.getStudentNumber());
        assertEquals(shermanExpected.getName(), sherman.getName());
    };
    runTest(hqlExecutor, criteriaExecutor, checker, false, scope);
}
Also used : CriteriaBuilder(jakarta.persistence.criteria.CriteriaBuilder) BasicTypeImpl(org.hibernate.type.internal.BasicTypeImpl) ServiceRegistry(org.hibernate.testing.orm.junit.ServiceRegistry) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) JoinType(jakarta.persistence.criteria.JoinType) JpaSelection(org.hibernate.query.criteria.JpaSelection) AvailableSettings(org.hibernate.cfg.AvailableSettings) Assertions.assertNotEquals(org.junit.jupiter.api.Assertions.assertNotEquals) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) Session(org.hibernate.Session) Constructor(java.lang.reflect.Constructor) ArrayList(java.util.ArrayList) HibernateProxy(org.hibernate.proxy.HibernateProxy) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) Map(java.util.Map) Query(org.hibernate.query.Query) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) Order(jakarta.persistence.criteria.Order) BigIntJdbcType(org.hibernate.type.descriptor.jdbc.BigIntJdbcType) Transformers(org.hibernate.transform.Transformers) Iterator(java.util.Iterator) ListJoin(jakarta.persistence.criteria.ListJoin) ReflectHelper(org.hibernate.internal.util.ReflectHelper) DomainModel(org.hibernate.testing.orm.junit.DomainModel) AliasToBeanConstructorResultTransformer(org.hibernate.transform.AliasToBeanConstructorResultTransformer) Selection(jakarta.persistence.criteria.Selection) CacheMode(org.hibernate.CacheMode) Assertions.assertSame(org.junit.jupiter.api.Assertions.assertSame) JpaCriteriaQuery(org.hibernate.query.criteria.JpaCriteriaQuery) Test(org.junit.jupiter.api.Test) MapJoin(jakarta.persistence.criteria.MapJoin) List(java.util.List) Root(jakarta.persistence.criteria.Root) SessionFactoryScope(org.hibernate.testing.orm.junit.SessionFactoryScope) CriteriaBuilder(jakarta.persistence.criteria.CriteriaBuilder) JpaRoot(org.hibernate.query.criteria.JpaRoot) LongJavaType(org.hibernate.type.descriptor.java.LongJavaType) Setting(org.hibernate.testing.orm.junit.Setting) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) AliasToEntityMapResultTransformer(org.hibernate.transform.AliasToEntityMapResultTransformer) SessionFactory(org.hibernate.testing.orm.junit.SessionFactory) Path(jakarta.persistence.criteria.Path) Hibernate(org.hibernate.Hibernate) ResultTransformer(org.hibernate.transform.ResultTransformer) Type(org.hibernate.type.Type) Join(jakarta.persistence.criteria.Join) AliasToBeanConstructorResultTransformer(org.hibernate.transform.AliasToBeanConstructorResultTransformer) JoinType(jakarta.persistence.criteria.JoinType) BigIntJdbcType(org.hibernate.type.descriptor.jdbc.BigIntJdbcType) LongJavaType(org.hibernate.type.descriptor.java.LongJavaType) Type(org.hibernate.type.Type) ArrayList(java.util.ArrayList) List(java.util.List) JpaCriteriaQuery(org.hibernate.query.criteria.JpaCriteriaQuery) Session(org.hibernate.Session) Test(org.junit.jupiter.api.Test)

Example 4 with BasicTypeImpl

use of org.hibernate.type.internal.BasicTypeImpl 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 5 with BasicTypeImpl

use of org.hibernate.type.internal.BasicTypeImpl in project hibernate-orm by hibernate.

the class BasicTypeRegistryTest method testOverriding.

@Test
public void testOverriding() {
    TypeConfiguration typeConfiguration = new TypeConfiguration();
    BasicTypeRegistry registry = typeConfiguration.getBasicTypeRegistry();
    BasicType<?> uuidBinaryRegistration = registry.getRegisteredType("uuid-binary");
    assertTrue(uuidBinaryRegistration.getJavaTypeDescriptor() instanceof UUIDJavaType);
    assertTrue(uuidBinaryRegistration.getJdbcType() instanceof BinaryJdbcType);
    final BasicType<UUID> uuidRegistration = registry.getRegisteredType(UUID.class.getName());
    assertTrue(uuidRegistration.getJavaTypeDescriptor() instanceof UUIDJavaType);
    assertTrue(uuidRegistration.getJdbcType() instanceof ObjectJdbcType);
    final BasicType<?> override = new BasicTypeImpl<>(UUIDJavaType.INSTANCE, CharJdbcType.INSTANCE);
    registry.register(override, UUID.class.getName());
    final BasicType<Object> overrideRegistration = registry.getRegisteredType(UUID.class.getName());
    assertSame(override, overrideRegistration);
    assertNotSame(uuidBinaryRegistration, overrideRegistration);
    assertNotSame(uuidRegistration, overrideRegistration);
}
Also used : ObjectJdbcType(org.hibernate.type.descriptor.jdbc.ObjectJdbcType) BinaryJdbcType(org.hibernate.type.descriptor.jdbc.BinaryJdbcType) BasicTypeImpl(org.hibernate.type.internal.BasicTypeImpl) BasicTypeRegistry(org.hibernate.type.BasicTypeRegistry) TypeConfiguration(org.hibernate.type.spi.TypeConfiguration) UUID(java.util.UUID) UUIDJavaType(org.hibernate.type.descriptor.java.UUIDJavaType) Test(org.junit.Test)

Aggregations

BasicTypeImpl (org.hibernate.type.internal.BasicTypeImpl)5 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)3 ArrayList (java.util.ArrayList)2 List (java.util.List)2 JdbcMappingContainer (org.hibernate.metamodel.mapping.JdbcMappingContainer)2 SqlAppender (org.hibernate.sql.ast.spi.SqlAppender)2 JdbcOperation (org.hibernate.sql.exec.spi.JdbcOperation)2 JdbcTypeRegistry (org.hibernate.type.descriptor.jdbc.spi.JdbcTypeRegistry)2 TypeConfiguration (org.hibernate.type.spi.TypeConfiguration)2 Test (org.junit.jupiter.api.Test)2 TemporalType (jakarta.persistence.TemporalType)1 CriteriaBuilder (jakarta.persistence.criteria.CriteriaBuilder)1 Join (jakarta.persistence.criteria.Join)1 JoinType (jakarta.persistence.criteria.JoinType)1 ListJoin (jakarta.persistence.criteria.ListJoin)1 MapJoin (jakarta.persistence.criteria.MapJoin)1 Order (jakarta.persistence.criteria.Order)1 Path (jakarta.persistence.criteria.Path)1 Root (jakarta.persistence.criteria.Root)1 Selection (jakarta.persistence.criteria.Selection)1