Search in sources :

Example 1 with Id

use of jakarta.persistence.Id in project hibernate-orm by hibernate.

the class JpaStreamTest method runTerminalOperationTests.

private void runTerminalOperationTests(Runnable prepare, List<Runnable> onCloseCallbacks, Runnable onCloseAssertion, boolean flatMapBefore, boolean flatMapAfter, SessionFactoryScope scope) {
    // collect as list
    scope.inTransaction(session -> {
        Stream<MyEntity> stream = getMyEntityStream(prepare, session, onCloseCallbacks, flatMapBefore, flatMapAfter);
        ResourceRegistry resourceRegistry = resourceRegistry(session);
        try {
            List<MyEntity> entities = stream.collect(Collectors.toList());
            assertTrue(resourceRegistry.hasRegisteredResources());
            assertEquals(10, entities.size());
        } finally {
            stream.close();
            assertFalse(resourceRegistry.hasRegisteredResources());
        }
        onCloseAssertion.run();
    });
    // forEach (TestCase based on attachment EntityManagerIllustrationTest.java in HHH-14449)
    scope.inTransaction(session -> {
        Stream<MyEntity> stream = getMyEntityStream(prepare, session, onCloseCallbacks, flatMapBefore, flatMapAfter);
        ResourceRegistry resourceRegistry = resourceRegistry(session);
        try {
            AtomicInteger count = new AtomicInteger();
            stream.forEach(myEntity -> count.incrementAndGet());
            assertTrue(resourceRegistry.hasRegisteredResources());
            assertEquals(10, count.get());
        } finally {
            stream.close();
            assertFalse(resourceRegistry.hasRegisteredResources());
        }
        onCloseAssertion.run();
    });
    // filter (always true) + forEach (TestCase based on attachment EntityManagerIllustrationTest.java in HHH-14449)
    scope.inTransaction(session -> {
        Stream<MyEntity> stream = getMyEntityStream(prepare, session, onCloseCallbacks, flatMapBefore, flatMapAfter);
        ResourceRegistry resourceRegistry = resourceRegistry(session);
        try {
            AtomicInteger count = new AtomicInteger();
            stream.filter(Objects::nonNull).forEach(myEntity -> count.incrementAndGet());
            assertTrue(resourceRegistry.hasRegisteredResources());
            assertEquals(10, count.get());
        } finally {
            stream.close();
            assertFalse(resourceRegistry.hasRegisteredResources());
        }
        onCloseAssertion.run();
    });
    // filter (partially true) + forEach (TestCase based on attachment EntityManagerIllustrationTest.java in HHH-14449)
    scope.inTransaction(session -> {
        Stream<MyEntity> stream = getMyEntityStream(prepare, session, onCloseCallbacks, flatMapBefore, flatMapAfter);
        ResourceRegistry resourceRegistry = resourceRegistry(session);
        try {
            AtomicInteger count = new AtomicInteger();
            stream.filter(entity -> entity.getId() % 2 == 0).forEach(myEntity -> count.incrementAndGet());
            assertTrue(resourceRegistry.hasRegisteredResources());
            assertEquals(5, count.get());
        } finally {
            stream.close();
            assertFalse(resourceRegistry.hasRegisteredResources());
        }
        onCloseAssertion.run();
    });
    // multiple chained operations (TestCase based on attachment EntityManagerIllustrationTest.java in HHH-14449)
    scope.inTransaction(session -> {
        Stream<MyEntity> stream = getMyEntityStream(prepare, session, onCloseCallbacks, flatMapBefore, flatMapAfter);
        ResourceRegistry resourceRegistry = resourceRegistry(session);
        try {
            AtomicInteger count = new AtomicInteger();
            stream.filter(Objects::nonNull).map(Optional::of).filter(Optional::isPresent).map(Optional::get).forEach(myEntity -> count.incrementAndGet());
            assertTrue(resourceRegistry.hasRegisteredResources());
            assertEquals(10, count.get());
        } finally {
            stream.close();
            assertFalse(resourceRegistry.hasRegisteredResources());
        }
        onCloseAssertion.run();
    });
    // mapToInt
    scope.inTransaction(session -> {
        Stream<MyEntity> stream = getMyEntityStream(prepare, session, onCloseCallbacks, flatMapBefore, flatMapAfter);
        ResourceRegistry resourceRegistry = resourceRegistry(session);
        try {
            int sum = stream.mapToInt(MyEntity::getId).sum();
            assertTrue(resourceRegistry.hasRegisteredResources());
            assertEquals(55, sum);
        } finally {
            stream.close();
            assertFalse(resourceRegistry.hasRegisteredResources());
        }
        onCloseAssertion.run();
    });
    // mapToLong
    scope.inTransaction(session -> {
        Stream<MyEntity> stream = getMyEntityStream(prepare, session, onCloseCallbacks, flatMapBefore, flatMapAfter);
        ResourceRegistry resourceRegistry = resourceRegistry(session);
        try {
            long result = stream.mapToLong(entity -> entity.id * 10).min().getAsLong();
            assertTrue(resourceRegistry.hasRegisteredResources());
            assertEquals(10, result);
        } finally {
            stream.close();
            assertFalse(resourceRegistry.hasRegisteredResources());
        }
        onCloseAssertion.run();
    });
    // mapToDouble
    scope.inTransaction(session -> {
        Stream<MyEntity> stream = getMyEntityStream(prepare, session, onCloseCallbacks, flatMapBefore, flatMapAfter);
        ResourceRegistry resourceRegistry = resourceRegistry(session);
        try {
            double result = stream.mapToDouble(entity -> entity.id * 0.1D).max().getAsDouble();
            assertTrue(resourceRegistry.hasRegisteredResources());
            assertEquals(1, result, 0.1);
        } finally {
            stream.close();
            assertFalse(resourceRegistry.hasRegisteredResources());
        }
        onCloseAssertion.run();
    });
    // Test call close explicitly
    scope.inTransaction(session -> {
        try (Stream<Long> stream = getLongStream(prepare, session, onCloseCallbacks, flatMapBefore, flatMapAfter)) {
            ResourceRegistry resourceRegistry = resourceRegistry(session);
            try {
                Object[] result = stream.sorted().skip(5).limit(5).toArray();
                assertTrue(resourceRegistry.hasRegisteredResources());
                assertEquals(5, result.length);
                assertEquals(6, result[0]);
                assertEquals(10, result[4]);
            } finally {
                stream.close();
                assertFalse(resourceRegistry.hasRegisteredResources());
            }
            onCloseAssertion.run();
        }
    });
    // Test Java 9 Stream methods
    scope.inTransaction(session -> {
        Method takeWhileMethod = ReflectHelper.getMethod(Stream.class, "takeWhile", Predicate.class);
        if (takeWhileMethod != null) {
            try (Stream<Long> stream = getLongStream(prepare, session, onCloseCallbacks, flatMapBefore, flatMapAfter)) {
                ResourceRegistry resourceRegistry = resourceRegistry(session);
                try {
                    Predicate<Integer> predicate = id -> id <= 5;
                    Stream<Integer> takeWhileStream = (Stream<Integer>) takeWhileMethod.invoke(stream, predicate);
                    List<Integer> result = takeWhileStream.collect(Collectors.toList());
                    assertTrue(resourceRegistry.hasRegisteredResources());
                    assertEquals(5, result.size());
                    assertTrue(result.contains(1));
                    assertTrue(result.contains(3));
                    assertTrue(result.contains(5));
                } finally {
                    stream.close();
                    assertFalse(resourceRegistry.hasRegisteredResources());
                }
                onCloseAssertion.run();
            } catch (IllegalAccessException | InvocationTargetException e) {
                fail("Could not execute takeWhile because of " + e.getMessage());
            }
        }
    });
    scope.inTransaction(session -> {
        Method dropWhileMethod = ReflectHelper.getMethod(Stream.class, "dropWhile", Predicate.class);
        if (dropWhileMethod != null) {
            try (Stream<Long> stream = getLongStream(prepare, session, onCloseCallbacks, flatMapBefore, flatMapAfter)) {
                ResourceRegistry resourceRegistry = resourceRegistry(session);
                Predicate<Integer> predicate = id -> id <= 5;
                Stream<Integer> dropWhileStream = (Stream<Integer>) dropWhileMethod.invoke(stream, predicate);
                try {
                    List<Integer> result = dropWhileStream.collect(Collectors.toList());
                    assertTrue(resourceRegistry.hasRegisteredResources());
                    assertEquals(5, result.size());
                    assertTrue(result.contains(6));
                    assertTrue(result.contains(8));
                    assertTrue(result.contains(10));
                } finally {
                    stream.close();
                    assertFalse(resourceRegistry.hasRegisteredResources());
                }
                onCloseAssertion.run();
            } catch (IllegalAccessException | InvocationTargetException e) {
                fail("Could not execute takeWhile because of " + e.getMessage());
            }
        }
    });
}
Also used : Assertions.fail(org.junit.jupiter.api.Assertions.fail) Entity(jakarta.persistence.Entity) Arrays(java.util.Arrays) H2Dialect(org.hibernate.dialect.H2Dialect) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) RequiresDialect(org.hibernate.testing.orm.junit.RequiresDialect) Session(org.hibernate.Session) Table(jakarta.persistence.Table) TestForIssue(org.hibernate.testing.TestForIssue) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Method(java.lang.reflect.Method) JdbcCoordinator(org.hibernate.engine.jdbc.spi.JdbcCoordinator) ReflectHelper(org.hibernate.internal.util.ReflectHelper) Predicate(java.util.function.Predicate) DomainModel(org.hibernate.testing.orm.junit.DomainModel) Id(jakarta.persistence.Id) Collectors(java.util.stream.Collectors) InvocationTargetException(java.lang.reflect.InvocationTargetException) Objects(java.util.Objects) Test(org.junit.jupiter.api.Test) List(java.util.List) ExtraAssertions.assertTyping(org.hibernate.testing.orm.junit.ExtraAssertions.assertTyping) Stream(java.util.stream.Stream) SessionFactoryScope(org.hibernate.testing.orm.junit.SessionFactoryScope) ResourceRegistry(org.hibernate.resource.jdbc.ResourceRegistry) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Optional(java.util.Optional) SessionFactory(org.hibernate.testing.orm.junit.SessionFactory) Collections(java.util.Collections) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) Optional(java.util.Optional) ResourceRegistry(org.hibernate.resource.jdbc.ResourceRegistry) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Objects(java.util.Objects) Stream(java.util.stream.Stream)

Example 2 with Id

use of jakarta.persistence.Id in project hibernate-orm by hibernate.

the class AnnotationBinder method addProperty.

private static int addProperty(PropertyContainer propertyContainer, XProperty property, List<PropertyData> inFlightPropertyDataList, MetadataBuildingContext context) {
    // and if so, skip it..
    for (PropertyData propertyData : inFlightPropertyDataList) {
        if (propertyData.getPropertyName().equals(property.getName())) {
            Id incomingIdProperty = property.getAnnotation(Id.class);
            Id existingIdProperty = propertyData.getProperty().getAnnotation(Id.class);
            if (incomingIdProperty != null && existingIdProperty == null) {
                throw new MappingException(String.format("You cannot override the [%s] non-identifier property from the [%s] base class or @MappedSuperclass and make it an identifier in the [%s] subclass!", propertyData.getProperty().getName(), propertyData.getProperty().getDeclaringClass().getName(), property.getDeclaringClass().getName()));
            }
            // EARLY EXIT!!!
            return 0;
        }
    }
    final XClass declaringClass = propertyContainer.getDeclaringClass();
    final XClass entity = propertyContainer.getEntityAtStake();
    int idPropertyCounter = 0;
    PropertyData propertyAnnotatedElement = new PropertyInferredData(declaringClass, property, propertyContainer.getClassLevelAccessType().getType(), context.getBootstrapContext().getReflectionManager());
    /*
		 * put element annotated by @Id in front
		 * since it has to be parsed before any association by Hibernate
		 */
    final XAnnotatedElement element = propertyAnnotatedElement.getProperty();
    if (hasIdAnnotation(element)) {
        inFlightPropertyDataList.add(0, propertyAnnotatedElement);
        /*
			 * The property must be put in hibernate.properties as it's a system wide property. Fixable?
			 * TODO support true/false/default on the property instead of present / not present
			 * TODO is @Column mandatory?
			 * TODO add method support
			 */
        if (context.getBuildingOptions().isSpecjProprietarySyntaxEnabled()) {
            if (element.isAnnotationPresent(Id.class) && element.isAnnotationPresent(Column.class)) {
                String columnName = element.getAnnotation(Column.class).name();
                for (XProperty prop : declaringClass.getDeclaredProperties(AccessType.FIELD.getType())) {
                    if (!prop.isAnnotationPresent(MapsId.class)) {
                        /*
							 * The detection of a configured individual JoinColumn differs between Annotation
							 * and XML configuration processing.
							 */
                        boolean isRequiredAnnotationPresent = false;
                        JoinColumns groupAnnotation = prop.getAnnotation(JoinColumns.class);
                        if ((prop.isAnnotationPresent(JoinColumn.class) && prop.getAnnotation(JoinColumn.class).name().equals(columnName))) {
                            isRequiredAnnotationPresent = true;
                        } else if (prop.isAnnotationPresent(JoinColumns.class)) {
                            for (JoinColumn columnAnnotation : groupAnnotation.value()) {
                                if (columnName.equals(columnAnnotation.name())) {
                                    isRequiredAnnotationPresent = true;
                                    break;
                                }
                            }
                        }
                        if (isRequiredAnnotationPresent) {
                            // create a PropertyData for the specJ property holding the mapping
                            PropertyData specJPropertyData = new PropertyInferredData(declaringClass, // same dec
                            prop, // the actual @XToOne property
                            propertyContainer.getClassLevelAccessType().getType(), // TODO we should get the right accessor but the same as id would do
                            context.getBootstrapContext().getReflectionManager());
                            context.getMetadataCollector().addPropertyAnnotatedWithMapsIdSpecj(entity, specJPropertyData, element.toString());
                        }
                    }
                }
            }
        }
        if (hasToOneAnnotation(element)) {
            context.getMetadataCollector().addToOneAndIdProperty(entity, propertyAnnotatedElement);
        }
        idPropertyCounter++;
    } else {
        inFlightPropertyDataList.add(propertyAnnotatedElement);
    }
    if (element.isAnnotationPresent(MapsId.class)) {
        context.getMetadataCollector().addPropertyAnnotatedWithMapsId(entity, propertyAnnotatedElement);
    }
    return idPropertyCounter;
}
Also used : BinderHelper.getPropertyOverriddenByMapperOrMapsId(org.hibernate.cfg.BinderHelper.getPropertyOverriddenByMapperOrMapsId) MapsId(jakarta.persistence.MapsId) XProperty(org.hibernate.annotations.common.reflection.XProperty) AnnotatedJoinColumn.buildJoinTableJoinColumns(org.hibernate.cfg.AnnotatedJoinColumn.buildJoinTableJoinColumns) JoinColumns(jakarta.persistence.JoinColumns) PrimaryKeyJoinColumns(jakarta.persistence.PrimaryKeyJoinColumns) MapKeyJoinColumns(jakarta.persistence.MapKeyJoinColumns) XAnnotatedElement(org.hibernate.annotations.common.reflection.XAnnotatedElement) XClass(org.hibernate.annotations.common.reflection.XClass) UniqueConstraint(jakarta.persistence.UniqueConstraint) Constraint(org.hibernate.mapping.Constraint) MappingException(org.hibernate.MappingException) MapKeyJoinColumn(jakarta.persistence.MapKeyJoinColumn) JoinColumn(jakarta.persistence.JoinColumn) PrimaryKeyJoinColumn(jakarta.persistence.PrimaryKeyJoinColumn) MapKeyColumn(jakarta.persistence.MapKeyColumn) MapKeyJoinColumn(jakarta.persistence.MapKeyJoinColumn) JoinColumn(jakarta.persistence.JoinColumn) Column(jakarta.persistence.Column) PrimaryKeyJoinColumn(jakarta.persistence.PrimaryKeyJoinColumn) OrderColumn(jakarta.persistence.OrderColumn) DiscriminatorColumn(jakarta.persistence.DiscriminatorColumn) AnnotatedDiscriminatorColumn.buildDiscriminatorColumn(org.hibernate.cfg.AnnotatedDiscriminatorColumn.buildDiscriminatorColumn) BinderHelper.getPropertyOverriddenByMapperOrMapsId(org.hibernate.cfg.BinderHelper.getPropertyOverriddenByMapperOrMapsId) Id(jakarta.persistence.Id) NaturalId(org.hibernate.annotations.NaturalId) EmbeddedId(jakarta.persistence.EmbeddedId) MapsId(jakarta.persistence.MapsId) CollectionId(org.hibernate.annotations.CollectionId)

Example 3 with Id

use of jakarta.persistence.Id in project hibernate-orm by hibernate.

the class DefaultCatalogAndSchemaTest method verifyEntityPersisterQualifiers.

private void verifyEntityPersisterQualifiers(Class<?> entityClass, ExpectedQualifier expectedQualifier) {
    // The hbm.xml mapping unfortunately sets the native entity name on top of the JPA entity name,
    // so many methods that allow retrieving the entity persister or entity metamodel from the entity class no longer work,
    // because these methods generally assume the native entity name is the FQCN.
    // Thus we use custom code.
    AbstractEntityPersister persister = (AbstractEntityPersister) sessionFactory.getRuntimeMetamodels().getMappingMetamodel().streamEntityDescriptors().filter(p -> p.getMappedClass().equals(entityClass)).findFirst().orElseThrow(() -> new IllegalStateException("Cannot find persister for " + entityClass));
    String jpaEntityName = sessionFactory.getRuntimeMetamodels().getJpaMetamodel().getEntities().stream().filter(p -> p.getBindableJavaType().equals(entityClass)).findFirst().orElseThrow(() -> new IllegalStateException("Cannot find entity metamodel for " + entityClass)).getName();
    // Table names are what's used for Query, in particular.
    verifyOnlyQualifier(persister.getTableName(), SqlType.RUNTIME, jpaEntityName, expectedQualifier);
    // Here, to simplify assertions, we assume all derived entity types have:
    // - an entity name prefixed with the name of their super entity type
    // - the same explicit catalog and schema, if any, as their super entity type
    verifyOnlyQualifier(persister.getTableNames(), SqlType.RUNTIME, jpaEntityName, expectedQualifier);
    // This will include SQL generated by ID generators in some cases, which will be validated here
    // because ID generators table/sequence names are prefixed with the owning entity name.
    verifyOnlyQualifier(persister.getSQLInsertStrings(), SqlType.RUNTIME, jpaEntityName, expectedQualifier);
    if (persister.isIdentifierAssignedByInsert()) {
        verifyOnlyQualifier(persister.getSQLIdentityInsertString(), SqlType.RUNTIME, jpaEntityName, expectedQualifier);
    }
    try {
        verifyOnlyQualifierOptional(persister.getIdentitySelectString(), SqlType.RUNTIME, jpaEntityName, expectedQualifier);
    } catch (MappingException e) {
        if (e.getMessage().contains("does not support identity key generation")) {
        // For some reason Oracle12cIdentityColumnSupport#supportsInsertSelectIdentity() returns true,
        // but getIdentitySelectString is not implemented, resulting in runtime exceptions.
        // Whatever, we'll just ignore this for now.
        } else {
            throw e;
        }
    }
    verifyOnlyQualifier(persister.getSQLUpdateStrings(), SqlType.RUNTIME, jpaEntityName, expectedQualifier);
    verifyOnlyQualifier(persister.getSQLLazyUpdateStrings(), SqlType.RUNTIME, jpaEntityName, expectedQualifier);
    verifyOnlyQualifier(persister.getSQLDeleteStrings(), SqlType.RUNTIME, jpaEntityName, expectedQualifier);
    // This is used in the "select" id generator in particular.
    verifyOnlyQualifierOptional(persister.getSelectByUniqueKeyString("basic"), SqlType.RUNTIME, jpaEntityName, expectedQualifier);
}
Also used : Entity(jakarta.persistence.Entity) Arrays(java.util.Arrays) TargetDescriptor(org.hibernate.tool.schema.spi.TargetDescriptor) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) SessionFactoryBuilder(org.hibernate.boot.SessionFactoryBuilder) SessionFactoryOptionsBuilder(org.hibernate.boot.internal.SessionFactoryOptionsBuilder) GenerationType(jakarta.persistence.GenerationType) Table(jakarta.persistence.Table) TestForIssue(org.hibernate.testing.TestForIssue) Map(java.util.Map) NameQualifierSupport(org.hibernate.engine.jdbc.env.spi.NameQualifierSupport) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) EnumSet(java.util.EnumSet) StandardServiceRegistry(org.hibernate.boot.registry.StandardServiceRegistry) Parameterized(org.junit.runners.Parameterized) SessionFactoryBuilderImpl(org.hibernate.boot.internal.SessionFactoryBuilderImpl) IdentifierGenerator(org.hibernate.id.IdentifierGenerator) Parameter(org.hibernate.annotations.Parameter) JoinColumn(jakarta.persistence.JoinColumn) Id(jakarta.persistence.Id) MetadataSources(org.hibernate.boot.MetadataSources) SchemaManagementToolCoordinator(org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator) SQLServerDialect(org.hibernate.dialect.SQLServerDialect) List(java.util.List) AfterClassOnce(org.hibernate.testing.AfterClassOnce) Basic(jakarta.persistence.Basic) MetadataImpl(org.hibernate.boot.internal.MetadataImpl) MappingException(org.hibernate.MappingException) JoinTable(jakarta.persistence.JoinTable) AbstractEntityPersister(org.hibernate.persister.entity.AbstractEntityPersister) Pattern(java.util.regex.Pattern) DelayedDropRegistryNotAvailableImpl(org.hibernate.tool.schema.spi.DelayedDropRegistryNotAvailableImpl) SharedDriverManagerConnectionProviderImpl(org.hibernate.testing.jdbc.SharedDriverManagerConnectionProviderImpl) ScriptTargetOutput(org.hibernate.tool.schema.spi.ScriptTargetOutput) BootstrapServiceRegistryBuilder(org.hibernate.boot.registry.BootstrapServiceRegistryBuilder) Inheritance(jakarta.persistence.Inheritance) AvailableSettings(org.hibernate.cfg.AvailableSettings) OneToMany(jakarta.persistence.OneToMany) RunWith(org.junit.runner.RunWith) HashMap(java.util.HashMap) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) ArrayList(java.util.ArrayList) TableGenerator(jakarta.persistence.TableGenerator) SequenceGenerator(jakarta.persistence.SequenceGenerator) SQLDelete(org.hibernate.annotations.SQLDelete) MetadataImplementor(org.hibernate.boot.spi.MetadataImplementor) ConfigurationService(org.hibernate.engine.config.spi.ConfigurationService) Environment(org.hibernate.cfg.Environment) SchemaExport(org.hibernate.tool.hbm2ddl.SchemaExport) ServiceRegistryImplementor(org.hibernate.service.spi.ServiceRegistryImplementor) SQLUpdate(org.hibernate.annotations.SQLUpdate) TargetType(org.hibernate.tool.schema.TargetType) ForeignKey(jakarta.persistence.ForeignKey) LocalTemporaryTableStrategy(org.hibernate.query.sqm.mutation.internal.temptable.LocalTemporaryTableStrategy) CustomParameterized(org.hibernate.testing.junit4.CustomParameterized) InheritanceType(jakarta.persistence.InheritanceType) StringWriter(java.io.StringWriter) BootstrapServiceRegistry(org.hibernate.boot.registry.BootstrapServiceRegistry) Test(org.junit.Test) GeneratedValue(jakarta.persistence.GeneratedValue) GenericGenerator(org.hibernate.annotations.GenericGenerator) ScriptTargetOutputToWriter(org.hibernate.tool.schema.internal.exec.ScriptTargetOutputToWriter) ElementCollection(jakarta.persistence.ElementCollection) MetadataBuilder(org.hibernate.boot.MetadataBuilder) GlobalTemporaryTableStrategy(org.hibernate.query.sqm.mutation.internal.temptable.GlobalTemporaryTableStrategy) BeforeClassOnce(org.hibernate.testing.BeforeClassOnce) Collections(java.util.Collections) SQLInsert(org.hibernate.annotations.SQLInsert) AbstractEntityPersister(org.hibernate.persister.entity.AbstractEntityPersister) MappingException(org.hibernate.MappingException)

Example 4 with Id

use of jakarta.persistence.Id in project hibernate-orm by hibernate.

the class StatelessDoWorkTest method testDoReturningWork.

@Test
public void testDoReturningWork(SessionFactoryScope scope) {
    String retrievedEntityName;
    try (StatelessSession statelessSession = scope.getSessionFactory().openStatelessSession()) {
        retrievedEntityName = statelessSession.doReturningWork((connection) -> {
            try (PreparedStatement preparedStatement = connection.prepareStatement("SELECT NAME FROM TEST_ENTITY WHERE ID = ?")) {
                preparedStatement.setInt(1, PERSISTED_TEST_ENTITY_ID);
                ResultSet resultSet = preparedStatement.executeQuery();
                String name = null;
                if (resultSet.next()) {
                    name = resultSet.getString(1);
                }
                return name;
            }
        });
    }
    assertThat(retrievedEntityName, is(EXPECTED_ENTITY_NAME));
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) Entity(jakarta.persistence.Entity) BeforeEach(org.junit.jupiter.api.BeforeEach) H2Dialect(org.hibernate.dialect.H2Dialect) StatelessSession(org.hibernate.StatelessSession) RequiresDialect(org.hibernate.testing.orm.junit.RequiresDialect) Id(jakarta.persistence.Id) DomainModel(org.hibernate.testing.orm.junit.DomainModel) PreparedStatement(java.sql.PreparedStatement) Table(jakarta.persistence.Table) Test(org.junit.jupiter.api.Test) Column(jakarta.persistence.Column) List(java.util.List) AfterEach(org.junit.jupiter.api.AfterEach) SessionFactoryScope(org.hibernate.testing.orm.junit.SessionFactoryScope) ResultSet(java.sql.ResultSet) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) SessionFactory(org.hibernate.testing.orm.junit.SessionFactory) StatelessSession(org.hibernate.StatelessSession) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) Test(org.junit.jupiter.api.Test)

Example 5 with Id

use of jakarta.persistence.Id in project boot by workoss.

the class JakartaEntityClassFinder method findTableColumnInfo.

@Override
public Optional<ClassTableColumnInfo> findTableColumnInfo(ProviderContext context) {
    return findTableColumnInfo(context, field -> !field.isAnnotationPresent(Transient.class), (tableColumnInfo, field) -> {
        String columnName = ObjectUtil.underscoreName(field.getName());
        Annotation[] annotations = field.getAnnotations();
        for (Annotation annotation : annotations) {
            if (annotation instanceof Column) {
                // 自定义列名称
                Column column = (Column) annotation;
                if (!ObjectUtil.isBlank(column.name())) {
                    columnName = column.name();
                }
            }
            if (annotation instanceof Id) {
                tableColumnInfo.idColumn(new ClassColumnInfo(field.getType(), field.getName(), columnName));
            }
        }
        if (tableColumnInfo.getIdColumn() == null && "id".equalsIgnoreCase(field.getName())) {
            tableColumnInfo.idColumn(new ClassColumnInfo(field.getType(), field.getName(), columnName));
        }
        tableColumnInfo.addColumnInfo(new ClassColumnInfo(field.getType(), field.getName(), columnName));
    });
}
Also used : Column(jakarta.persistence.Column) ClassColumnInfo(com.workoss.boot.plugin.mybatis.provider.ClassColumnInfo) Id(jakarta.persistence.Id) Annotation(java.lang.annotation.Annotation)

Aggregations

Id (jakarta.persistence.Id)5 Column (jakarta.persistence.Column)3 Entity (jakarta.persistence.Entity)3 Table (jakarta.persistence.Table)3 List (java.util.List)3 JoinColumn (jakarta.persistence.JoinColumn)2 Arrays (java.util.Arrays)2 Collections (java.util.Collections)2 MappingException (org.hibernate.MappingException)2 ClassColumnInfo (com.workoss.boot.plugin.mybatis.provider.ClassColumnInfo)1 Basic (jakarta.persistence.Basic)1 DiscriminatorColumn (jakarta.persistence.DiscriminatorColumn)1 ElementCollection (jakarta.persistence.ElementCollection)1 EmbeddedId (jakarta.persistence.EmbeddedId)1 ForeignKey (jakarta.persistence.ForeignKey)1 GeneratedValue (jakarta.persistence.GeneratedValue)1 GenerationType (jakarta.persistence.GenerationType)1 Inheritance (jakarta.persistence.Inheritance)1 InheritanceType (jakarta.persistence.InheritanceType)1 JoinColumns (jakarta.persistence.JoinColumns)1