Search in sources :

Example 1 with ResourceRegistry

use of org.hibernate.resource.jdbc.ResourceRegistry 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 ResourceRegistry

use of org.hibernate.resource.jdbc.ResourceRegistry in project hibernate-orm by hibernate.

the class AbstractBatchImpl method releaseStatements.

protected void releaseStatements() {
    final LinkedHashMap<String, PreparedStatement> statements = getStatements();
    final ResourceRegistry resourceRegistry = jdbcCoordinator.getLogicalConnection().getResourceRegistry();
    for (PreparedStatement statement : statements.values()) {
        clearBatch(statement);
        resourceRegistry.release(statement);
    }
    // IMPL NOTE: If the statements are not cleared and JTA is being used, then
    // jdbcCoordinator.afterStatementExecution() will abort the batch and a
    // warning will be logged. To avoid the warning, clear statements first,
    // before calling jdbcCoordinator.afterStatementExecution().
    statements.clear();
    jdbcCoordinator.afterStatementExecution();
}
Also used : PreparedStatement(java.sql.PreparedStatement) ResourceRegistry(org.hibernate.resource.jdbc.ResourceRegistry)

Example 3 with ResourceRegistry

use of org.hibernate.resource.jdbc.ResourceRegistry in project hibernate-orm by hibernate.

the class AggressiveReleaseTest method testReleaseCircumventedManually.

@Test
public void testReleaseCircumventedManually() {
    connectionProvider.clear();
    connectionProvider.clear();
    ResourceRegistry registry = sessionFactoryScope().fromSession(session -> {
        JdbcCoordinatorImpl jdbcCoord = (JdbcCoordinatorImpl) session.getJdbcCoordinator();
        ResourceRegistry resourceRegistry = jdbcCoord.getLogicalConnection().getResourceRegistry();
        try {
            PreparedStatement ps = jdbcCoord.getStatementPreparer().prepareStatement("insert into SANDBOX_JDBC_TST( ID, NAME ) values ( ?, ? )");
            ps.setLong(1, 1);
            ps.setString(2, "name");
            jdbcCoord.getResultSetReturn().execute(ps);
            assertTrue(resourceRegistry.hasRegisteredResources());
            assertEquals(1, connectionProvider.getAcquiredConnections().size());
            assertEquals(0, connectionProvider.getReleasedConnections().size());
            resourceRegistry.release(ps);
            jdbcCoord.afterStatementExecution();
            assertFalse(resourceRegistry.hasRegisteredResources());
            assertEquals(0, connectionProvider.getAcquiredConnections().size());
            assertEquals(1, connectionProvider.getReleasedConnections().size());
            // disable releases...
            jdbcCoord.disableReleases();
            // open a result set...
            ps = jdbcCoord.getStatementPreparer().prepareStatement("select * from SANDBOX_JDBC_TST");
            jdbcCoord.getResultSetReturn().extract(ps);
            assertTrue(resourceRegistry.hasRegisteredResources());
            assertEquals(1, connectionProvider.getAcquiredConnections().size());
            assertEquals(1, connectionProvider.getReleasedConnections().size());
            // and close it...
            resourceRegistry.release(ps);
            jdbcCoord.afterStatementExecution();
            // the release should be circumvented...
            assertFalse(resourceRegistry.hasRegisteredResources());
            assertEquals(1, connectionProvider.getAcquiredConnections().size());
            assertEquals(1, connectionProvider.getReleasedConnections().size());
        // let the close of the logical connection below release all resources (hopefully)...
        } catch (SQLException sqle) {
            fail("incorrect exception type : sqlexception");
        } finally {
            jdbcCoord.close();
        }
        return resourceRegistry;
    });
    assertFalse(registry.hasRegisteredResources());
    assertEquals(0, connectionProvider.getAcquiredConnections().size());
    assertEquals(2, connectionProvider.getReleasedConnections().size());
}
Also used : JdbcCoordinatorImpl(org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) ResourceRegistry(org.hibernate.resource.jdbc.ResourceRegistry) BaseSessionFactoryFunctionalTest(org.hibernate.testing.orm.junit.BaseSessionFactoryFunctionalTest) Test(org.junit.jupiter.api.Test)

Example 4 with ResourceRegistry

use of org.hibernate.resource.jdbc.ResourceRegistry in project hibernate-orm by hibernate.

the class AggressiveReleaseTest method testBasicRelease.

@Test
public void testBasicRelease() {
    connectionProvider.clear();
    ResourceRegistry registry = sessionFactoryScope().fromSession(session -> {
        JdbcCoordinatorImpl jdbcCoord = (JdbcCoordinatorImpl) session.getJdbcCoordinator();
        ResourceRegistry resourceRegistry = jdbcCoord.getLogicalConnection().getResourceRegistry();
        try {
            PreparedStatement ps = jdbcCoord.getStatementPreparer().prepareStatement("insert into SANDBOX_JDBC_TST( ID, NAME ) values ( ?, ? )");
            ps.setLong(1, 1);
            ps.setString(2, "name");
            jdbcCoord.getResultSetReturn().execute(ps);
            assertTrue(jdbcCoord.getLogicalConnection().getResourceRegistry().hasRegisteredResources());
            assertEquals(1, connectionProvider.getAcquiredConnections().size());
            assertEquals(0, connectionProvider.getReleasedConnections().size());
            resourceRegistry.release(ps);
            jdbcCoord.afterStatementExecution();
            assertFalse(resourceRegistry.hasRegisteredResources());
            assertEquals(0, connectionProvider.getAcquiredConnections().size());
            assertEquals(1, connectionProvider.getReleasedConnections().size());
        } catch (SQLException sqle) {
            fail("incorrect exception type : sqlexception");
        } finally {
            jdbcCoord.close();
        }
        return resourceRegistry;
    });
    assertFalse(registry.hasRegisteredResources());
}
Also used : JdbcCoordinatorImpl(org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) ResourceRegistry(org.hibernate.resource.jdbc.ResourceRegistry) BaseSessionFactoryFunctionalTest(org.hibernate.testing.orm.junit.BaseSessionFactoryFunctionalTest) Test(org.junit.jupiter.api.Test)

Example 5 with ResourceRegistry

use of org.hibernate.resource.jdbc.ResourceRegistry in project hibernate-orm by hibernate.

the class AggressiveReleaseTest method testReleaseCircumventedByHeldResources.

@Test
public void testReleaseCircumventedByHeldResources() {
    connectionProvider.clear();
    ResourceRegistry registry = sessionFactoryScope().fromSession(session -> {
        JdbcCoordinatorImpl jdbcCoord = (JdbcCoordinatorImpl) session.getJdbcCoordinator();
        ResourceRegistry resourceRegistry = jdbcCoord.getLogicalConnection().getResourceRegistry();
        try {
            PreparedStatement ps = jdbcCoord.getStatementPreparer().prepareStatement("insert into SANDBOX_JDBC_TST( ID, NAME ) values ( ?, ? )");
            ps.setLong(1, 1);
            ps.setString(2, "name");
            jdbcCoord.getResultSetReturn().execute(ps);
            assertTrue(resourceRegistry.hasRegisteredResources());
            assertEquals(1, connectionProvider.getAcquiredConnections().size());
            assertEquals(0, connectionProvider.getReleasedConnections().size());
            resourceRegistry.release(ps);
            jdbcCoord.afterStatementExecution();
            assertFalse(resourceRegistry.hasRegisteredResources());
            assertEquals(0, connectionProvider.getAcquiredConnections().size());
            assertEquals(1, connectionProvider.getReleasedConnections().size());
            // open a result set and hold it open...
            ps = jdbcCoord.getStatementPreparer().prepareStatement("select * from SANDBOX_JDBC_TST");
            jdbcCoord.getResultSetReturn().extract(ps);
            assertTrue(resourceRegistry.hasRegisteredResources());
            assertEquals(1, connectionProvider.getAcquiredConnections().size());
            assertEquals(1, connectionProvider.getReleasedConnections().size());
            // open a second result set
            PreparedStatement ps2 = jdbcCoord.getStatementPreparer().prepareStatement("select * from SANDBOX_JDBC_TST");
            jdbcCoord.getResultSetReturn().execute(ps);
            assertTrue(resourceRegistry.hasRegisteredResources());
            assertEquals(1, connectionProvider.getAcquiredConnections().size());
            assertEquals(1, connectionProvider.getReleasedConnections().size());
            // and close it...
            resourceRegistry.release(ps2);
            jdbcCoord.afterStatementExecution();
            // the release should be circumvented...
            assertTrue(resourceRegistry.hasRegisteredResources());
            assertEquals(1, connectionProvider.getAcquiredConnections().size());
            assertEquals(1, connectionProvider.getReleasedConnections().size());
        // let the close of the logical connection below release all resources (hopefully)...
        } catch (SQLException sqle) {
            fail("incorrect exception type : sqlexception");
        } finally {
            jdbcCoord.close();
        }
        return resourceRegistry;
    });
    assertFalse(registry.hasRegisteredResources());
    assertEquals(0, connectionProvider.getAcquiredConnections().size());
    assertEquals(2, connectionProvider.getReleasedConnections().size());
}
Also used : JdbcCoordinatorImpl(org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) ResourceRegistry(org.hibernate.resource.jdbc.ResourceRegistry) BaseSessionFactoryFunctionalTest(org.hibernate.testing.orm.junit.BaseSessionFactoryFunctionalTest) Test(org.junit.jupiter.api.Test)

Aggregations

ResourceRegistry (org.hibernate.resource.jdbc.ResourceRegistry)5 PreparedStatement (java.sql.PreparedStatement)4 Test (org.junit.jupiter.api.Test)4 SQLException (java.sql.SQLException)3 JdbcCoordinatorImpl (org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl)3 BaseSessionFactoryFunctionalTest (org.hibernate.testing.orm.junit.BaseSessionFactoryFunctionalTest)3 Entity (jakarta.persistence.Entity)1 Id (jakarta.persistence.Id)1 Table (jakarta.persistence.Table)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Method (java.lang.reflect.Method)1 Arrays (java.util.Arrays)1 Collections (java.util.Collections)1 List (java.util.List)1 Objects (java.util.Objects)1 Optional (java.util.Optional)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 Predicate (java.util.function.Predicate)1 Collectors (java.util.stream.Collectors)1 Stream (java.util.stream.Stream)1