Search in sources :

Example 6 with Entity

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

the class JPAXMLOverriddenAnnotationReader method getEntity.

private Entity getEntity(ManagedType element, XMLContext.Default defaults) {
    if (element == null) {
        return defaults.canUseJavaAnnotations() ? getPhysicalAnnotation(Entity.class) : null;
    } else {
        if (element instanceof JaxbEntity) {
            JaxbEntity entityElement = (JaxbEntity) element;
            AnnotationDescriptor entity = new AnnotationDescriptor(Entity.class);
            copyAttribute(entity, "name", entityElement.getName(), false);
            if (defaults.canUseJavaAnnotations() && StringHelper.isEmpty((String) entity.valueOf("name"))) {
                Entity javaAnn = getPhysicalAnnotation(Entity.class);
                if (javaAnn != null) {
                    entity.setValue("name", javaAnn.name());
                }
            }
            return AnnotationFactory.create(entity);
        } else {
            // this is not an entity
            return null;
        }
    }
}
Also used : AnnotationDescriptor(org.hibernate.annotations.common.annotationfactory.AnnotationDescriptor) Entity(jakarta.persistence.Entity) JaxbEntity(org.hibernate.boot.jaxb.mapping.spi.JaxbEntity) JaxbEntity(org.hibernate.boot.jaxb.mapping.spi.JaxbEntity)

Example 7 with Entity

use of jakarta.persistence.Entity 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 8 with Entity

use of jakarta.persistence.Entity in project eclipselink by eclipse-ee4j.

the class TestProcessor method testProc.

private void testProc(String name, String pxml, String oxml) throws Exception {
    TestFO entity = new TestFO("org.Sample", "package org; import jakarta.persistence.Entity; @Entity public class Sample { public  Sample() {} public int getX() {return 1;} interface A {}}");
    TestFO nonSC = new TestFO("some.IF", "package some; public class IF { public IF() {}}");
    TestFO nonAnn = new TestFO("custom.Ann", "package custom; public @interface Ann { }");
    TestFO nonExt = new TestFO("external.Cls", "package external; public class Cls { public Cls(){}}");
    TestFO nonEntity = new TestFO("org.NotE", "package org; import jakarta.persistence.Entity; public class NotE extends some.IF { public  NotE() {} @custom.Ann public external.Cls getW() {return new Object();}}");
    TestFO generated8 = new TestFO("org.Gen8", "package org; import jakarta.annotation.Generated; @Generated(\"com.example.Generator\") public class Gen8 { public  Gen8() {} public int getY() {return 42;}}");
    TestFO generated9 = new TestFO("org.Gen9", "package org; @javax.annotation.processing.Generated(\"com.example.Generator\") public class Gen9 { public  Gen9() {} public int getZ() {return 9*42;}}");
    Result result = runProject(name, getJavacOptions("-Aeclipselink.logging.level.processor=OFF"), Arrays.asList(entity, nonSC, nonAnn, nonExt, nonEntity, generated8, generated9), pxml, oxml);
    File outputFile = new File(result.srcOut, "org/Sample_.java");
    Assert.assertTrue("Model file not generated", outputFile.exists());
    Assert.assertTrue(Files.lines(outputFile.toPath()).anyMatch(s -> s.contains("@StaticMetamodel(Sample.class)")));
}
Also used : Entity(jakarta.persistence.Entity) Arrays(java.util.Arrays) CanonicalModelProcessor(org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor) BeforeClass(org.junit.BeforeClass) URL(java.net.URL) ArrayList(java.util.ArrayList) CompilationTask(javax.tools.JavaCompiler.CompilationTask) Diagnostic(javax.tools.Diagnostic) URI(java.net.URI) Path(java.nio.file.Path) DiagnosticCollector(javax.tools.DiagnosticCollector) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) PrintWriter(java.io.PrintWriter) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) StandardLocation(javax.tools.StandardLocation) Files(java.nio.file.Files) JavaCompiler(javax.tools.JavaCompiler) BufferedWriter(java.io.BufferedWriter) StandardOpenOption(java.nio.file.StandardOpenOption) CanonicalModelProperties(org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProperties) IOException(java.io.IOException) Test(org.junit.Test) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) File(java.io.File) Generated(jakarta.annotation.Generated) JavaFileObject(javax.tools.JavaFileObject) FileVisitResult(java.nio.file.FileVisitResult) StandardJavaFileManager(javax.tools.StandardJavaFileManager) List(java.util.List) Assert(org.junit.Assert) Collections(java.util.Collections) ToolProvider(javax.tools.ToolProvider) File(java.io.File) FileVisitResult(java.nio.file.FileVisitResult)

Example 9 with Entity

use of jakarta.persistence.Entity in project eclipselink by eclipse-ee4j.

the class TestProcessor method testTypeUse.

public void testTypeUse(String name, String pxml, String oxml) throws Exception {
    TestFO entity = new TestFO("org.Ent", "package org; @jakarta.persistence.Entity public class Ent { @org.ann.NotNull private byte[] bytes;}");
    TestFO ann = new TestFO("org.ann.NotNull", "package org.ann; @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) public @interface NotNull {}");
    Result result = runProject(name, getJavacOptions("-Aeclipselink.logging.level.processor=OFF"), Arrays.asList(entity, ann), pxml, oxml);
    File outputFile = new File(result.srcOut, "org/Ent_.java");
    Assert.assertTrue("Model file not generated", outputFile.exists());
    Assert.assertTrue(Files.lines(outputFile.toPath()).noneMatch(s -> s.contains("NotNull")));
    Assert.assertTrue("Compilation failed", result.success);
}
Also used : Entity(jakarta.persistence.Entity) Arrays(java.util.Arrays) CanonicalModelProcessor(org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor) BeforeClass(org.junit.BeforeClass) URL(java.net.URL) ArrayList(java.util.ArrayList) CompilationTask(javax.tools.JavaCompiler.CompilationTask) Diagnostic(javax.tools.Diagnostic) URI(java.net.URI) Path(java.nio.file.Path) DiagnosticCollector(javax.tools.DiagnosticCollector) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) PrintWriter(java.io.PrintWriter) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) StandardLocation(javax.tools.StandardLocation) Files(java.nio.file.Files) JavaCompiler(javax.tools.JavaCompiler) BufferedWriter(java.io.BufferedWriter) StandardOpenOption(java.nio.file.StandardOpenOption) CanonicalModelProperties(org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProperties) IOException(java.io.IOException) Test(org.junit.Test) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) File(java.io.File) Generated(jakarta.annotation.Generated) JavaFileObject(javax.tools.JavaFileObject) FileVisitResult(java.nio.file.FileVisitResult) StandardJavaFileManager(javax.tools.StandardJavaFileManager) List(java.util.List) Assert(org.junit.Assert) Collections(java.util.Collections) ToolProvider(javax.tools.ToolProvider) File(java.io.File) FileVisitResult(java.nio.file.FileVisitResult)

Aggregations

Entity (jakarta.persistence.Entity)9 Arrays (java.util.Arrays)6 Collections (java.util.Collections)6 List (java.util.List)6 ArrayList (java.util.ArrayList)5 Test (org.junit.Test)5 Generated (jakarta.annotation.Generated)4 BufferedWriter (java.io.BufferedWriter)4 File (java.io.File)4 IOException (java.io.IOException)4 PrintWriter (java.io.PrintWriter)4 URI (java.net.URI)4 URL (java.net.URL)4 FileVisitResult (java.nio.file.FileVisitResult)4 Files (java.nio.file.Files)4 Path (java.nio.file.Path)4 SimpleFileVisitor (java.nio.file.SimpleFileVisitor)4 StandardOpenOption (java.nio.file.StandardOpenOption)4 BasicFileAttributes (java.nio.file.attribute.BasicFileAttributes)4 Diagnostic (javax.tools.Diagnostic)4