Search in sources :

Example 1 with Entity

use of jakarta.persistence.Entity in project jOOQ by jOOQ.

the class JPADatabase method export.

@Override
protected void export() throws Exception {
    String packages = getProperties().getProperty("packages");
    if (isBlank(packages)) {
        packages = "";
        log.warn("No packages defined", "It is highly recommended that you provide explicit packages to scan");
    }
    // [#9058] Properties use camelCase notation.
    boolean useAttributeConverters = Boolean.parseBoolean(getProperties().getProperty("useAttributeConverters", getProperties().getProperty("use-attribute-converters", "true")));
    // [#6709] Apply default settings first, then allow custom overrides
    Map<String, Object> settings = new LinkedHashMap<>();
    settings.put("hibernate.dialect", HIBERNATE_DIALECT);
    settings.put("javax.persistence.schema-generation-connection", connection());
    settings.put("javax.persistence.create-database-schemas", true);
    // [#5607] JPADatabase causes warnings - This prevents them
    settings.put(AvailableSettings.CONNECTION_PROVIDER, connectionProvider());
    for (Entry<Object, Object> entry : getProperties().entrySet()) {
        String key = "" + entry.getKey();
        if (key.startsWith("hibernate.") || key.startsWith("javax.persistence.") || key.startsWith("jakarta.persistence."))
            userSettings.put(key, entry.getValue());
    }
    settings.putAll(userSettings);
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
    builder.applySettings(settings);
    MetadataSources metadata = new MetadataSources(builder.applySettings(settings).build());
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
    scanner.addIncludeFilter(new AnnotationTypeFilter(Entity.class));
    // [#5845] Use the correct ClassLoader to load the jpa entity classes defined in the user project
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    int count = 0;
    for (String pkg : packages.split(",")) {
        for (BeanDefinition def : scanner.findCandidateComponents(defaultIfBlank(pkg, "").trim())) {
            Class<?> klass = Class.forName(def.getBeanClassName(), true, cl);
            log.debug("Entity added", klass.getName());
            metadata.addAnnotatedClass(klass);
            count++;
        }
    }
    if (count > 0)
        log.info("Entities added", "Number of entities added: " + count);
    else
        log.warn("No entities added", ("" + "No entities were added to the MetadataSources\n" + "\n" + "This can have several reasons, including:\n" + "- The packages you've listed do not exist ({packages})\n" + "- The entities in the listed packages are not on the JPADatabase classpath (you must compile them before running jOOQ's codegen, see \"how to organise your dependencies\" in the manual: https://www.jooq.org/doc/latest/manual/code-generation/codegen-jpa/!)\n" + "").replace("{packages}", packages));
    // This seems to be the way to do this in idiomatic Hibernate 5.0 API
    // See also: http://stackoverflow.com/q/32178041/521799
    // SchemaExport export = new SchemaExport((MetadataImplementor) metadata.buildMetadata(), connection);
    // export.create(true, true);
    // Hibernate 5.2 broke 5.0 API again. Here's how to do this now:
    SchemaExport export = new SchemaExport();
    export.create(EnumSet.of(TargetType.DATABASE), metadata.buildMetadata());
    if (useAttributeConverters)
        loadAttributeConverters(metadata.getAnnotatedClasses());
}
Also used : AnnotationTypeFilter(org.springframework.core.type.filter.AnnotationTypeFilter) Entity(jakarta.persistence.Entity) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) MetadataSources(org.hibernate.boot.MetadataSources) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) LinkedHashMap(java.util.LinkedHashMap) ClassPathScanningCandidateComponentProvider(org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider) SchemaExport(org.hibernate.tool.hbm2ddl.SchemaExport)

Example 2 with Entity

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

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

the class JavaEntity method buildName.

protected String buildName() {
    Class<?> type = getType().getType();
    Entity entity = type.getAnnotation(Entity.class);
    String entityName = entity.name();
    if (ExpressionTools.stringIsEmpty(entityName)) {
        name = type.getSimpleName();
    }
    return name;
}
Also used : Entity(jakarta.persistence.Entity) IEntity(org.eclipse.persistence.jpa.jpql.tools.spi.IEntity)

Example 4 with Entity

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

the class TestProcessor method testGenerate.

private void testGenerate(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 {}}");
    Result result = runProject(name, getJavacOptions("-A" + CanonicalModelProperties.CANONICAL_MODEL_GENERATE_GENERATED + "=false", "-Aeclipselink.logging.level.processor=OFF"), Arrays.asList(entity), 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()).noneMatch(s -> s.contains("Generated")));
    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)

Example 5 with Entity

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

the class TestProcessor method testGenerateComment.

private void testGenerateComment(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 {}}");
    Result result = runProject(name, getJavacOptions("-A" + CanonicalModelProperties.CANONICAL_MODEL_GENERATE_COMMENTS + "=false", "-Aeclipselink.logging.level.processor=OFF"), Arrays.asList(entity), 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()).noneMatch(s -> s.contains("comments=")));
    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