From f6dbbe7dbb49cafd80ee9fb5f5ec262d56ed103f Mon Sep 17 00:00:00 2001 From: marko-bekhta Date: Mon, 13 Oct 2025 15:30:28 +0200 Subject: [PATCH] HHH-19846 Drop JUnit 4 usage --- .../bytecode/ReflectionOptimizerTest.java | 37 +- .../lazy/LazySqlResultMappingTest.java | 142 ++-- .../enhancement/lazy/fetch/FetchTest.java | 123 ++- .../lazy/proxy/NoProxyFactoryTests.java | 38 +- .../lazy/proxy/ProxyDeletionTest.java | 122 ++- .../MergeEnhancedEntityDynamicUpdateTest.java | 94 +-- .../tracker/CompositeOwnerTrackerTest.java | 4 +- .../enhancement/tracker/DirtyTrackerTest.java | 14 +- ...deEnhancedImmutableReferenceCacheTest.java | 99 +-- .../orm/test/cache/CacheAnnotationTests.java | 52 +- .../test/cache/CacheRegionStatisticsTest.java | 79 +- .../cache/CollectionCacheEvictionTest.java | 484 ++++++------ ...ctionCacheEvictionWithoutMappedByTest.java | 222 +++--- .../EntityUpdateCacheModeIgnoreTest.java | 139 ++-- .../orm/test/cache/InsertedDataTest.java | 287 +++---- .../orm/test/cache/LockModeTest.java | 204 +++-- ...ManyToManyCollectionCacheEvictionTest.java | 115 ++- .../cache/NoCachingRegionFactoryTest.java | 36 +- .../NonRootEntityWithCacheAnnotationTest.java | 10 +- ...RootEntityWithCacheableAnnotationTest.java | 22 +- .../orm/test/cache/ReferenceCacheTest.java | 96 ++- .../test/cache/RefreshUpdatedDataTest.java | 267 ++++--- .../SharedDomainDataAndQueryResultsTest.java | 140 ++-- .../orm/test/cache/SharedRegionTest.java | 80 +- .../cache/SingleRegisteredProviderTest.java | 29 +- ...oncurrencyCollectionCacheEvictionTest.java | 109 ++- .../NonAggregatedCompositeIdCachingTest.java | 5 +- .../caching/mocked/CacheAccessTypeTest.java | 7 +- .../CacheKeyImplementationHashCodeTest.java | 6 +- .../caching/mocked/NaturalIdCacheKeyTest.java | 25 +- .../caching/mocked/ReadWriteCacheTest.java | 206 ++--- .../cascade/RefreshLazyOneToManyTest.java | 58 +- .../orm/test/event/MergeContextTest.java | 589 +++++++------- ...ertEventListenerVetoBidirectionalTest.java | 50 +- ...rtEventListenerVetoUnidirectionalTest.java | 52 +- .../SessionEventListenersManagerTest.java | 17 +- .../AbstractCollectionEventTest.java | 732 ++++++++++-------- .../collection/BrokenCollectionEventTest.java | 320 ++------ ...bstractAssociationCollectionEventTest.java | 32 +- ...ManyToManyBagToSetCollectionEventTest.java | 8 +- ...ManyToManySetToSetCollectionEventTest.java | 6 +- ...tionalOneToManyBagCollectionEventTest.java | 6 +- ...eToManyBagSubclassCollectionEventTest.java | 6 +- ...tionalOneToManySetCollectionEventTest.java | 6 +- ...ionalManyToManyBagCollectionEventTest.java | 6 +- ...tionalOneToManyBagCollectionEventTest.java | 6 +- ...tionalOneToManySetCollectionEventTest.java | 6 +- .../AggregatedCollectionEventListener.java | 4 + .../detached/BadMergeHandlingTest.java | 133 ++-- .../DetachedMultipleCollectionChangeTest.java | 291 ++++--- .../detached/MergeCollectionEventTest.java | 192 ++--- .../values/ValuesBagCollectionEventTest.java | 6 +- .../MergeListPreAndPostPersistTest.java | 66 +- ...ListPreAndPostPersistWithIdentityTest.java | 86 +- .../orm/test/events/CallbackTest.java | 101 +-- .../events/DefaultEntityListenerTest.java | 92 +-- .../events/EventEngineContributionsTests.java | 73 +- .../orm/test/events/InterceptorTest.java | 82 +- .../events/LegacyPostCommitListenerTest.java | 230 +++--- .../orm/test/events/ListenerTest.java | 84 +- .../test/events/PostCommitListenerTest.java | 280 +++---- .../orm/test/eviction/EvictionTest.java | 155 ++-- .../exception/SQLExceptionConversionTest.java | 202 +++-- .../orm/test/extendshbm/ExtendsTest.java | 17 +- .../testing/orm/junit/SessionFactory.java | 11 + .../orm/junit/SessionFactoryExtension.java | 5 +- 66 files changed, 3417 insertions(+), 3886 deletions(-) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/ReflectionOptimizerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/ReflectionOptimizerTest.java index 0ff9961aab52..895f81e36785 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/ReflectionOptimizerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/ReflectionOptimizerTest.java @@ -5,31 +5,30 @@ package org.hibernate.orm.test.bytecode; import static org.hibernate.bytecode.internal.BytecodeProviderInitiator.buildDefaultBytecodeProvider; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import org.hibernate.bytecode.spi.BytecodeProvider; import org.hibernate.bytecode.spi.ReflectionOptimizer; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * @author Steve Ebersole */ -public class ReflectionOptimizerTest extends BaseUnitTestCase { +public class ReflectionOptimizerTest { private static BytecodeProvider provider; - @BeforeClass + @BeforeAll public static void initBytecodeProvider() { provider = buildDefaultBytecodeProvider(); } - @AfterClass + @AfterAll public static void clearBytecodeProvider() { if ( provider != null ) { provider.resetCaches(); @@ -50,11 +49,11 @@ public void testReflectionOptimization() { assertNotNull( optimizer.getAccessOptimizer() ); Object instance = optimizer.getInstantiationOptimizer().newInstance(); - assertEquals( instance.getClass(), Bean.class ); - Bean bean = ( Bean ) instance; + assertEquals( Bean.class, instance.getClass() ); + Bean bean = (Bean) instance; optimizer.getAccessOptimizer().setPropertyValues( bean, BeanReflectionHelper.TEST_VALUES ); - assertEquals( bean.getSomeString(), BeanReflectionHelper.TEST_VALUES[0] ); + assertEquals( BeanReflectionHelper.TEST_VALUES[0], bean.getSomeString() ); Object[] values = optimizer.getAccessOptimizer().getPropertyValues( bean ); assertEquivalent( values, BeanReflectionHelper.TEST_VALUES ); } @@ -62,23 +61,25 @@ public void testReflectionOptimization() { @Test @JiraKey(value = "HHH-12584") public void testAbstractClass() { - ReflectionOptimizer reflectionOptimizer = provider.getReflectionOptimizer( AbstractClass.class, new String[]{ "getProperty" }, - new String[]{ "setProperty" }, new Class[]{ String.class } ); + ReflectionOptimizer reflectionOptimizer = provider.getReflectionOptimizer( AbstractClass.class, + new String[] {"getProperty"}, + new String[] {"setProperty"}, new Class[] {String.class} ); assertNotNull( reflectionOptimizer ); } @Test @JiraKey(value = "HHH-12584") public void testInterface() { - ReflectionOptimizer reflectionOptimizer = provider.getReflectionOptimizer( Interface.class, new String[]{ "getProperty" }, - new String[]{ "setProperty" }, new Class[]{ String.class } ); + ReflectionOptimizer reflectionOptimizer = provider.getReflectionOptimizer( Interface.class, + new String[] {"getProperty"}, + new String[] {"setProperty"}, new Class[] {String.class} ); assertNotNull( reflectionOptimizer ); } private void assertEquivalent(Object[] checkValues, Object[] values) { - assertEquals( "Different lengths", checkValues.length, values.length ); + assertEquals( checkValues.length, values.length, "Different lengths" ); for ( int i = 0; i < checkValues.length; i++ ) { - assertEquals( "different values at index [" + i + "]", checkValues[i], values[i] ); + assertEquals( checkValues[i], values[i], "different values at index [" + i + "]" ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazySqlResultMappingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazySqlResultMappingTest.java index 0074cfbe3a56..65407ae02e65 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazySqlResultMappingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazySqlResultMappingTest.java @@ -8,13 +8,14 @@ import org.hibernate.Hibernate; -import org.hibernate.testing.FailureExpected; +import org.hibernate.testing.bytecode.enhancement.extension.BytecodeEnhanced; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.FailureExpected; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; -import org.junit.runner.RunWith; import jakarta.persistence.Basic; import jakarta.persistence.Entity; @@ -26,102 +27,103 @@ import jakarta.persistence.SqlResultSetMapping; import jakarta.persistence.Table; -import org.hibernate.testing.bytecode.enhancement.BytecodeEnhancerRunner; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; - -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author Jan Schatteman * @author Christian Beikov */ -@RunWith( BytecodeEnhancerRunner.class ) -public class LazySqlResultMappingTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ User.class }; - } - - @Before - public void prepareData() { - doInHibernate( this::sessionFactory, - session -> { - session.persist(new User(1L, (byte)1)); - } +@DomainModel( + annotatedClasses = { + LazySqlResultMappingTest.User.class + } +) +@SessionFactory +@BytecodeEnhanced +public class LazySqlResultMappingTest { + + @BeforeEach + public void prepareData(SessionFactoryScope scope) { + scope.inTransaction( session -> { + session.persist( new User( 1L, (byte) 1 ) ); + } ); } - @After - public void cleanupData() { - doInHibernate( this::sessionFactory, - session -> { - session.createMutationQuery("delete from User").executeUpdate(); - } - ); + @AfterEach + public void cleanupData(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Test - public void testGetIdAndPrincipalUsingFieldResults() { - doInHibernate( this::sessionFactory, - session -> { - List users = session.createNamedQuery( "getIdAndPrincipalUsingFieldResults", User.class ).getResultList(); - Assertions.assertTrue( Hibernate.isPropertyInitialized( users.get(0), "principal" ) ); - } + public void testGetIdAndPrincipalUsingFieldResults(SessionFactoryScope scope) { + scope.inTransaction( session -> { + List users = session.createNamedQuery( "getIdAndPrincipalUsingFieldResults", User.class ) + .getResultList(); + Assertions.assertTrue( Hibernate.isPropertyInitialized( users.get( 0 ), "principal" ) ); + } ); } @Test - @JiraKey( value = "HHH-953" ) - public void testGetIdAndPrincipalWithoutUsingFieldResults() { - doInHibernate( this::sessionFactory, - session -> { - List users = session.createNamedQuery( "getIdAndPrincipalWithoutUsingFieldResults", User.class ).getResultList(); - Assertions.assertTrue( Hibernate.isPropertyInitialized( users.get(0), "principal" ) ); - } + @JiraKey(value = "HHH-953") + public void testGetIdAndPrincipalWithoutUsingFieldResults(SessionFactoryScope scope) { + scope.inTransaction( session -> { + List users = session.createNamedQuery( "getIdAndPrincipalWithoutUsingFieldResults", + User.class ).getResultList(); + Assertions.assertTrue( Hibernate.isPropertyInitialized( users.get( 0 ), "principal" ) ); + } ); } @Test - @JiraKey( value = "HHH-15667" ) - @FailureExpected(jiraKey = "HHH-15667", message = "SQLGrammarException: Unable to find column position by name: principal") - public void testGetIdWithoutUsingFieldResults() { - doInHibernate( this::sessionFactory, - session -> { - List users = session.createNamedQuery( "getIdWithoutUsingFieldResults", User.class ).getResultList(); - Assertions.assertFalse( Hibernate.isPropertyInitialized( users.get(0), "principal" ) ); - } + @JiraKey(value = "HHH-15667") + @FailureExpected(jiraKey = "HHH-15667", + reason = "SQLGrammarException: Unable to find column position by name: principal") + public void testGetIdWithoutUsingFieldResults(SessionFactoryScope scope) { + scope.inTransaction( session -> { + List users = session.createNamedQuery( "getIdWithoutUsingFieldResults", User.class ) + .getResultList(); + Assertions.assertFalse( Hibernate.isPropertyInitialized( users.get( 0 ), "principal" ) ); + } ); } @Test - public void testGetIdUsingFieldResults() { - doInHibernate( this::sessionFactory, - session -> { - List users = session.createNamedQuery( "getIdUsingFieldResults", User.class ).getResultList(); - Assertions.assertFalse( Hibernate.isPropertyInitialized( users.get(0), "principal" ) ); - } + public void testGetIdUsingFieldResults(SessionFactoryScope scope) { + scope.inTransaction( session -> { + List users = session.createNamedQuery( "getIdUsingFieldResults", User.class ).getResultList(); + Assertions.assertFalse( Hibernate.isPropertyInitialized( users.get( 0 ), "principal" ) ); + } ); } - @NamedNativeQuery(name = "getIdAndPrincipalUsingFieldResults", query = "select u.id as id, u.principal as principal from user_tbl u", resultSetMapping = "id_and_principal_with_fields") - @NamedNativeQuery(name = "getIdUsingFieldResults", query = "select u.id as id from user_tbl u", resultSetMapping = "id_with_fields") - @NamedNativeQuery(name = "getIdAndPrincipalWithoutUsingFieldResults", query = "select u.id as id, u.principal as principal from user_tbl u", resultSetMapping = "without_fields") - @NamedNativeQuery(name = "getIdWithoutUsingFieldResults", query = "select u.id as id from user_tbl u", resultSetMapping = "without_fields") - - @SqlResultSetMapping( name = "id_and_principal_with_fields", - entities = @EntityResult( entityClass = User.class, fields = { @FieldResult(name = "id", column = "id"), @FieldResult(name = "principal", column = "principal") } ) + @NamedNativeQuery(name = "getIdAndPrincipalUsingFieldResults", + query = "select u.id as id, u.principal as principal from user_tbl u", + resultSetMapping = "id_and_principal_with_fields") + @NamedNativeQuery(name = "getIdUsingFieldResults", query = "select u.id as id from user_tbl u", + resultSetMapping = "id_with_fields") + @NamedNativeQuery(name = "getIdAndPrincipalWithoutUsingFieldResults", + query = "select u.id as id, u.principal as principal from user_tbl u", resultSetMapping = "without_fields") + @NamedNativeQuery(name = "getIdWithoutUsingFieldResults", query = "select u.id as id from user_tbl u", + resultSetMapping = "without_fields") + + @SqlResultSetMapping(name = "id_and_principal_with_fields", + entities = @EntityResult(entityClass = User.class, + fields = {@FieldResult(name = "id", column = "id"), @FieldResult(name = "principal", + column = "principal")}) ) - @SqlResultSetMapping( name = "id_with_fields", - entities = @EntityResult( entityClass = User.class, fields = { @FieldResult(name = "id", column = "id") } ) + @SqlResultSetMapping(name = "id_with_fields", + entities = @EntityResult(entityClass = User.class, fields = {@FieldResult(name = "id", column = "id")}) ) - @SqlResultSetMapping( name = "without_fields", - entities = @EntityResult( entityClass = User.class ) + @SqlResultSetMapping(name = "without_fields", + entities = @EntityResult(entityClass = User.class) ) - @Entity( name = "User") + @Entity(name = "User") @Table(name = "user_tbl") - private static class User { + static class User { @Id private Long id; @Basic(fetch = FetchType.LAZY) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/fetch/FetchTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/fetch/FetchTest.java index 54129a115571..f8050849e0a9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/fetch/FetchTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/fetch/FetchTest.java @@ -12,122 +12,105 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; import org.hibernate.Hibernate; -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.SessionFactoryBuilder; import org.hibernate.collection.spi.PersistentSet; import org.hibernate.proxy.HibernateProxy; import org.hibernate.stat.Statistics; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import java.util.Set; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Gavin King */ -public class FetchTest extends BaseNonConfigCoreFunctionalTestCase { - - @Override - protected void configureSessionFactoryBuilder(SessionFactoryBuilder sfb) { - super.configureSessionFactoryBuilder( sfb ); - sfb.applyStatisticsSupport( true ); - sfb.applySecondLevelCacheSupport( false ); - sfb.applyQueryCacheSupport( false ); - } - - @Override - protected void applyMetadataSources(MetadataSources sources) { - super.applyMetadataSources( sources ); - sources.addAnnotatedClass( School.class ); - sources.addAnnotatedClass( Primary.class ); - sources.addAnnotatedClass( Secondary.class ); - sources.addAnnotatedClass( Student.class ); - } +@DomainModel( + annotatedClasses = { + FetchTest.School.class, + FetchTest.Primary.class, + FetchTest.Secondary.class, + FetchTest.Student.class + } +) +@SessionFactory(generateStatistics = true) +public class FetchTest { @Test - public void testFetch() { - inStatelessTransaction( - session -> { + public void testFetch(SessionFactoryScope scope) { + scope.inStatelessTransaction( session -> { Secondary secondary = new Secondary( "BHS" ); Student student = new Student( "gavin" ); student.school = secondary; - session.insert(secondary); - session.insert(student); + session.insert( secondary ); + session.insert( student ); } ); - inStatelessSession( - session -> { - final Statistics stats = sessionFactory().getStatistics(); + scope.inStatelessTransaction( session -> { + final Statistics stats = session.getFactory().getStatistics(); stats.clear(); final Student student = session.get( Student.class, "gavin" ); - assertFalse( Hibernate.isInitialized( student.school) ); - assertTrue( student.school instanceof HibernateProxy ); + assertFalse( Hibernate.isInitialized( student.school ) ); + assertInstanceOf( HibernateProxy.class, student.school ); long count = stats.getPrepareStatementCount(); - session.fetch( student.school); - assertTrue( Hibernate.isInitialized( student.school) ); + session.fetch( student.school ); + assertTrue( Hibernate.isInitialized( student.school ) ); assertEquals( "BHS", student.school.getName() ); - assertEquals( count+1, stats.getPrepareStatementCount() ); + assertEquals( count + 1, stats.getPrepareStatementCount() ); } ); - inStatelessSession( - session -> { - final Statistics stats = sessionFactory().getStatistics(); + scope.inStatelessTransaction( session -> { + final Statistics stats = session.getFactory().getStatistics(); stats.clear(); final School school = session.get( School.class, "BHS" ); - assertFalse( Hibernate.isInitialized( school.students) ); - assertTrue( school.students instanceof PersistentSet ); + assertFalse( Hibernate.isInitialized( school.students ) ); + assertInstanceOf( PersistentSet.class, school.students ); long count = stats.getPrepareStatementCount(); - session.fetch( school.students); - assertTrue( Hibernate.isInitialized( school.students) ); + session.fetch( school.students ); + assertTrue( Hibernate.isInitialized( school.students ) ); assertEquals( 1, school.students.size() ); - assertEquals( count+1, stats.getPrepareStatementCount() ); + assertEquals( count + 1, stats.getPrepareStatementCount() ); } ); } @Test - public void testFetchEmpty() { - inStatelessTransaction( - session -> { + public void testFetchEmpty(SessionFactoryScope scope) { + scope.inStatelessTransaction( session -> { Secondary secondary = new Secondary( "BHS" ); - session.insert(secondary); + session.insert( secondary ); } ); - inStatelessSession( - session -> { - final Statistics stats = sessionFactory().getStatistics(); + scope.inStatelessTransaction( session -> { + final Statistics stats = session.getFactory().getStatistics(); stats.clear(); final School school = session.get( School.class, "BHS" ); - assertFalse( Hibernate.isInitialized( school.students) ); - assertTrue( school.students instanceof PersistentSet ); + assertFalse( Hibernate.isInitialized( school.students ) ); + assertInstanceOf( PersistentSet.class, school.students ); long count = stats.getPrepareStatementCount(); - session.fetch( school.students); - assertTrue( Hibernate.isInitialized( school.students) ); + session.fetch( school.students ); + assertTrue( Hibernate.isInitialized( school.students ) ); assertTrue( school.students.isEmpty() ); - assertEquals( count+1, stats.getPrepareStatementCount() ); + assertEquals( count + 1, stats.getPrepareStatementCount() ); } ); } - @After - public void cleanUpTestData() { - inTransaction( - session -> { - session.createQuery( "delete from SchoolStudent" ).executeUpdate(); - session.createQuery( "delete from School" ).executeUpdate(); - } - ); + @AfterEach + public void cleanUpTestData(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Entity(name = "School") @@ -182,7 +165,8 @@ public Secondary(String name) { setName( name ); } - protected Secondary() {} + protected Secondary() { + } public String getSex() { return sex; @@ -202,7 +186,8 @@ public static class Student { @ManyToOne(fetch = FetchType.LAZY) private School school = null; - protected Student() {} + protected Student() { + } public Student(String id) { this.id = id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/NoProxyFactoryTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/NoProxyFactoryTests.java index 48abb33e925c..9d5cce33cbfa 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/NoProxyFactoryTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/NoProxyFactoryTests.java @@ -5,24 +5,24 @@ package org.hibernate.orm.test.bytecode.enhancement.lazy.proxy; import org.hibernate.Hibernate; -import org.hibernate.boot.MetadataSources; import org.hibernate.metamodel.spi.MappingMetamodelImplementor; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.proxy.HibernateProxy; -import org.hibernate.testing.bytecode.enhancement.BytecodeEnhancerRunner; import org.hibernate.testing.bytecode.enhancement.EnhancementOptions; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; +import org.hibernate.testing.bytecode.enhancement.extension.BytecodeEnhanced; import org.hibernate.testing.logger.LoggerInspectionRule; import org.hibernate.testing.logger.Triggerable; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.Rule; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.hibernate.internal.CoreMessageLogger.CORE_LOGGER; @@ -32,9 +32,15 @@ * * @author Steve Ebersole */ -@RunWith(BytecodeEnhancerRunner.class ) +@DomainModel( + annotatedClasses = { + NoProxyFactoryTests.SimpleEntity.class + } +) +@SessionFactory +@BytecodeEnhanced @EnhancementOptions(lazyLoading = true) -public class NoProxyFactoryTests extends BaseNonConfigCoreFunctionalTestCase { +public class NoProxyFactoryTests { @Rule public LoggerInspectionRule logInspection = new LoggerInspectionRule( CORE_LOGGER ); @@ -43,32 +49,26 @@ public class NoProxyFactoryTests extends BaseNonConfigCoreFunctionalTestCase { */ private final Triggerable triggerable = logInspection.watchForLogMessages( "HHH000305" ); - - @Override - protected void applyMetadataSources(MetadataSources sources) { - sources.addAnnotatedClasses( SimpleEntity.class ); - } - @Test - public void testNoInheritance() { + public void testNoInheritance(SessionFactoryScope scope) { assertThat( triggerable.wasTriggered() ) .describedAs( "Warning was logged" ) .isFalse(); - final MappingMetamodelImplementor mappingMetamodel = sessionFactory().getMappingMetamodel(); + final MappingMetamodelImplementor mappingMetamodel = scope.getSessionFactory().getMappingMetamodel(); final EntityPersister entityDescriptor = mappingMetamodel.findEntityDescriptor( SimpleEntity.class ); assertThat( entityDescriptor.getBytecodeEnhancementMetadata().isEnhancedForLazyLoading() ).isTrue(); assertThat( entityDescriptor.getRepresentationStrategy().getProxyFactory() ).isNull(); - inTransaction( (session) -> { + scope.inTransaction( session -> { final SimpleEntity reference = session.getReference( SimpleEntity.class, 1 ); assertThat( Hibernate.isInitialized( reference ) ).isFalse(); assertThat( reference ).isNotInstanceOf( HibernateProxy.class ); } ); } - @Entity(name="SimpleEntity") - @Table(name="SimpleEntity") + @Entity(name = "SimpleEntity") + @Table(name = "SimpleEntity") public static class SimpleEntity { @Id private Integer id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/ProxyDeletionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/ProxyDeletionTest.java index 9d78b0b0b720..f007bc882af3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/ProxyDeletionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/ProxyDeletionTest.java @@ -7,6 +7,7 @@ import java.sql.Blob; import java.util.HashSet; import java.util.Set; + import jakarta.persistence.Basic; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -21,26 +22,50 @@ import jakarta.persistence.Table; import org.hibernate.annotations.LazyGroup; -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.SessionFactoryBuilder; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.AvailableSettings; - -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author Steve Ebersole */ -public class ProxyDeletionTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + ProxyDeletionTest.AEntity.class, + ProxyDeletionTest.BEntity.class, + ProxyDeletionTest.CEntity.class, + ProxyDeletionTest.DEntity.class, + ProxyDeletionTest.EEntity.class, + ProxyDeletionTest.GEntity.class, + Activity.class, + Instruction.class, + WebApplication.class, + SpecializedKey.class, + MoreSpecializedKey.class, + RoleEntity.class, + AbstractKey.class, + GenericKey.class, + SpecializedEntity.class + } +) +@ServiceRegistry( + settings = { + @Setting(name = AvailableSettings.FORMAT_SQL, value = "false"), + } +) +@SessionFactory(generateStatistics = true) +public class ProxyDeletionTest { @Test - public void testGetAndDeleteEEntity() { - inTransaction( - session -> { + public void testGetAndDeleteEEntity(SessionFactoryScope scope) { + scope.inTransaction( session -> { EEntity entity = session.get( EEntity.class, 17L ); session.remove( entity ); session.remove( entity.getD() ); @@ -48,46 +73,9 @@ public void testGetAndDeleteEEntity() { ); } - @Override - protected void configureStandardServiceRegistryBuilder(StandardServiceRegistryBuilder ssrb) { - super.configureStandardServiceRegistryBuilder( ssrb ); - ssrb.applySetting( AvailableSettings.FORMAT_SQL, "false" ); - } - - @Override - protected void configureSessionFactoryBuilder(SessionFactoryBuilder sfb) { - super.configureSessionFactoryBuilder( sfb ); - sfb.applyStatisticsSupport( true ); - sfb.applySecondLevelCacheSupport( false ); - sfb.applyQueryCacheSupport( false ); - } - - @Override - protected void applyMetadataSources(MetadataSources sources) { - super.applyMetadataSources( sources ); - sources.addAnnotatedClass( AEntity.class ); - sources.addAnnotatedClass( BEntity.class ); - sources.addAnnotatedClass( CEntity.class ); - sources.addAnnotatedClass( DEntity.class ); - sources.addAnnotatedClass( EEntity.class ); - sources.addAnnotatedClass( GEntity.class ); - - sources.addAnnotatedClass( Activity.class ); - sources.addAnnotatedClass( Instruction.class ); - sources.addAnnotatedClass( WebApplication.class ); - - sources.addAnnotatedClass( SpecializedKey.class ); - sources.addAnnotatedClass( MoreSpecializedKey.class ); - sources.addAnnotatedClass( RoleEntity.class ); - sources.addAnnotatedClass( AbstractKey.class ); - sources.addAnnotatedClass( GenericKey.class ); - sources.addAnnotatedClass( SpecializedEntity.class ); - } - - @Before - public void prepareTestData() { - inTransaction( - session -> { + @BeforeEach + public void prepareTestData(SessionFactoryScope scope) { + scope.inTransaction( session -> { DEntity d = new DEntity(); d.setD( "bla" ); d.setOid( 1 ); @@ -171,7 +159,7 @@ public void prepareTestData() { roleEntity.setOid( 1L ); SpecializedKey specializedKey = new SpecializedKey(); - specializedKey.setOid(1L); + specializedKey.setOid( 1L ); MoreSpecializedKey moreSpecializedKey = new MoreSpecializedKey(); moreSpecializedKey.setOid( 3L ); @@ -179,7 +167,7 @@ public void prepareTestData() { SpecializedEntity specializedEntity = new SpecializedEntity(); specializedEntity.setId( 2L ); specializedKey.addSpecializedEntity( specializedEntity ); - specializedEntity.setSpecializedKey( specializedKey); + specializedEntity.setSpecializedKey( specializedKey ); specializedKey.addRole( roleEntity ); roleEntity.setKey( specializedKey ); @@ -193,29 +181,9 @@ public void prepareTestData() { ); } - @After - public void cleanUpTestData() { - inTransaction( - session -> { - session.createQuery( "delete from E" ).executeUpdate(); - session.createQuery( "delete from D" ).executeUpdate(); - session.createQuery( "delete from C" ).executeUpdate(); - session.createQuery( "delete from B" ).executeUpdate(); - session.createQuery( "delete from A" ).executeUpdate(); - session.createQuery( "delete from G" ).executeUpdate(); - - session.createQuery( "delete from Activity" ).executeUpdate(); - session.createQuery( "delete from Instruction" ).executeUpdate(); - session.createQuery( "delete from WebApplication" ).executeUpdate(); - - session.createQuery( "delete from SpecializedEntity" ).executeUpdate(); - session.createQuery( "delete from RoleEntity" ).executeUpdate(); - session.createQuery( "delete from MoreSpecializedKey" ).executeUpdate(); - session.createQuery( "delete from SpecializedKey" ).executeUpdate(); - session.createQuery( "delete from GenericKey" ).executeUpdate(); - session.createQuery( "delete from AbstractKey" ).executeUpdate(); - } - ); + @AfterEach + public void cleanUpTestData(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @MappedSuperclass diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/merge/MergeEnhancedEntityDynamicUpdateTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/merge/MergeEnhancedEntityDynamicUpdateTest.java index 85c3308530a4..ea1924d020a0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/merge/MergeEnhancedEntityDynamicUpdateTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/merge/MergeEnhancedEntityDynamicUpdateTest.java @@ -10,13 +10,9 @@ import org.hibernate.annotations.DynamicInsert; import org.hibernate.annotations.DynamicUpdate; +import org.hibernate.testing.bytecode.enhancement.extension.BytecodeEnhanced; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.bytecode.enhancement.BytecodeEnhancerRunner; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; @@ -26,47 +22,56 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Luis Barreiro */ -@JiraKey( value = "HHH-11459" ) -@RunWith( BytecodeEnhancerRunner.class ) -public class MergeEnhancedEntityDynamicUpdateTest extends BaseCoreFunctionalTestCase { +@JiraKey(value = "HHH-11459") +@DomainModel( + annotatedClasses = { + MergeEnhancedEntityDynamicUpdateTest.Person.class, + MergeEnhancedEntityDynamicUpdateTest.PersonAddress.class, + MergeEnhancedEntityDynamicUpdateTest.NullablePerson.class + } +) +@SessionFactory +@BytecodeEnhanced +public class MergeEnhancedEntityDynamicUpdateTest { private Person person; - @Override - public Class[] getAnnotatedClasses() { - return new Class[]{Person.class, PersonAddress.class, NullablePerson.class}; - } - @Before - public void prepare() { + @BeforeEach + public void prepare(SessionFactoryScope scope) { person = new Person( 1L, "Sam" ); - doInHibernate( this::sessionFactory, s -> { + scope.inTransaction( s -> { s.persist( person ); } ); } @Test - public void testMerge() { - doInHibernate( this::sessionFactory, s -> { + public void testMerge(SessionFactoryScope scope) { + scope.inTransaction( s -> { Person entity = s.find( Person.class, 1L ); entity.name = "John"; try { s.merge( entity ); - } catch ( RuntimeException e ) { + } + catch (RuntimeException e) { fail( "Enhanced entity can't be merged: " + e.getMessage() ); } } ); } @Test - public void testRefresh() { - doInHibernate( this::sessionFactory, s -> { + public void testRefresh(SessionFactoryScope scope) { + scope.inTransaction( s -> { Person entity = s.find( Person.class, 1L ); entity.name = "John"; @@ -81,65 +86,60 @@ public void testRefresh() { } @Test - public void testMergeWithNullValues() { - doInHibernate( this::sessionFactory, em -> { + public void testMergeWithNullValues(SessionFactoryScope scope) { + scope.inTransaction( s -> { NullablePerson nullablePerson = new NullablePerson( 1L, "Sam", 100 ); - em.persist( nullablePerson ); + s.persist( nullablePerson ); } ); - doInHibernate( this::sessionFactory, em -> { + scope.inTransaction( em -> { NullablePerson updated = em.find( NullablePerson.class, 1L ); assertThat( updated.name ).isEqualTo( "Sam" ); assertThat( updated.number ).isEqualTo( 100 ); } ); // only some properties are null - doInHibernate( this::sessionFactory, em -> { + scope.inTransaction( em -> { NullablePerson nullablePerson = new NullablePerson( 1L, "Joe", null ); em.merge( nullablePerson ); } ); - doInHibernate( this::sessionFactory, em -> { + scope.inTransaction( em -> { NullablePerson updated = em.find( NullablePerson.class, 1L ); assertThat( updated.name ).isEqualTo( "Joe" ); assertThat( updated.number ).isNull(); } ); // all properties are null: - doInHibernate( this::sessionFactory, em -> { + scope.inTransaction( em -> { NullablePerson nullablePerson = new NullablePerson( 1L, null, null ); em.merge( nullablePerson ); } ); - doInHibernate( this::sessionFactory, em -> { + scope.inTransaction( em -> { NullablePerson updated = em.find( NullablePerson.class, 1L ); assertThat( updated.name ).isNull(); assertThat( updated.number ).isNull(); } ); } - @After - public void cleanup() { - doInHibernate( this::sessionFactory, s -> { - s.remove( person ); - } ); - doInHibernate( this::sessionFactory, s -> { - s.createQuery( "delete from NullablePerson" ); - } ); + @AfterEach + public void cleanup(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } // --- // @Entity - @Table( name = "PERSON" ) + @Table(name = "PERSON") @DynamicUpdate @DynamicInsert - private static class Person { + static class Person { @Id Long id; - @Column( name = "name", length = 10, nullable = false ) + @Column(name = "name", length = 10, nullable = false) String name; - @OneToMany( fetch = FetchType.LAZY, mappedBy = "parent", orphanRemoval = true, cascade = CascadeType.ALL ) + @OneToMany(fetch = FetchType.LAZY, mappedBy = "parent", orphanRemoval = true, cascade = CascadeType.ALL) List details = new ArrayList<>(); Person() { @@ -152,15 +152,15 @@ private static class Person { } @Entity - @Table( name = "PERSON_ADDRESS" ) + @Table(name = "PERSON_ADDRESS") @DynamicUpdate @DynamicInsert - private static class PersonAddress { + static class PersonAddress { @Id Long id; - @ManyToOne( optional = false, fetch = FetchType.LAZY ) + @ManyToOne(optional = false, fetch = FetchType.LAZY) Person parent; } @@ -168,7 +168,7 @@ private static class PersonAddress { @Table(name = "NULLABLE_PERSON") @DynamicUpdate @DynamicInsert - private static class NullablePerson { + static class NullablePerson { @Id Long id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/tracker/CompositeOwnerTrackerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/tracker/CompositeOwnerTrackerTest.java index b78df887e754..3fa27fb49f05 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/tracker/CompositeOwnerTrackerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/tracker/CompositeOwnerTrackerTest.java @@ -6,9 +6,9 @@ import org.hibernate.bytecode.enhance.internal.tracker.CompositeOwnerTracker; import org.hibernate.engine.spi.CompositeOwner; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Ståle W. Pedersen diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/tracker/DirtyTrackerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/tracker/DirtyTrackerTest.java index f41a72831104..e11347c6b530 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/tracker/DirtyTrackerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/tracker/DirtyTrackerTest.java @@ -7,12 +7,12 @@ import org.hibernate.bytecode.enhance.internal.tracker.DirtyTracker; import org.hibernate.bytecode.enhance.internal.tracker.SimpleFieldTracker; import org.hibernate.bytecode.enhance.internal.tracker.SortedFieldTracker; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Ståle W. Pedersen @@ -27,7 +27,7 @@ public void testSimpleTracker() { tracker.add( "foo" ); assertFalse( tracker.isEmpty() ); - assertArrayEquals( tracker.get(), new String[]{"foo"} ); + assertArrayEquals( new String[]{"foo"}, tracker.get() ); tracker.clear(); assertTrue( tracker.isEmpty() ); @@ -54,7 +54,7 @@ public void testSortedTracker() { tracker.add( "foo" ); assertFalse( tracker.isEmpty() ); - assertArrayEquals( tracker.get(), new String[]{"foo"} ); + assertArrayEquals( new String[]{"foo"}, tracker.get() ); tracker.clear(); assertTrue( tracker.isEmpty() ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/ByteCodeEnhancedImmutableReferenceCacheTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/ByteCodeEnhancedImmutableReferenceCacheTest.java index 1fd234e1c485..c57b089b9715 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/ByteCodeEnhancedImmutableReferenceCacheTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/ByteCodeEnhancedImmutableReferenceCacheTest.java @@ -4,53 +4,56 @@ */ package org.hibernate.orm.test.cache; +import jakarta.persistence.Cacheable; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Transient; import org.hibernate.Session; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.Immutable; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; +import org.hibernate.cfg.Environment; import org.hibernate.engine.spi.EntityEntry; import org.hibernate.engine.spi.ManagedEntity; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.Status; import org.hibernate.persister.entity.EntityPersister; - +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; - -import jakarta.persistence.Cacheable; -import jakarta.persistence.Entity; -import jakarta.persistence.Id; -import jakarta.persistence.Transient; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author John O'Hara */ -public class ByteCodeEnhancedImmutableReferenceCacheTest extends BaseCoreFunctionalTestCase { - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - configuration.setProperty( AvailableSettings.USE_DIRECT_REFERENCE_CACHE_ENTRIES, true ); - configuration.setProperty( AvailableSettings.USE_QUERY_CACHE, true ); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{MyEnhancedReferenceData.class}; - } +@DomainModel( + annotatedClasses = { + ByteCodeEnhancedImmutableReferenceCacheTest.MyEnhancedReferenceData.class + } +) +@ServiceRegistry( + settings = { + @Setting(name = Environment.USE_DIRECT_REFERENCE_CACHE_ENTRIES, value = "true"), + @Setting(name = Environment.USE_QUERY_CACHE, value = "true"), + } +) +@SessionFactory +public class ByteCodeEnhancedImmutableReferenceCacheTest { @Test - public void testUseOfDirectReferencesInCache() { - EntityPersister persister = sessionFactory().getMappingMetamodel().getEntityDescriptor( MyEnhancedReferenceData.class ); + public void testUseOfDirectReferencesInCache(SessionFactoryScope scope) { + EntityPersister persister = scope.getSessionFactory().getMappingMetamodel() + .getEntityDescriptor( MyEnhancedReferenceData.class ); assertFalse( persister.isMutable() ); assertTrue( persister.buildCacheEntry( null, null, null, null ).isReferenceEntry() ); assertFalse( persister.hasProxy() ); @@ -58,7 +61,7 @@ public void testUseOfDirectReferencesInCache() { final MyEnhancedReferenceData myReferenceData = new MyEnhancedReferenceData( 1, "first item", "abc" ); // save a reference in one session - Session s = openSession(); + Session s = scope.getSessionFactory().openSession(); s.beginTransaction(); s.persist( myReferenceData ); s.getTransaction().commit(); @@ -67,7 +70,7 @@ public void testUseOfDirectReferencesInCache() { assertNotNull( myReferenceData.$$_hibernate_getEntityEntry() ); // now load it in another - s = openSession(); + s = scope.getSessionFactory().openSession(); s.beginTransaction(); // MyEnhancedReferenceData loaded = (MyEnhancedReferenceData) s.get( MyEnhancedReferenceData.class, 1 ); MyEnhancedReferenceData loaded = s.getReference( MyEnhancedReferenceData.class, 1 ); @@ -75,10 +78,10 @@ public void testUseOfDirectReferencesInCache() { s.close(); // the 2 instances should be the same (==) - assertSame( "The two instances were different references", myReferenceData, loaded ); + assertSame( myReferenceData, loaded, "The two instances were different references" ); // now try query caching - s = openSession(); + s = scope.getSessionFactory().openSession(); s.beginTransaction(); MyEnhancedReferenceData queried = (MyEnhancedReferenceData) s.createQuery( "from MyEnhancedReferenceData" ) @@ -88,10 +91,10 @@ public void testUseOfDirectReferencesInCache() { s.close(); // the 2 instances should be the same (==) - assertSame( "The two instances were different references", myReferenceData, queried ); + assertSame( myReferenceData, queried, "The two instances were different references" ); // cleanup - s = openSession(); + s = scope.getSessionFactory().openSession(); s.beginTransaction(); s.remove( myReferenceData ); s.getTransaction().commit(); @@ -99,13 +102,13 @@ public void testUseOfDirectReferencesInCache() { } @Test - @JiraKey( value = "HHH-10795") - public void testAssociatedWithMultiplePersistenceContexts() { + @JiraKey(value = "HHH-10795") + public void testAssociatedWithMultiplePersistenceContexts(SessionFactoryScope scope) { MyEnhancedReferenceData myReferenceData = new MyEnhancedReferenceData( 1, "first item", "abc" ); MyEnhancedReferenceData myOtherReferenceData = new MyEnhancedReferenceData( 2, "second item", "def" ); // save a reference in one session - Session s1 = openSession(); + Session s1 = scope.getSessionFactory().openSession(); s1.beginTransaction(); s1.persist( myReferenceData ); s1.persist( myOtherReferenceData ); @@ -116,7 +119,7 @@ public void testAssociatedWithMultiplePersistenceContexts() { assertNotNull( myOtherReferenceData.$$_hibernate_getEntityEntry() ); // now associate myReferenceData with 2 sessions - s1 = openSession(); + s1 = scope.getSessionFactory().openSession(); s1.beginTransaction(); myReferenceData = s1.get( MyEnhancedReferenceData.class, myReferenceData.getId() ); myOtherReferenceData = s1.get( MyEnhancedReferenceData.class, myOtherReferenceData.getId() ); @@ -130,22 +133,22 @@ public void testAssociatedWithMultiplePersistenceContexts() { assertSame( myReferenceData.$$_hibernate_getEntityEntry(), - ( (SharedSessionContractImplementor) s1 ).getPersistenceContext().getEntry( myReferenceData ) + ((SharedSessionContractImplementor) s1).getPersistenceContext().getEntry( myReferenceData ) ); assertSame( myOtherReferenceData.$$_hibernate_getEntityEntry(), - ( (SharedSessionContractImplementor) s1 ).getPersistenceContext().getEntry( myOtherReferenceData ) + ((SharedSessionContractImplementor) s1).getPersistenceContext().getEntry( myOtherReferenceData ) ); - Session s2 = openSession(); + Session s2 = scope.getSessionFactory().openSession(); s2.beginTransaction(); // s2 should contains no entities assertFalse( s2.contains( myReferenceData ) ); assertFalse( s2.contains( myOtherReferenceData ) ); - assertNull( ( (SharedSessionContractImplementor) s2 ).getPersistenceContext().getEntry( myReferenceData ) ); - assertNull( ( (SharedSessionContractImplementor) s2 ).getPersistenceContext().getEntry( myOtherReferenceData ) ); + assertNull( ((SharedSessionContractImplementor) s2).getPersistenceContext().getEntry( myReferenceData ) ); + assertNull( ((SharedSessionContractImplementor) s2).getPersistenceContext().getEntry( myOtherReferenceData ) ); // evict should do nothing, since p is not associated with s2 s2.evict( myReferenceData ); @@ -186,12 +189,12 @@ public void testAssociatedWithMultiplePersistenceContexts() { assertNotNull( myOtherReferenceData.$$_hibernate_getEntityEntry() ); // load them into 2 sessions - s1 = openSession(); + s1 = scope.getSessionFactory().openSession(); s1.getTransaction().begin(); assertSame( myReferenceData, s1.get( MyEnhancedReferenceData.class, myReferenceData.getId() ) ); assertSame( myOtherReferenceData, s1.get( MyEnhancedReferenceData.class, myOtherReferenceData.getId() ) ); - s2 = openSession(); + s2 = scope.getSessionFactory().openSession(); s2.getTransaction().begin(); assertSame( myReferenceData, s2.get( MyEnhancedReferenceData.class, myReferenceData.getId() ) ); assertSame( myOtherReferenceData, s2.get( MyEnhancedReferenceData.class, myOtherReferenceData.getId() ) ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/CacheAnnotationTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/CacheAnnotationTests.java index ffd36c8b602d..7c8bae7b90d4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/CacheAnnotationTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/CacheAnnotationTests.java @@ -7,41 +7,42 @@ import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; - import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; -import org.junit.Test; - +import org.hibernate.cfg.Environment; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Chris Cranford */ -public class CacheAnnotationTests extends BaseCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + CacheAnnotationTests.NoCacheConcurrencyStrategyEntity.class + } +) +@SessionFactory +@ServiceRegistry( + settings = { + @Setting(name = Environment.USE_SECOND_LEVEL_CACHE, value = "true"), + } +) +public class CacheAnnotationTests { private Integer entityId; - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - configuration.setProperty( AvailableSettings.USE_SECOND_LEVEL_CACHE, true ); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { NoCacheConcurrencyStrategyEntity.class }; - } @Test @JiraKey(value = "HHH-12587") - public void testCacheWriteConcurrencyStrategyNone() { - doInHibernate( this::sessionFactory, session -> { + public void testCacheWriteConcurrencyStrategyNone(SessionFactoryScope scope) { + scope.inTransaction( session -> { NoCacheConcurrencyStrategyEntity entity = new NoCacheConcurrencyStrategyEntity(); session.persist( entity ); session.flush(); @@ -51,8 +52,8 @@ public void testCacheWriteConcurrencyStrategyNone() { @Test @JiraKey(value = "HHH-12868") - public void testCacheReadConcurrencyStrategyNone() { - doInHibernate( this::sessionFactory, session -> { + public void testCacheReadConcurrencyStrategyNone(SessionFactoryScope scope) { + scope.inTransaction( session -> { NoCacheConcurrencyStrategyEntity entity = new NoCacheConcurrencyStrategyEntity(); entity.setName( "name" ); session.persist( entity ); @@ -63,8 +64,9 @@ public void testCacheReadConcurrencyStrategyNone() { session.clear(); } ); - doInHibernate( this::sessionFactory, session -> { - NoCacheConcurrencyStrategyEntity entity = session.getReference( NoCacheConcurrencyStrategyEntity.class, this.entityId ); + scope.inTransaction( session -> { + NoCacheConcurrencyStrategyEntity entity = session.getReference( NoCacheConcurrencyStrategyEntity.class, + this.entityId ); assertEquals( "name", entity.getName() ); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/CacheRegionStatisticsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/CacheRegionStatisticsTest.java index 523df93f7031..1408d16c50bb 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/CacheRegionStatisticsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/CacheRegionStatisticsTest.java @@ -7,40 +7,56 @@ import java.util.HashSet; import java.util.List; import java.util.Set; + import jakarta.persistence.ElementCollection; import jakarta.persistence.Entity; import jakarta.persistence.Id; -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.AvailableSettings; import org.hibernate.stat.CacheRegionStatistics; import org.hibernate.stat.Statistics; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.cache.CachingRegionFactory; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; import static org.junit.Assert.assertEquals; /** * @author Christian Beikov */ -public class CacheRegionStatisticsTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + CacheRegionStatisticsTest.Dog.class + } +) +@SessionFactory(generateStatistics = true) +@ServiceRegistry( + settings = { + @Setting(name = AvailableSettings.FORMAT_SQL, value = "false"), + @Setting(name = AvailableSettings.AUTO_EVICT_COLLECTION_CACHE, value = "true"), + @Setting(name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "true"), + @Setting(name = AvailableSettings.USE_QUERY_CACHE, value = "true"), + @Setting(name = AvailableSettings.CACHE_REGION_FACTORY, + value = "org.hibernate.testing.cache.CachingRegionFactory"), + } +) +public class CacheRegionStatisticsTest { @Test - @JiraKey( value = "HHH-15105") - public void testAccessDefaultQueryRegionStatistics() { - final Statistics statistics = sessionFactory().getStatistics(); + @JiraKey(value = "HHH-15105") + public void testAccessDefaultQueryRegionStatistics(SessionFactoryScope scope) { + final Statistics statistics = scope.getSessionFactory().getStatistics(); final CacheRegionStatistics queryRegionStatistics = statistics.getQueryRegionStatistics( "default-query-results-region" ); - doInHibernate( - this::sessionFactory, session -> { + scope.inTransaction( session -> { List resultList = session.createQuery( "from Dog", Dog.class ) .setCacheable( true ) .getResultList(); @@ -50,25 +66,9 @@ public void testAccessDefaultQueryRegionStatistics() { ); } - @Override - protected void configureStandardServiceRegistryBuilder(StandardServiceRegistryBuilder ssrb) { - super.configureStandardServiceRegistryBuilder( ssrb ); - ssrb.applySetting( AvailableSettings.USE_SECOND_LEVEL_CACHE, true ); - ssrb.applySetting( AvailableSettings.USE_QUERY_CACHE, true ); - ssrb.applySetting( AvailableSettings.CACHE_REGION_FACTORY, new CachingRegionFactory() ); - ssrb.applySetting( AvailableSettings.GENERATE_STATISTICS, "true" ); - } - - @Override - protected void applyMetadataSources(MetadataSources metadataSources) { - super.applyMetadataSources( metadataSources ); - metadataSources.addAnnotatedClass( Dog.class ); - } - - @Before - public void setupData() { - doInHibernate( - this::sessionFactory, session -> { + @BeforeEach + public void setupData(SessionFactoryScope scope) { + scope.inTransaction( session -> { Dog yogi = new Dog( "Yogi" ); yogi.nickNames.add( "The Yog" ); yogi.nickNames.add( "Little Boy" ); @@ -82,16 +82,9 @@ public void setupData() { ); } - @After - public void cleanupData() { - doInHibernate( - this::sessionFactory, session -> { - List dogs = session.createQuery( "from Dog", Dog.class ).getResultList(); - for ( Dog dog : dogs ) { - session.remove( dog ); - } - } - ); + @AfterEach + public void cleanupData(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Entity(name = "Dog") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/CollectionCacheEvictionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/CollectionCacheEvictionTest.java index e01f4242ea6b..357817d6dee8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/CollectionCacheEvictionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/CollectionCacheEvictionTest.java @@ -5,333 +5,287 @@ package org.hibernate.orm.test.cache; import org.hibernate.ObjectNotFoundException; -import org.hibernate.Session; import org.hibernate.cache.internal.CollectionCacheInvalidator; import org.hibernate.cache.spi.access.CollectionDataAccess; -import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; -import org.hibernate.engine.spi.SessionImplementor; -import org.hibernate.metamodel.CollectionClassification; import org.hibernate.persister.collection.CollectionPersister; - +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.hibernate.cfg.AvailableSettings.DEFAULT_LIST_SEMANTICS; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Andreas Berger */ @JiraKey(value = "HHH-4910") -public class CollectionCacheEvictionTest extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { User.class, Company.class }; - } +@DomainModel( + annotatedClasses = { + User.class, Company.class + } +) +@ServiceRegistry( + settings = { + @Setting(name = Environment.AUTO_EVICT_COLLECTION_CACHE, value = "true"), + @Setting(name = Environment.USE_SECOND_LEVEL_CACHE, value = "true"), + @Setting(name = Environment.USE_QUERY_CACHE, value = "true"), + @Setting(name = Environment.DEFAULT_LIST_SEMANTICS, value = "bag"), // CollectionClassification.BAG + } +) +@SessionFactory(generateStatistics = true) +public class CollectionCacheEvictionTest { - @Before + @BeforeEach public void before() { CollectionCacheInvalidator.PROPAGATE_EXCEPTION = true; } - @After + @AfterEach public void after() { CollectionCacheInvalidator.PROPAGATE_EXCEPTION = false; } - @Override - protected void configure(Configuration cfg) { - super.configure( cfg ); - cfg.setProperty( Environment.AUTO_EVICT_COLLECTION_CACHE, true ); - cfg.setProperty( Environment.USE_SECOND_LEVEL_CACHE, true ); - cfg.setProperty( Environment.USE_QUERY_CACHE, true ); - cfg.setProperty( DEFAULT_LIST_SEMANTICS, CollectionClassification.BAG ); - } - - @Override - protected void prepareTest() throws Exception { - Session s = openSession(); - s.beginTransaction(); + @BeforeEach + void prepareTest(SessionFactoryScope scope) throws Exception { + scope.inTransaction( s -> { - Company company1 = new Company( 1 ); - s.persist( company1 ); + Company company1 = new Company( 1 ); + s.persist( company1 ); - User user = new User( 1, company1 ); - s.persist( user ); + User user = new User( 1, company1 ); + s.persist( user ); - Company company2 = new Company( 2 ); - s.persist( company2 ); + Company company2 = new Company( 2 ); + s.persist( company2 ); - s.getTransaction().commit(); - s.close(); + } ); } - @Override - protected void cleanupTest() throws Exception { - Session s = openSession(); - s.beginTransaction(); - - s.createQuery( "delete from org.hibernate.orm.test.cache.User" ).executeUpdate(); - s.createQuery( "delete from org.hibernate.orm.test.cache.Company" ).executeUpdate(); - - s.getTransaction().commit(); - s.close(); + @AfterEach + protected void cleanupTest(SessionFactoryScope scope) throws Exception { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); + scope.getSessionFactory().getCache().evictAll(); } @Test - public void testCachedValueAfterEviction() { - CollectionPersister persister = sessionFactory().getRuntimeMetamodels() + public void testCachedValueAfterEviction(SessionFactoryScope scope) { + CollectionPersister persister = scope.getSessionFactory().getRuntimeMetamodels() .getMappingMetamodel() - .getCollectionDescriptor(Company.class.getName() + ".users"); - - Session session = openSession(); - SessionImplementor sessionImplementor = (SessionImplementor) session; - - CollectionDataAccess cache = persister.getCacheAccessStrategy(); - Object key = cache.generateCacheKey( 1, persister, sessionFactory(), session.getTenantIdentifier() ); - Object cachedValue = cache.get( sessionImplementor, key ); - assertNull( cachedValue ); - - Company company = session.get( Company.class, 1 ); - //should add in cache - assertEquals( 1, company.getUsers().size() ); - session.close(); - - session = openSession(); - sessionImplementor = (SessionImplementor) session; - key = cache.generateCacheKey( 1, persister, sessionFactory(), session.getTenantIdentifier() ); - cachedValue = cache.get( sessionImplementor, key ); - assertNotNull( "Collection wasn't cached", cachedValue ); - session.close(); + .getCollectionDescriptor( Company.class.getName() + ".users" ); + + scope.inSession( session -> { + CollectionDataAccess cache = persister.getCacheAccessStrategy(); + Object key = cache.generateCacheKey( 1, persister, session.getFactory(), session.getTenantIdentifier() ); + Object cachedValue = cache.get( session, key ); + assertNull( cachedValue ); + + Company company = session.get( Company.class, 1 ); + //should add in cache + assertEquals( 1, company.getUsers().size() ); + } ); + + scope.inSession( session -> { + CollectionDataAccess cache = persister.getCacheAccessStrategy(); + Object key = cache.generateCacheKey( 1, persister, session.getFactory(), session.getTenantIdentifier() ); + Object cachedValue = cache.get( session, key ); + assertNotNull( cachedValue, "Collection wasn't cached" ); + } ); } @Test - public void testCollectionCacheEvictionInsert() { - Session s = openSession(); - s.beginTransaction(); - - Company company = (Company) s.get( Company.class, 1 ); - // init cache of collection - assertEquals( 1, company.getUsers().size() ); - - User user = new User( 2, company ); - s.persist( user ); + public void testCollectionCacheEvictionInsert(SessionFactoryScope scope) { + scope.inTransaction( s -> { + Company company = (Company) s.get( Company.class, 1 ); + // init cache of collection + assertEquals( 1, company.getUsers().size() ); - s.getTransaction().commit(); - s.close(); + User user = new User( 2, company ); + s.persist( user ); - s = openSession(); - s.beginTransaction(); + } ); - company = (Company) s.get( Company.class, 1 ); - // fails if cache is not evicted - assertEquals( 2, company.getUsers().size() ); + scope.inTransaction( s -> { + Company company = (Company) s.get( Company.class, 1 ); + // fails if cache is not evicted + assertEquals( 2, company.getUsers().size() ); - s.close(); + } ); } @Test - public void testCollectionCacheEvictionInsertWithEntityOutOfContext() { - Session s = openSession(); - Company company = s.get( Company.class, 1 ); - assertEquals( 1, company.getUsers().size() ); - s.close(); - - s = openSession(); - s.beginTransaction(); - - User user = new User( 2, company ); - s.persist( user ); - - s.getTransaction().commit(); - s.close(); - - s = openSession(); - - company = s.get( Company.class, 1 ); - assertEquals( 2, company.getUsers().size() ); - s.close(); + public void testCollectionCacheEvictionInsertWithEntityOutOfContext(SessionFactoryScope scope) { + Company company = scope.fromSession( s -> { + Company c = s.get( Company.class, 1 ); + assertEquals( 1, c.getUsers().size() ); + return c; + } ); + + scope.inTransaction( s -> { + User user = new User( 2, company ); + s.persist( user ); + } ); + + scope.inSession( s -> { + Company c = s.get( Company.class, 1 ); + assertEquals( 2, c.getUsers().size() ); + } ); } @Test - public void testCollectionCacheEvictionRemove() { - Session s = openSession(); - s.beginTransaction(); - - Company company = (Company) s.get( Company.class, 1 ); - // init cache of collection - assertEquals( 1, company.getUsers().size() ); - - s.remove( company.getUsers().get( 0 ) ); - - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - - company = (Company) s.get( Company.class, 1 ); - // fails if cache is not evicted - try { - assertEquals( 0, company.getUsers().size() ); - } - catch ( ObjectNotFoundException e ) { - fail( "Cached element not found" ); - } - s.close(); + public void testCollectionCacheEvictionRemove(SessionFactoryScope scope) { + scope.inTransaction( s -> { + Company company = (Company) s.get( Company.class, 1 ); + // init cache of collection + assertEquals( 1, company.getUsers().size() ); + + s.remove( company.getUsers().get( 0 ) ); + + } ); + + scope.inTransaction( s -> { + Company company = (Company) s.get( Company.class, 1 ); + // fails if cache is not evicted + try { + assertEquals( 0, company.getUsers().size() ); + } + catch (ObjectNotFoundException e) { + fail( "Cached element not found" ); + } + } ); } @Test - public void testCollectionCacheEvictionRemoveWithEntityOutOfContext() { - Session s = openSession(); - Company company = s.get( Company.class, 1 ); - assertEquals( 1, company.getUsers().size() ); - s.close(); - - s = openSession(); - s.beginTransaction(); - s.remove( company.getUsers().get( 0 ) ); - - s.getTransaction().commit(); - s.close(); - - s = openSession(); - - company = s.get( Company.class, 1 ); - try { - assertEquals( 0, company.getUsers().size() ); - } - catch ( ObjectNotFoundException e ) { - fail( "Cached element not found" ); - } - s.close(); + public void testCollectionCacheEvictionRemoveWithEntityOutOfContext(SessionFactoryScope scope) { + Company company = scope.fromSession( s -> { + Company c = s.get( Company.class, 1 ); + assertEquals( 1, c.getUsers().size() ); + return c; + } ); + + scope.inTransaction( s -> { + s.remove( company.getUsers().get( 0 ) ); + } ); + + scope.inSession( s -> { + + var c = s.get( Company.class, 1 ); + try { + assertEquals( 0, c.getUsers().size() ); + } + catch (ObjectNotFoundException e) { + fail( "Cached element not found" ); + } + } ); } @Test - public void testCollectionCacheEvictionUpdate() { - Session s = openSession(); - s.beginTransaction(); - - Company company1 = (Company) s.get( Company.class, 1 ); - Company company2 = (Company) s.get( Company.class, 2 ); - - // init cache of collection - assertEquals( 1, company1.getUsers().size() ); - assertEquals( 0, company2.getUsers().size() ); - - User user = (User) s.get( User.class, 1 ); - user.setCompany( company2 ); - - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - - company1 = (Company) s.get( Company.class, 1 ); - company2 = (Company) s.get( Company.class, 2 ); - - assertEquals( 1, company2.getUsers().size() ); - - // fails if cache is not evicted - try { - assertEquals( 0, company1.getUsers().size() ); - } - catch ( ObjectNotFoundException e ) { - fail( "Cached element not found" ); - } - - s.close(); + public void testCollectionCacheEvictionUpdate(SessionFactoryScope scope) { + scope.inTransaction( s -> { + Company company1 = (Company) s.get( Company.class, 1 ); + Company company2 = (Company) s.get( Company.class, 2 ); + + // init cache of collection + assertEquals( 1, company1.getUsers().size() ); + assertEquals( 0, company2.getUsers().size() ); + + User user = (User) s.get( User.class, 1 ); + user.setCompany( company2 ); + } ); + + scope.inSession( s -> { + var company1 = (Company) s.get( Company.class, 1 ); + var company2 = (Company) s.get( Company.class, 2 ); + + assertEquals( 1, company2.getUsers().size() ); + + // fails if cache is not evicted + try { + assertEquals( 0, company1.getUsers().size() ); + } + catch (ObjectNotFoundException e) { + fail( "Cached element not found" ); + } + + } ); } @Test @JiraKey(value = "HHH-10631") - public void testCollectionCacheEvictionUpdateWhenChildIsSetToNull() { - Session s = openSession(); - s.beginTransaction(); - - Company company1 = (Company) s.get( Company.class, 1 ); - Company company2 = (Company) s.get( Company.class, 2 ); + public void testCollectionCacheEvictionUpdateWhenChildIsSetToNull(SessionFactoryScope scope) { + scope.inTransaction( s -> { - // init cache of collection - assertEquals( 1, company1.getUsers().size() ); - assertEquals( 0, company2.getUsers().size() ); + Company company1 = (Company) s.get( Company.class, 1 ); + Company company2 = (Company) s.get( Company.class, 2 ); - User user = (User) s.get( User.class, 1 ); - user.setCompany( null ); + // init cache of collection + assertEquals( 1, company1.getUsers().size() ); + assertEquals( 0, company2.getUsers().size() ); - s.getTransaction().commit(); - s.close(); + User user = (User) s.get( User.class, 1 ); + user.setCompany( null ); + } ); - s = openSession(); + scope.inSession( s -> { + var company1 = (Company) s.get( Company.class, 1 ); + var company2 = (Company) s.get( Company.class, 2 ); - company1 = (Company) s.get( Company.class, 1 ); - company2 = (Company) s.get( Company.class, 2 ); - - assertEquals( 0, company1.getUsers().size() ); - assertEquals( 0, company2.getUsers().size() ); - s.close(); + assertEquals( 0, company1.getUsers().size() ); + assertEquals( 0, company2.getUsers().size() ); + } ); } @Test - public void testCollectionCacheEvictionUpdateWithEntityOutOfContext() { - Session s = openSession(); - Company company1 = s.get( Company.class, 1 ); - Company company2 = s.get( Company.class, 2 ); - - assertEquals( 1, company1.getUsers().size() ); - assertEquals( 0, company2.getUsers().size() ); - - s.close(); - s = openSession(); - s.beginTransaction(); - - User user = s.get( User.class, 1 ); - user.setCompany( company2 ); - - s.getTransaction().commit(); - s.close(); - - s = openSession(); - - company1 = s.get( Company.class, 1 ); - company2 = s.get( Company.class, 2 ); - - assertEquals( 1, company2.getUsers().size() ); - - try { - assertEquals( 0, company1.getUsers().size() ); - } - catch ( ObjectNotFoundException e ) { - fail( "Cached element not found" ); - } - s.close(); + public void testCollectionCacheEvictionUpdateWithEntityOutOfContext(SessionFactoryScope scope) { + Company c = scope.fromSession( s -> { + Company company1 = s.get( Company.class, 1 ); + Company company2 = s.get( Company.class, 2 ); + + assertEquals( 1, company1.getUsers().size() ); + assertEquals( 0, company2.getUsers().size() ); + return company2; + } ); + scope.inTransaction( s -> { + User user = s.get( User.class, 1 ); + user.setCompany( c ); + } ); + + scope.inSession( s -> { + + var company1 = s.get( Company.class, 1 ); + var company2 = s.get( Company.class, 2 ); + + assertEquals( 1, company2.getUsers().size() ); + + try { + assertEquals( 0, company1.getUsers().size() ); + } + catch (ObjectNotFoundException e) { + fail( "Cached element not found" ); + } + } ); } @Test - public void testUpdateWithNullRelation() { - Session session = openSession(); - session.beginTransaction(); - User user = new User(); - user.setName( "User1" ); - session.persist( user ); - - session.getTransaction().commit(); - session.close(); - - session = openSession(); - session.beginTransaction(); - user.setName( "UserUpdate" ); - session.merge( user ); - - session.getTransaction().commit(); - session.close(); + public void testUpdateWithNullRelation(SessionFactoryScope scope) { + User user = scope.fromTransaction( session -> { + User u = new User(); + u.setName( "User1" ); + session.persist( u ); + return u; + } ); + + scope.inTransaction( session -> { + user.setName( "UserUpdate" ); + session.merge( user ); + } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/CollectionCacheEvictionWithoutMappedByTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/CollectionCacheEvictionWithoutMappedByTest.java index bfe15e7c00ec..457729993ee8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/CollectionCacheEvictionWithoutMappedByTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/CollectionCacheEvictionWithoutMappedByTest.java @@ -4,8 +4,6 @@ */ package org.hibernate.orm.test.cache; -import java.util.ArrayList; -import java.util.List; import jakarta.persistence.Cacheable; import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; @@ -13,150 +11,142 @@ import jakarta.persistence.Id; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; - -import org.hibernate.Session; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.cache.internal.CollectionCacheInvalidator; -import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.Assert.assertEquals; /** * @author Janario Oliveira */ -public class CollectionCacheEvictionWithoutMappedByTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] {Person.class, People.class}; - } +@DomainModel( + annotatedClasses = { + CollectionCacheEvictionWithoutMappedByTest.Person.class, + CollectionCacheEvictionWithoutMappedByTest.People.class + } +) +@ServiceRegistry( + settings = { + @Setting(name = Environment.AUTO_EVICT_COLLECTION_CACHE, value = "true"), + @Setting(name = Environment.USE_SECOND_LEVEL_CACHE, value = "true"), + @Setting(name = Environment.USE_QUERY_CACHE, value = "true"), + @Setting(name = Environment.IMPLICIT_NAMING_STRATEGY, value = "legacy-jpa"), + } +) +@SessionFactory +public class CollectionCacheEvictionWithoutMappedByTest { - @Before + @BeforeEach public void before() { CollectionCacheInvalidator.PROPAGATE_EXCEPTION = true; } - @After + @AfterEach public void after() { CollectionCacheInvalidator.PROPAGATE_EXCEPTION = false; } - @Override - protected void configure(Configuration cfg) { - cfg.setProperty( Environment.AUTO_EVICT_COLLECTION_CACHE, true ); - cfg.setProperty( Environment.USE_SECOND_LEVEL_CACHE, true ); - cfg.setProperty( Environment.USE_QUERY_CACHE, true ); - } - - private People createPeople() { - Session session = openSession(); - session.beginTransaction(); - People people = new People(); - people.people.add( new Person() ); - people.people.add( new Person() ); - session.persist( people ); - - session.getTransaction().commit(); - session.close(); - return people; + private People createPeople(SessionFactoryScope scope) { + return scope.fromTransaction( session -> { + People people = new People(); + people.people.add( new Person() ); + people.people.add( new Person() ); + session.persist( people ); + return people; + } ); } - private People initCache(int id) { - Session session = openSession(); - People people = session.get( People.class, id ); - //should add in cache - assertEquals( 2, people.people.size() ); - session.close(); - return people; + private People initCache(int id, SessionFactoryScope scope) { + return scope.fromSession( session -> { + People people = session.get( People.class, id ); + //should add in cache + assertEquals( 2, people.people.size() ); + return people; + } ); } @Test - public void testCollectionCacheEvictionInsert() { - People people = createPeople(); - people = initCache( people.id ); - - Session session = openSession(); - session.beginTransaction(); - - people = session.get( People.class, people.id ); - Person person = new Person(); - session.persist( person ); - people.people.add( person ); - - session.getTransaction().commit(); - session.close(); - - session = openSession(); - - people = session.get( People.class, people.id ); - assertEquals( 3, people.people.size() ); - - session.close(); + public void testCollectionCacheEvictionInsert(SessionFactoryScope scope) { + People people = createPeople( scope ); + Integer id = people.id; + people = initCache( id, scope ); + + scope.inTransaction( session -> { + People p = session.get( People.class, id ); + Person person = new Person(); + session.persist( person ); + p.people.add( person ); + + } ); + + scope.inSession( session -> { + People p = session.get( People.class, id ); + assertEquals( 3, p.people.size() ); + } ); } @Test - public void testCollectionCacheEvictionRemove() { - People people = createPeople(); - people = initCache( people.id ); - - Session session = openSession(); - session.beginTransaction(); - - people = session.get( People.class, people.id ); - Person person = people.people.remove( 0 ); - session.remove( person ); - - session.getTransaction().commit(); - session.close(); - - session = openSession(); - - people = session.get( People.class, people.id ); - assertEquals( 1, people.people.size() ); - - session.close(); + public void testCollectionCacheEvictionRemove(SessionFactoryScope scope) { + People people = createPeople( scope ); + Integer id = people.id; + people = initCache( id, scope ); + + scope.inTransaction( session -> { + People p = session.get( People.class, id ); + Person person = p.people.remove( 0 ); + session.remove( person ); + } ); + + scope.inSession( session -> { + var p = session.get( People.class, id ); + assertEquals( 1, p.people.size() ); + } ); } @Test - public void testCollectionCacheEvictionUpdate() { - People people1 = createPeople(); - people1 = initCache( people1.id ); - People people2 = createPeople(); - people2 = initCache( people2.id ); - - - Session session = openSession(); - session.beginTransaction(); - - people1 = session.get( People.class, people1.id ); - people2 = session.get( People.class, people2.id ); - - Person person1 = people1.people.remove( 0 ); - Person person2 = people1.people.remove( 0 ); - Person person3 = people2.people.remove( 0 ); - session.flush();//avoid: Unique index or primary key violation - people1.people.add( person3 ); - people2.people.add( person2 ); - people2.people.add( person1 ); - - session.getTransaction().commit(); - session.close(); - - session = openSession(); - - people1 = session.get( People.class, people1.id ); - people2 = session.get( People.class, people2.id ); - assertEquals( 1, people1.people.size() ); - assertEquals( 3, people2.people.size() ); - - session.close(); + public void testCollectionCacheEvictionUpdate(SessionFactoryScope scope) { + People people1 = createPeople( scope ); + Integer p1id = people1.id; + people1 = initCache( p1id, scope ); + People people2 = createPeople( scope ); + Integer p2id = people2.id; + people2 = initCache( p2id, scope ); + + + scope.inTransaction( session -> { + var p1 = session.get( People.class, p1id ); + var p2 = session.get( People.class, p2id ); + + Person person1 = p1.people.remove( 0 ); + Person person2 = p1.people.remove( 0 ); + Person person3 = p2.people.remove( 0 ); + session.flush();//avoid: Unique index or primary key violation + p1.people.add( person3 ); + p2.people.add( person2 ); + p2.people.add( person1 ); + + } ); + + scope.inSession( s -> { + var p1 = s.get( People.class, p1id ); + var p2 = s.get( People.class, p2id ); + assertEquals( 1, p1.people.size() ); + assertEquals( 3, p2.people.size() ); + } ); } @Entity(name = "People") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/EntityUpdateCacheModeIgnoreTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/EntityUpdateCacheModeIgnoreTest.java index 9c90d4093667..13aa3ac30f14 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/EntityUpdateCacheModeIgnoreTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/EntityUpdateCacheModeIgnoreTest.java @@ -4,120 +4,105 @@ */ package org.hibernate.orm.test.cache; -import java.io.Serializable; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; - -import org.junit.Test; - import org.hibernate.CacheMode; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.Transaction; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; +import org.hibernate.cfg.Environment; import org.hibernate.stat.Statistics; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import java.io.Serializable; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; /** * Tests that updating an entity does not add an entity to the cache with CacheMode.IGNORE */ -public class EntityUpdateCacheModeIgnoreTest extends BaseCoreFunctionalTestCase { - - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - configuration.setProperty(AvailableSettings.USE_SECOND_LEVEL_CACHE, true); - configuration.setProperty(AvailableSettings.USE_QUERY_CACHE, true); - configuration.setProperty(AvailableSettings.GENERATE_STATISTICS, true); - } +@DomainModel( + annotatedClasses = { + EntityUpdateCacheModeIgnoreTest.PurchaseOrder.class + } +) +@ServiceRegistry( + settings = { + @Setting(name = Environment.USE_SECOND_LEVEL_CACHE, value = "true"), + @Setting(name = Environment.USE_QUERY_CACHE, value = "true"), + } +) +@SessionFactory(generateStatistics = true) +public class EntityUpdateCacheModeIgnoreTest { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - PurchaseOrder.class - }; + @AfterEach + void tearDown(SessionFactoryScope scope) { + scope.dropData(); } @Test - @JiraKey( value = "HHH9739") - public void testCachModeIgnore() { + @JiraKey(value = "HHH9739") + public void testCacheModeIgnore(SessionFactoryScope scope) { // Test that there is no interaction with cache except for invalidation when using CacheMode.IGNORE // From API Doc : CacheMode.IGNORE -> The session will never interact with the cache, except to invalidate cache items when updates occur. - Session s; - Transaction t; - SessionFactory sessionFactory; - Statistics statistics; + Statistics statistics = scope.getSessionFactory().getStatistics(); + statistics.clear(); // ---------------------------------------------------------------------------------------------- // insert - s = openSession(); - s.setCacheMode( CacheMode.IGNORE); - sessionFactory = s.getSessionFactory(); - sessionFactory.getCache().evictAllRegions(); - statistics = sessionFactory.getStatistics(); - statistics.clear(); - t = s.beginTransaction(); + scope.inTransaction( s -> { + s.setCacheMode( CacheMode.IGNORE ); + scope.getSessionFactory().getCache().evictAllRegions(); - PurchaseOrder purchaseOrder = new PurchaseOrder(1L, 2L, 1000L); - s.persist(purchaseOrder); + PurchaseOrder purchaseOrder = new PurchaseOrder( 1L, 2L, 1000L ); + s.persist( purchaseOrder ); - t.commit(); - s.close(); + } ); - assertEquals(0L, statistics.getSecondLevelCacheHitCount()); - assertEquals(0L, statistics.getSecondLevelCacheMissCount()); - assertEquals(0L, statistics.getSecondLevelCachePutCount()); - assertFalse(sessionFactory.getCache().containsEntity(PurchaseOrder.class, 1L)); + assertEquals( 0L, statistics.getSecondLevelCacheHitCount() ); + assertEquals( 0L, statistics.getSecondLevelCacheMissCount() ); + assertEquals( 0L, statistics.getSecondLevelCachePutCount() ); + assertFalse( scope.getSessionFactory().getCache().containsEntity( PurchaseOrder.class, 1L ) ); // ---------------------------------------------------------------------------------------------- // update - s = openSession(); - s.setCacheMode(CacheMode.IGNORE); - sessionFactory = s.getSessionFactory(); - sessionFactory.getCache().evictAllRegions(); - statistics = sessionFactory.getStatistics(); - statistics.clear(); - t = s.beginTransaction(); - - PurchaseOrder result = (PurchaseOrder)s.get(PurchaseOrder.class, 1L); - result.setTotalAmount(2000L); - - t.commit(); - s.close(); - - assertEquals(0, statistics.getSecondLevelCacheHitCount()); - assertEquals(0, statistics.getSecondLevelCacheMissCount()); - assertEquals(0, statistics.getSecondLevelCachePutCount()); + scope.inTransaction( s -> { + s.setCacheMode( CacheMode.IGNORE ); + scope.getSessionFactory().getCache().evictAllRegions(); + statistics.clear(); + PurchaseOrder result = (PurchaseOrder) s.get( PurchaseOrder.class, 1L ); + result.setTotalAmount( 2000L ); + } ); + + assertEquals( 0, statistics.getSecondLevelCacheHitCount() ); + assertEquals( 0, statistics.getSecondLevelCacheMissCount() ); + assertEquals( 0, statistics.getSecondLevelCachePutCount() ); // the following fails because the cache contains a lock for that entity //assertFalse(sessionFactory.getCache().containsEntity(PurchaseOrder.class, 1L)); // make sure the updated entity is not found in the cache - s = openSession(); - s.setCacheMode( CacheMode.GET ); - sessionFactory = s.getSessionFactory(); - //sessionFactory.getCache().evictAllRegions(); - t = s.beginTransaction(); - result = s.get( PurchaseOrder.class, 1L ); - assertEquals( 2000, result.getTotalAmount().longValue() ); - t.commit(); - s.close(); - - assertEquals( 0, statistics.getSecondLevelCacheHitCount()); + scope.inTransaction( s -> { + s.setCacheMode( CacheMode.GET ); + var result = s.get( PurchaseOrder.class, 1L ); + assertEquals( 2000, result.getTotalAmount().longValue() ); + } ); + + assertEquals( 0, statistics.getSecondLevelCacheHitCount() ); assertEquals( 1, statistics.getSecondLevelCacheMissCount() ); assertEquals( 0, statistics.getSecondLevelCachePutCount() ); } @Entity - @Table(name="PurchaseOrder") - @Cache(usage= CacheConcurrencyStrategy.READ_WRITE) + @Table(name = "PurchaseOrder") + @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public static class PurchaseOrder implements Serializable { private static final long serialVersionUID = 1L; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/InsertedDataTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/InsertedDataTest.java index c5e29f4813c1..f0662c1fbf09 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/InsertedDataTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/InsertedDataTest.java @@ -5,15 +5,18 @@ package org.hibernate.orm.test.cache; import org.hibernate.Session; -import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; - -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests for handling of data just inserted during a transaction being read from the database @@ -22,199 +25,137 @@ * * @author Steve Ebersole */ -public class InsertedDataTest extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { CacheableItem.class }; +@DomainModel( + annotatedClasses = { + CacheableItem.class + } +) +@ServiceRegistry( + settings = { + @Setting(name = Environment.CACHE_REGION_PREFIX, value = ""), + } +) +@SessionFactory(generateStatistics = true) +public class InsertedDataTest { + + @AfterEach + void tearDown(SessionFactoryScope scope) { + scope.getSessionFactory().getCache().evictEntityData(); + scope.getSessionFactory().getStatistics().clear(); + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } - @Override - protected void configure(Configuration cfg) { - super.configure( cfg ); - cfg.setProperty( Environment.CACHE_REGION_PREFIX, "" ); - cfg.setProperty( Environment.GENERATE_STATISTICS, true ); + @Test + public void testInsert(SessionFactoryScope scope) { + CacheableItem item = scope.fromTransaction( s -> { + CacheableItem i = new CacheableItem( "data" ); + s.persist( i ); + return i; + } ); + + assertTrue( scope.getSessionFactory().getCache().containsEntity( CacheableItem.class, item.getId() ) ); } @Test - public void testInsert() { - sessionFactory().getCache().evictEntityData(); - sessionFactory().getStatistics().clear(); - - Session s = openSession(); - s.beginTransaction(); + public void testInsertWithRollback(SessionFactoryScope scope) { CacheableItem item = new CacheableItem( "data" ); - s.persist( item ); - s.getTransaction().commit(); - s.close(); - - assertTrue( sessionFactory().getCache().containsEntity( CacheableItem.class, item.getId() ) ); - - s = openSession(); - s.beginTransaction(); - s.createQuery( "delete CacheableItem" ).executeUpdate(); - s.getTransaction().commit(); - s.close(); + try (Session s = scope.getSessionFactory().openSession()) { + s.beginTransaction(); + s.persist( item ); + s.flush(); + s.getTransaction().rollback(); + } + + assertFalse( scope.getSessionFactory().getCache().containsEntity( CacheableItem.class, item.getId() ) ); } @Test - public void testInsertWithRollback() { - sessionFactory().getCache().evictEntityData(); - sessionFactory().getStatistics().clear(); - - Session s = openSession(); - s.beginTransaction(); - CacheableItem item = new CacheableItem( "data" ); - s.persist( item ); - s.flush(); - s.getTransaction().rollback(); - s.close(); - - assertFalse( sessionFactory().getCache().containsEntity( CacheableItem.class, item.getId() ) ); + public void testInsertThenUpdate(SessionFactoryScope scope) { + CacheableItem item = scope.fromTransaction( s -> { + CacheableItem i = new CacheableItem( "data" ); + s.persist( i ); + s.flush(); + i.setName( "new data" ); + return i; + } ); + + assertTrue( scope.getSessionFactory().getCache().containsEntity( CacheableItem.class, item.getId() ) ); } @Test - public void testInsertThenUpdate() { - sessionFactory().getCache().evictEntityData(); - sessionFactory().getStatistics().clear(); - - Session s = openSession(); - s.beginTransaction(); + public void testInsertThenUpdateThenRollback(SessionFactoryScope scope) { CacheableItem item = new CacheableItem( "data" ); - s.persist( item ); - s.flush(); - item.setName( "new data" ); - s.getTransaction().commit(); - s.close(); - - assertTrue( sessionFactory().getCache().containsEntity( CacheableItem.class, item.getId() ) ); - - - s = openSession(); - s.beginTransaction(); - s.createQuery( "delete CacheableItem" ).executeUpdate(); - s.getTransaction().commit(); - s.close(); + try (Session s = scope.getSessionFactory().openSession()) { + s.beginTransaction(); + s.persist( item ); + s.flush(); + item.setName( "new data" ); + s.getTransaction().rollback(); + } + + assertFalse( scope.getSessionFactory().getCache().containsEntity( CacheableItem.class, item.getId() ) ); } @Test - public void testInsertThenUpdateThenRollback() { - sessionFactory().getCache().evictEntityData(); - sessionFactory().getStatistics().clear(); - - Session s = openSession(); - s.beginTransaction(); - CacheableItem item = new CacheableItem( "data" ); - s.persist( item ); - s.flush(); - item.setName( "new data" ); - s.getTransaction().rollback(); - s.close(); - - assertFalse( sessionFactory().getCache().containsEntity( CacheableItem.class, item.getId() ) ); - - s = openSession(); - s.beginTransaction(); - s.createQuery( "delete CacheableItem" ).executeUpdate(); - s.getTransaction().commit(); - s.close(); + public void testInsertWithRefresh(SessionFactoryScope scope) { + CacheableItem item = scope.fromTransaction( s -> { + CacheableItem i = new CacheableItem( "data" ); + s.persist( i ); + s.flush(); + s.refresh( i ); + return i; + } ); + + assertTrue( scope.getSessionFactory().getCache().containsEntity( CacheableItem.class, item.getId() ) ); } @Test - public void testInsertWithRefresh() { - sessionFactory().getCache().evictEntityData(); - sessionFactory().getStatistics().clear(); - - Session s = openSession(); - s.beginTransaction(); + public void testInsertWithRefreshThenRollback(SessionFactoryScope scope) { CacheableItem item = new CacheableItem( "data" ); - s.persist( item ); - s.flush(); - s.refresh( item ); - s.getTransaction().commit(); - s.close(); - - assertTrue( sessionFactory().getCache().containsEntity( CacheableItem.class, item.getId() ) ); - - s = openSession(); - s.beginTransaction(); - s.createQuery( "delete CacheableItem" ).executeUpdate(); - s.getTransaction().commit(); - s.close(); - } + try (Session s = scope.getSessionFactory().openSession()) { + s.beginTransaction(); + s.persist( item ); + s.flush(); + s.refresh( item ); + s.getTransaction().rollback(); + } - @Test - public void testInsertWithRefreshThenRollback() { - sessionFactory().getCache().evictEntityData(); - sessionFactory().getStatistics().clear(); + assertTrue( scope.getSessionFactory().getCache().containsEntity( CacheableItem.class, item.getId() ) ); - Session s = openSession(); - s.beginTransaction(); - CacheableItem item = new CacheableItem( "data" ); - s.persist( item ); - s.flush(); - s.refresh( item ); - s.getTransaction().rollback(); - s.close(); - - assertTrue( sessionFactory().getCache().containsEntity( CacheableItem.class, item.getId() ) ); -// Object lock = cacheMap.values().iterator().next(); -// assertEquals( "org.hibernate.testing.cache.AbstractReadWriteAccessStrategy$Lock", lock.getClass().getName() ); - - s = openSession(); - s.beginTransaction(); - item = s.get( CacheableItem.class, item.getId() ); - s.getTransaction().commit(); - s.close(); - - assertNull( "it should be null", item ); + CacheableItem item1 = scope.fromTransaction( s -> s.get( CacheableItem.class, item.getId() ) ); + + assertNull( item1, "it should be null" ); } @Test - public void testInsertWithClear() { - sessionFactory().getCache().evictEntityData(); - sessionFactory().getStatistics().clear(); - - Session s = openSession(); - s.beginTransaction(); - CacheableItem item = new CacheableItem( "data" ); - s.persist( item ); - s.flush(); - s.clear(); - s.getTransaction().commit(); - s.close(); - - assertTrue( sessionFactory().getCache().containsEntity( CacheableItem.class, item.getId() ) ); - - s = openSession(); - s.beginTransaction(); - s.createQuery( "delete CacheableItem" ).executeUpdate(); - s.getTransaction().commit(); - s.close(); + public void testInsertWithClear(SessionFactoryScope scope) { + CacheableItem item = scope.fromTransaction( s -> { + CacheableItem i = new CacheableItem( "data" ); + s.persist( i ); + s.flush(); + s.clear(); + return i; + } ); + + assertTrue( scope.getSessionFactory().getCache().containsEntity( CacheableItem.class, item.getId() ) ); } @Test - public void testInsertWithClearThenRollback() { - sessionFactory().getCache().evictEntityData(); - sessionFactory().getStatistics().clear(); - - Session s = openSession(); - s.beginTransaction(); + public void testInsertWithClearThenRollback(SessionFactoryScope scope) { CacheableItem item = new CacheableItem( "data" ); - s.persist( item ); - s.flush(); - s.clear(); - item = (CacheableItem) s.get( CacheableItem.class, item.getId() ); - s.getTransaction().rollback(); - s.close(); - - assertFalse( sessionFactory().getCache().containsEntity( CacheableItem.class, item.getId() ) ); - - s = openSession(); - s.beginTransaction(); - item = (CacheableItem) s.get( CacheableItem.class, item.getId() ); - s.getTransaction().commit(); - s.close(); - - assertNull( "it should be null", item ); + try (Session s = scope.getSessionFactory().openSession()) { + s.beginTransaction(); + s.persist( item ); + s.flush(); + s.clear(); + item = s.get( CacheableItem.class, item.getId() ); + s.getTransaction().rollback(); + } + + assertFalse( scope.getSessionFactory().getCache().containsEntity( CacheableItem.class, item.getId() ) ); + + Long id = item.getId(); + item = scope.fromTransaction( s -> s.get( CacheableItem.class, id ) ); + assertNull( item, "it should be null" ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/LockModeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/LockModeTest.java index 97c07f630fb6..c2aba16e3106 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/LockModeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/LockModeTest.java @@ -4,57 +4,55 @@ */ package org.hibernate.orm.test.cache; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - import org.hibernate.LockMode; -import org.hibernate.Session; import org.hibernate.cache.internal.CollectionCacheInvalidator; -import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; -import org.hibernate.metamodel.CollectionClassification; - +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.hibernate.cfg.AvailableSettings.DEFAULT_LIST_SEMANTICS; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; /** * @author Guenther Demetz * @author Gail Badner */ -public class LockModeTest extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { User.class, Company.class }; - } - - @Before +@DomainModel( + annotatedClasses = { + User.class, Company.class + } +) +@ServiceRegistry( + settings = { + @Setting(name = Environment.USE_SECOND_LEVEL_CACHE, value = "true"), + @Setting(name = Environment.AUTO_EVICT_COLLECTION_CACHE, value = "true"), + @Setting(name = Environment.USE_QUERY_CACHE, value = "true"), + @Setting(name = Environment.DEFAULT_LIST_SEMANTICS, value = "bag"), // CollectionClassification.BAG + } +) +@SessionFactory +public class LockModeTest { + + @BeforeEach public void before() { CollectionCacheInvalidator.PROPAGATE_EXCEPTION = true; } - @After + @AfterEach public void after() { CollectionCacheInvalidator.PROPAGATE_EXCEPTION = false; } - @Override - protected void configure(Configuration cfg) { - super.configure( cfg ); - cfg.setProperty( Environment.AUTO_EVICT_COLLECTION_CACHE, true ); - cfg.setProperty( Environment.USE_SECOND_LEVEL_CACHE, true ); - cfg.setProperty( Environment.USE_QUERY_CACHE, true ); - cfg.setProperty( DEFAULT_LIST_SEMANTICS, CollectionClassification.BAG ); - } - - @Override - protected void prepareTest() { - inTransaction( - s -> { + @BeforeEach + protected void prepareTest(SessionFactoryScope scope) { + scope.inTransaction( s -> { Company company1 = new Company( 1 ); s.persist( company1 ); @@ -67,122 +65,108 @@ protected void prepareTest() { ); } - @Override - protected void cleanupTest() { - inTransaction( - s -> { - s.createQuery( "delete from org.hibernate.orm.test.cache.User" ).executeUpdate(); - s.createQuery( "delete from org.hibernate.orm.test.cache.Company" ).executeUpdate(); - - } - ); + @AfterEach + protected void cleanupTest(SessionFactoryScope scope) { + scope.dropData(); + scope.getSessionFactory().getCache().evictAll(); } /** + * */ @JiraKey(value = "HHH-9764") @Test - public void testDefaultLockModeOnCollectionInitialization() { - Session s1 = openSession(); - s1.beginTransaction(); - - Company company1 = s1.get( Company.class, 1 ); - - User user1 = s1.get( User.class, 1 ); // into persistent context - - /****************************************** - * - */ - Session s2 = openSession(); - s2.beginTransaction(); - User user = s2.get( User.class, 1 ); - user.setName("TestUser"); - s2.getTransaction().commit(); - s2.close(); + public void testDefaultLockModeOnCollectionInitialization(SessionFactoryScope scope) { + scope.inTransaction( s1 -> { + Company company1 = s1.get( Company.class, 1 ); - /****************************************** - * - */ + User user1 = s1.get( User.class, 1 ); // into persistent context - // init cache of collection - assertEquals( 1, company1.getUsers().size() ); // raises org.hibernate.StaleObjectStateException if 2LCache is enabled + /****************************************** + * + */ + scope.inTransaction( s2 -> { + User user = s2.get( User.class, 1 ); + user.setName( "TestUser" ); + } ); + /****************************************** + * + */ - s1.getTransaction().commit(); - s1.close(); + // init cache of collection + assertEquals( 1, company1.getUsers() + .size() ); // raises org.hibernate.StaleObjectStateException if 2LCache is enabled + } ); } @JiraKey(value = "HHH-9764") @Test - public void testDefaultLockModeOnEntityLoad() { + public void testDefaultLockModeOnEntityLoad(SessionFactoryScope scope) { // first evict user - sessionFactory().getCache().evictEntityData( User.class.getName(), 1 ); + scope.getSessionFactory().getCache().evictEntityData( User.class.getName(), 1 ); - Session s1 = openSession(); - s1.beginTransaction(); + scope.inTransaction( s1 -> { - Company company1 = s1.get( Company.class, 1 ); + Company company1 = s1.get( Company.class, 1 ); - /****************************************** - * - */ - Session s2 = openSession(); - s2.beginTransaction(); - Company company = s2.get( Company.class, 1 ); - company.setName( "TestCompany" ); - s2.getTransaction().commit(); - s2.close(); + /****************************************** + * + */ + scope.inTransaction( s2 -> { + Company company = s2.get( Company.class, 1 ); + company.setName( "TestCompany" ); + } ); - /****************************************** - * - */ + /****************************************** + * + */ - User user1 = s1.get( User.class, 1 ); // into persistent context + User user1 = s1.get( User.class, 1 ); // into persistent context - // init cache of collection - assertNull( user1.getCompany().getName() ); // raises org.hibernate.StaleObjectStateException if 2LCache is enabled + // init cache of collection + assertNull( + user1.getCompany() + .getName() ); // raises org.hibernate.StaleObjectStateException if 2LCache is enabled - s1.getTransaction().commit(); - s1.close(); + } ); } @JiraKey(value = "HHH-9764") @Test - public void testReadLockModeOnEntityLoad() { + public void testReadLockModeOnEntityLoad(SessionFactoryScope scope) { // first evict user - sessionFactory().getCache().evictEntityData( User.class.getName(), 1 ); + scope.getSessionFactory().getCache().evictEntityData( User.class.getName(), 1 ); - Session s1 = openSession(); - s1.beginTransaction(); + scope.inTransaction( s1 -> { - Company company1 = s1.get( Company.class, 1 ); + Company company1 = s1.get( Company.class, 1 ); - /****************************************** - * - */ - Session s2 = openSession(); - s2.beginTransaction(); - Company company = s2.get( Company.class, 1 ); - company.setName( "TestCompany" ); - s2.getTransaction().commit(); - s2.close(); + /****************************************** + * + */ + scope.inTransaction( s2 -> { + Company company = s2.get( Company.class, 1 ); + company.setName( "TestCompany" ); + } ); - /****************************************** - * - */ + /****************************************** + * + */ - User user1 = s1.get( User.class, 1, LockMode.READ ); // into persistent context + User user1 = s1.get( User.class, 1, LockMode.READ ); // into persistent context - // init cache of collection - assertNull( user1.getCompany().getName() ); // raises org.hibernate.StaleObjectStateException if 2LCache is enabled + // init cache of collection + assertNull( + user1.getCompany() + .getName() ); // raises org.hibernate.StaleObjectStateException if 2LCache is enabled - s1.getTransaction().commit(); - s1.close(); + } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/ManyToManyCollectionCacheEvictionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/ManyToManyCollectionCacheEvictionTest.java index 85877891820b..790decfac0a1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/ManyToManyCollectionCacheEvictionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/ManyToManyCollectionCacheEvictionTest.java @@ -4,92 +4,87 @@ */ package org.hibernate.orm.test.cache; -import java.util.ArrayList; -import java.util.List; import jakarta.persistence.Cacheable; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.ManyToMany; import jakarta.persistence.Table; - -import org.hibernate.Session; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.cache.internal.CollectionCacheInvalidator; -import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; -import org.hibernate.metamodel.CollectionClassification; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import java.util.ArrayList; +import java.util.List; -import static org.hibernate.cfg.AvailableSettings.DEFAULT_LIST_SEMANTICS; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Janario Oliveira */ -public class ManyToManyCollectionCacheEvictionTest extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] {Customer.class, Application.class}; - } - - @Before +@DomainModel( + annotatedClasses = { + ManyToManyCollectionCacheEvictionTest.Customer.class, + ManyToManyCollectionCacheEvictionTest.Application.class + } +) +@ServiceRegistry( + settings = { + @Setting(name = Environment.USE_SECOND_LEVEL_CACHE, value = "true"), + @Setting(name = Environment.AUTO_EVICT_COLLECTION_CACHE, value = "true"), + @Setting(name = Environment.USE_QUERY_CACHE, value = "true"), + @Setting(name = Environment.DEFAULT_LIST_SEMANTICS, value = "bag"), // CollectionClassification.BAG + } +) +@SessionFactory +public class ManyToManyCollectionCacheEvictionTest { + + @BeforeEach public void before() { CollectionCacheInvalidator.PROPAGATE_EXCEPTION = true; } - @After + @AfterEach public void after() { CollectionCacheInvalidator.PROPAGATE_EXCEPTION = false; } - @Override - protected void configure(Configuration cfg) { - super.configure( cfg ); - cfg.setProperty( Environment.AUTO_EVICT_COLLECTION_CACHE, true ); - cfg.setProperty( Environment.USE_SECOND_LEVEL_CACHE, true ); - cfg.setProperty( Environment.USE_QUERY_CACHE, true ); - cfg.setProperty( DEFAULT_LIST_SEMANTICS, CollectionClassification.BAG ); - } - @Test - public void testManyToManyPersist() { + public void testManyToManyPersist(SessionFactoryScope scope) { //if an error happen, it will propagate the exception failing the test case - Session s = openSession(); - s.beginTransaction(); - - Application application = new Application(); - s.persist( application ); - - Customer customer = new Customer(); - customer.applications.add( application ); - s.persist( customer ); - - s.getTransaction().commit(); - s.close(); - - - s = openSession(); - - assertEquals( 1, s.get( Application.class, application.id ).customers.size() ); - assertEquals( 1, s.get( Customer.class, customer.id ).applications.size() ); - - s.close(); - - s = openSession(); - s.beginTransaction(); - - Customer customer2 = new Customer(); - customer2.applications.add( application ); - s.persist( customer2 ); - - s.getTransaction().commit(); - s.close(); + Application application = scope.fromTransaction( s -> { + Application a = new Application(); + s.persist( a ); + return a; + } ); + + Customer customer = scope.fromTransaction( s -> { + Customer c = new Customer(); + c.applications.add( application ); + s.persist( c ); + return c; + } ); + + scope.inSession( s -> { + assertEquals( 1, s.get( Application.class, application.id ).customers.size() ); + assertEquals( 1, s.get( Customer.class, customer.id ).applications.size() ); + } ); + + + scope.inTransaction( s -> { + Customer customer2 = new Customer(); + customer2.applications.add( application ); + s.persist( customer2 ); + }); } @Entity(name = "Customer") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/NoCachingRegionFactoryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/NoCachingRegionFactoryTest.java index 2cec66eda70a..78d526a2f6e3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/NoCachingRegionFactoryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/NoCachingRegionFactoryTest.java @@ -4,28 +4,38 @@ */ package org.hibernate.orm.test.cache; -import org.hibernate.cache.internal.NoCachingRegionFactory; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; +import org.hibernate.cfg.Environment; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.Assert.assertFalse; /** * @author Gail Badner. */ -public class NoCachingRegionFactoryTest extends BaseCoreFunctionalTestCase { - @Override - protected void configure(Configuration configuration) { - configuration.setProperty( AvailableSettings.CACHE_REGION_FACTORY, NoCachingRegionFactory.class ); - } +@DomainModel( + annotatedClasses = { + ReferenceCacheTest.MyReferenceData.class + } +) +@ServiceRegistry( + settings = { + @Setting(name = Environment.CACHE_REGION_FACTORY, value = "org.hibernate.cache.internal.NoCachingRegionFactory"), + } +) +@SessionFactory +public class NoCachingRegionFactoryTest { @Test @JiraKey( value = "HHH-12508" ) - public void testSessionFactoryOptionsConsistent() { - assertFalse( sessionFactory().getSessionFactoryOptions().isSecondLevelCacheEnabled() ); + public void testSessionFactoryOptionsConsistent(SessionFactoryScope scope) { + assertFalse( scope.getSessionFactory().getSessionFactoryOptions().isSecondLevelCacheEnabled() ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/NonRootEntityWithCacheAnnotationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/NonRootEntityWithCacheAnnotationTest.java index 6161503ecb20..bea22ce7e67f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/NonRootEntityWithCacheAnnotationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/NonRootEntityWithCacheAnnotationTest.java @@ -17,19 +17,16 @@ import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.cache.CachingRegionFactory; -import org.hibernate.testing.logger.LoggerInspectionRule; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Rule; -import org.junit.Test; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Inheritance; import jakarta.persistence.SharedCacheMode; +import org.junit.jupiter.api.Test; -import static org.hibernate.internal.CoreMessageLogger.CORE_LOGGER; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Gail Badner @@ -37,9 +34,6 @@ @JiraKey( value = "HHH-11143") public class NonRootEntityWithCacheAnnotationTest { - @Rule - public LoggerInspectionRule logInspection = new LoggerInspectionRule( CORE_LOGGER ); - @Test public void testCacheOnNonRootEntity() { Map settings = new HashMap<>(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/NonRootEntityWithCacheableAnnotationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/NonRootEntityWithCacheableAnnotationTest.java index 2ab1f449d0f8..78faf5bed022 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/NonRootEntityWithCacheableAnnotationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/NonRootEntityWithCacheableAnnotationTest.java @@ -6,30 +6,30 @@ import java.util.HashMap; import java.util.Map; +import java.util.Set; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Environment; +import org.hibernate.internal.CoreMessageLogger; import org.hibernate.service.spi.ServiceRegistryImplementor; +import org.hibernate.testing.logger.LogInspectionHelper; +import org.hibernate.testing.logger.TriggerOnPrefixLogListener; import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.cache.CachingRegionFactory; -import org.hibernate.testing.logger.LoggerInspectionRule; -import org.hibernate.testing.logger.Triggerable; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Rule; -import org.junit.Test; import jakarta.persistence.Cacheable; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Inheritance; import jakarta.persistence.SharedCacheMode; +import org.junit.jupiter.api.Test; -import static org.hibernate.internal.CoreMessageLogger.CORE_LOGGER; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Gail Badner @@ -37,9 +37,6 @@ @JiraKey( value = "HHH-11143") public class NonRootEntityWithCacheableAnnotationTest { - @Rule - public LoggerInspectionRule logInspection = new LoggerInspectionRule( CORE_LOGGER ); - @Test public void testCacheableOnNonRootEntity() { Map settings = new HashMap<>(); @@ -51,7 +48,8 @@ public void testCacheableOnNonRootEntity() { .applySettings( settings ) .build()) { - Triggerable triggerable = logInspection.watchForLogMessages( "HHH000482" ); + TriggerOnPrefixLogListener trigger = new TriggerOnPrefixLogListener( Set.of( "HHH000482" ) ); + LogInspectionHelper.registerListener( trigger, CoreMessageLogger.CORE_LOGGER ); Metadata metadata = new MetadataSources( serviceRegistry ) .addAnnotatedClass( ABase.class ) @@ -61,7 +59,7 @@ public void testCacheableOnNonRootEntity() { assertFalse( metadata.getEntityBinding( ABase.class.getName() ).isCached() ); assertTrue( metadata.getEntityBinding( AEntity.class.getName() ).isCached() ); - assertFalse( triggerable.wasTriggered() ); + assertFalse( trigger.wasTriggered() ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/ReferenceCacheTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/ReferenceCacheTest.java index ca2c3951dd08..65d3a46c5f7b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/ReferenceCacheTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/ReferenceCacheTest.java @@ -4,43 +4,47 @@ */ package org.hibernate.orm.test.cache; -import org.hibernate.Session; +import jakarta.persistence.Cacheable; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.Immutable; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; +import org.hibernate.cfg.Environment; import org.hibernate.persister.entity.EntityPersister; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; - -import jakarta.persistence.Cacheable; -import jakarta.persistence.Entity; -import jakarta.persistence.Id; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * @author Steve Ebersole */ -public class ReferenceCacheTest extends BaseCoreFunctionalTestCase { - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - configuration.setProperty( AvailableSettings.USE_DIRECT_REFERENCE_CACHE_ENTRIES, true ); - configuration.setProperty( AvailableSettings.USE_QUERY_CACHE, true ); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { MyReferenceData.class }; - } +@DomainModel( + annotatedClasses = { + ReferenceCacheTest.MyReferenceData.class + } +) +@ServiceRegistry( + settings = { + @Setting(name = Environment.USE_DIRECT_REFERENCE_CACHE_ENTRIES, value = "true"), + @Setting(name = Environment.USE_QUERY_CACHE, value = "true"), + } +) +@SessionFactory +public class ReferenceCacheTest { @Test - public void testUseOfDirectReferencesInCache() throws Exception { - EntityPersister persister = sessionFactory().getMappingMetamodel().getEntityDescriptor( MyReferenceData.class ); + public void testUseOfDirectReferencesInCache(SessionFactoryScope scope) throws Exception { + EntityPersister persister = scope.getSessionFactory().getMappingMetamodel() + .getEntityDescriptor( MyReferenceData.class ); assertFalse( persister.isMutable() ); assertTrue( persister.buildCacheEntry( null, null, null, null ).isReferenceEntry() ); assertFalse( persister.hasProxy() ); @@ -48,45 +52,37 @@ public void testUseOfDirectReferencesInCache() throws Exception { final MyReferenceData myReferenceData = new MyReferenceData( 1, "first item", "abc" ); // save a reference in one session - Session s = openSession(); - s.beginTransaction(); - s.persist( myReferenceData ); - s.getTransaction().commit(); - s.close(); + scope.inTransaction( s -> { + s.persist( myReferenceData ); + } ); // now load it in another - s = openSession(); - s.beginTransaction(); -// MyReferenceData loaded = (MyReferenceData) s.get( MyReferenceData.class, 1 ); - MyReferenceData loaded = (MyReferenceData) s.getReference( MyReferenceData.class, 1 ); - s.getTransaction().commit(); - s.close(); + MyReferenceData loaded = scope.fromTransaction( s -> { + return (MyReferenceData) s.getReference( MyReferenceData.class, 1 ); + } ); // the 2 instances should be the same (==) - assertTrue( "The two instances were different references", myReferenceData == loaded ); + assertSame( myReferenceData, loaded, "The two instances were different references" ); // now try query caching - s = openSession(); - s.beginTransaction(); - MyReferenceData queried = (MyReferenceData) s.createQuery( "from MyReferenceData" ).setCacheable( true ).list().get( 0 ); - s.getTransaction().commit(); - s.close(); + MyReferenceData queried = scope.fromTransaction( s -> { + return (MyReferenceData) s.createQuery( "from MyReferenceData" ).setCacheable( true ) + .list().get( 0 ); + } ); // the 2 instances should be the same (==) - assertTrue( "The two instances were different references", myReferenceData == queried ); + assertSame( myReferenceData, queried, "The two instances were different references" ); // cleanup - s = openSession(); - s.beginTransaction(); - s.remove( myReferenceData ); - s.getTransaction().commit(); - s.close(); + scope.inTransaction( s -> { + s.remove( myReferenceData ); + } ); } - @Entity( name="MyReferenceData" ) + @Entity(name = "MyReferenceData") @Immutable @Cacheable - @Cache( usage = CacheConcurrencyStrategy.READ_ONLY ) + @Cache(usage = CacheConcurrencyStrategy.READ_ONLY) @SuppressWarnings("unused") public static class MyReferenceData { @Id diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/RefreshUpdatedDataTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/RefreshUpdatedDataTest.java index 7e8f569cd35b..a493d18ea07a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/RefreshUpdatedDataTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/RefreshUpdatedDataTest.java @@ -4,180 +4,179 @@ */ package org.hibernate.orm.test.cache; -import static org.junit.Assert.assertEquals; - -import java.sql.Statement; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - +import jakarta.persistence.ElementCollection; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.Version; import org.hibernate.Session; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; -import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.dialect.H2Dialect; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import jakarta.persistence.ElementCollection; -import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.Id; -import jakarta.persistence.Version; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Zhenlei Huang */ @JiraKey(value = "HHH-10649") @RequiresDialect(value = H2Dialect.class) -public class RefreshUpdatedDataTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - ReadWriteCacheableItem.class, - ReadWriteVersionedCacheableItem.class, - }; - } - - @Override - protected void configure(Configuration cfg) { - super.configure( cfg ); - Properties properties = Environment.getProperties(); - if ( H2Dialect.class.getName().equals( properties.get( Environment.DIALECT ) ) ) { - cfg.setProperty( Environment.URL, "jdbc:h2:mem:db-mvcc;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE" ); +@DomainModel( + annotatedClasses = { + RefreshUpdatedDataTest.ReadWriteCacheableItem.class, + RefreshUpdatedDataTest.ReadWriteVersionedCacheableItem.class, + } +) +@ServiceRegistry( + settings = { + @Setting(name = Environment.URL, + value = "jdbc:h2:mem:db-mvcc;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"), + @Setting(name = Environment.USE_QUERY_CACHE, value = "true"), + @Setting(name = Environment.CACHE_REGION_PREFIX, value = ""), + @Setting(name = Environment.CACHE_REGION_FACTORY, + value = "org.hibernate.testing.cache.CachingRegionFactory"), } - cfg.setProperty( Environment.CACHE_REGION_PREFIX, "" ); - cfg.setProperty( Environment.GENERATE_STATISTICS, true ); - cfg.setProperty( Environment.USE_SECOND_LEVEL_CACHE, true ); +) +@SessionFactory(generateStatistics = true) +public class RefreshUpdatedDataTest { + + @AfterEach + void tearDown(SessionFactoryScope scope) { + scope.dropData(); } @Test - public void testUpdateAndFlushThenRefresh() { + public void testUpdateAndFlushThenRefresh(SessionFactoryScope scope) { // prepare data - Session s = openSession(); - s.beginTransaction(); - + ReadWriteCacheableItem readWriteCacheableItem; + ReadWriteVersionedCacheableItem readWriteVersionedCacheableItem; final String BEFORE = "before"; - - ReadWriteCacheableItem readWriteCacheableItem = new ReadWriteCacheableItem( BEFORE ); - readWriteCacheableItem.getTags().add( "Hibernate" ); - readWriteCacheableItem.getTags().add( "ORM" ); - s.persist( readWriteCacheableItem ); - - ReadWriteVersionedCacheableItem readWriteVersionedCacheableItem = new ReadWriteVersionedCacheableItem( BEFORE ); - readWriteVersionedCacheableItem.getTags().add( "Hibernate" ); - readWriteVersionedCacheableItem.getTags().add( "ORM" ); - s.persist( readWriteVersionedCacheableItem ); - - s.getTransaction().commit(); - s.close(); - - Session s1 = openSession(); - s1.beginTransaction(); - final String AFTER = "after"; - ReadWriteCacheableItem readWriteCacheableItem1 = s1.get( ReadWriteCacheableItem.class, readWriteCacheableItem.getId() ); - readWriteCacheableItem1.setName( AFTER ); - readWriteCacheableItem1.getTags().remove("ORM"); - - ReadWriteVersionedCacheableItem readWriteVersionedCacheableItem1 = s1.get( ReadWriteVersionedCacheableItem.class, readWriteVersionedCacheableItem.getId() ); - readWriteVersionedCacheableItem1.setName( AFTER ); - readWriteVersionedCacheableItem1.getTags().remove("ORM"); - - s1.flush(); - s1.refresh( readWriteCacheableItem1 ); - s1.refresh( readWriteVersionedCacheableItem1 ); - - assertEquals( AFTER, readWriteCacheableItem1.getName() ); - assertEquals( 1, readWriteCacheableItem1.getTags().size() ); - assertEquals( AFTER, readWriteVersionedCacheableItem1.getName() ); - assertEquals( 1, readWriteVersionedCacheableItem1.getTags().size() ); - - // open another session - Session s2 = sessionFactory().openSession(); - try { - s2.beginTransaction(); - ReadWriteCacheableItem readWriteCacheableItem2 = s2.get( ReadWriteCacheableItem.class, readWriteCacheableItem.getId() ); - ReadWriteVersionedCacheableItem readWriteVersionedCacheableItem2 = s2.get( ReadWriteVersionedCacheableItem.class, readWriteVersionedCacheableItem.getId() ); - - assertEquals( BEFORE, readWriteCacheableItem2.getName() ); - assertEquals( 2, readWriteCacheableItem2.getTags().size() ); - assertEquals( BEFORE, readWriteVersionedCacheableItem2.getName() ); - assertEquals( 2, readWriteVersionedCacheableItem2.getTags().size() ); - - s2.getTransaction().commit(); - } - finally { - if ( s2.getTransaction().getStatus().canRollback() ) { - s2.getTransaction().rollback(); - } - s2.close(); + try (var s = scope.getSessionFactory().openSession()) { + s.beginTransaction(); + readWriteCacheableItem = new ReadWriteCacheableItem( BEFORE ); + readWriteCacheableItem.getTags().add( "Hibernate" ); + readWriteCacheableItem.getTags().add( "ORM" ); + s.persist( readWriteCacheableItem ); + + readWriteVersionedCacheableItem = new ReadWriteVersionedCacheableItem( BEFORE ); + readWriteVersionedCacheableItem.getTags().add( "Hibernate" ); + readWriteVersionedCacheableItem.getTags().add( "ORM" ); + s.persist( readWriteVersionedCacheableItem ); + s.getTransaction().commit(); } - s1.getTransaction().rollback(); - s1.close(); + try (var s1 = scope.getSessionFactory().openSession()) { + s1.beginTransaction(); + ReadWriteCacheableItem readWriteCacheableItem1 = s1.get( ReadWriteCacheableItem.class, + readWriteCacheableItem.getId() ); + readWriteCacheableItem1.setName( AFTER ); + readWriteCacheableItem1.getTags().remove( "ORM" ); + + ReadWriteVersionedCacheableItem readWriteVersionedCacheableItem1 = s1.get( + ReadWriteVersionedCacheableItem.class, readWriteVersionedCacheableItem.getId() ); + readWriteVersionedCacheableItem1.setName( AFTER ); + readWriteVersionedCacheableItem1.getTags().remove( "ORM" ); + + s1.flush(); + s1.refresh( readWriteCacheableItem1 ); + s1.refresh( readWriteVersionedCacheableItem1 ); + + assertEquals( AFTER, readWriteCacheableItem1.getName() ); + assertEquals( 1, readWriteCacheableItem1.getTags().size() ); + assertEquals( AFTER, readWriteVersionedCacheableItem1.getName() ); + assertEquals( 1, readWriteVersionedCacheableItem1.getTags().size() ); + + // open another session + try (Session s2 = scope.getSessionFactory().openSession()) { + s2.beginTransaction(); + ReadWriteCacheableItem readWriteCacheableItem2 = s2.get( ReadWriteCacheableItem.class, + readWriteCacheableItem.getId() ); + ReadWriteVersionedCacheableItem readWriteVersionedCacheableItem2 = s2.get( + ReadWriteVersionedCacheableItem.class, readWriteVersionedCacheableItem.getId() ); + + assertEquals( BEFORE, readWriteCacheableItem2.getName() ); + assertEquals( 2, readWriteCacheableItem2.getTags().size() ); + assertEquals( BEFORE, readWriteVersionedCacheableItem2.getName() ); + assertEquals( 2, readWriteVersionedCacheableItem2.getTags().size() ); + + s2.getTransaction().commit(); + } - s = openSession(); - s.beginTransaction(); - s.remove( readWriteCacheableItem ); - s.remove( readWriteVersionedCacheableItem ); - s.getTransaction().commit(); - s.close(); + s1.getTransaction().rollback(); + } } @Test - public void testExternalUpdateRefresh() { + public void testExternalUpdateRefresh(SessionFactoryScope scope) { // prepare data - Session s = openSession(); - s.beginTransaction(); - final String BEFORE = "before"; - ReadWriteVersionedCacheableItem readWriteVersionedCacheableItem = new ReadWriteVersionedCacheableItem( BEFORE ); - readWriteVersionedCacheableItem.getTags().add( "Hibernate" ); - readWriteVersionedCacheableItem.getTags().add( "ORM" ); - s.persist( readWriteVersionedCacheableItem ); - - s.getTransaction().commit(); - s.close(); + try (var s = scope.getSessionFactory().openSession()) { + s.beginTransaction(); + readWriteVersionedCacheableItem.getTags().add( "Hibernate" ); + readWriteVersionedCacheableItem.getTags().add( "ORM" ); + s.persist( readWriteVersionedCacheableItem ); - s = openSession(); - s.beginTransaction(); + s.getTransaction().commit(); + } - // Read the entry in to populate 2LC - readWriteVersionedCacheableItem = s.get( ReadWriteVersionedCacheableItem.class, readWriteVersionedCacheableItem.getId() ); + Session s2 = null; + int v = 0; + try (var s = scope.getSessionFactory().openSession()) { + s.beginTransaction(); - // open another session - Session s2 = sessionFactory().openSession(); - s2.beginTransaction(); - // Read from 2LC - readWriteVersionedCacheableItem = s2.get( ReadWriteVersionedCacheableItem.class, readWriteVersionedCacheableItem.getId() ); + // Read the entry in to populate 2LC + readWriteVersionedCacheableItem = s.get( ReadWriteVersionedCacheableItem.class, + readWriteVersionedCacheableItem.getId() ); - assertEquals( BEFORE, readWriteVersionedCacheableItem.getName() ); - assertEquals( 2, readWriteVersionedCacheableItem.getTags().size() ); + // open another session + s2 = scope.getSessionFactory().openSession(); + s2.beginTransaction(); + // Read from 2LC + readWriteVersionedCacheableItem = s2.get( ReadWriteVersionedCacheableItem.class, + readWriteVersionedCacheableItem.getId() ); - // Change the value externally - int version = readWriteVersionedCacheableItem.version + 1; - long id = readWriteVersionedCacheableItem.id; + assertEquals( BEFORE, readWriteVersionedCacheableItem.getName() ); + assertEquals( 2, readWriteVersionedCacheableItem.getTags().size() ); - s.doWork(connection -> { - try (Statement stmt = connection.createStatement()) { - stmt.executeUpdate("UPDATE ReadWriteVersionedCacheableItem SET version = " + version + " WHERE id = " + id); - } - }); + // Change the value externally + int version = readWriteVersionedCacheableItem.version + 1; + v = version; + long id = readWriteVersionedCacheableItem.id; - s.getTransaction().commit(); + s.doWork( connection -> { + try (Statement stmt = connection.createStatement()) { + stmt.executeUpdate( + "UPDATE ReadWriteVersionedCacheableItem SET version = " + version + " WHERE id = " + id ); + } + } ); - s.close(); + s.getTransaction().commit(); - s2.refresh(readWriteVersionedCacheableItem); + } + if ( s2 == null ) { + fail(); + } + s2.refresh( readWriteVersionedCacheableItem ); - assertEquals( version, readWriteVersionedCacheableItem.version ); + assertEquals( v, readWriteVersionedCacheableItem.version ); assertEquals( 2, readWriteVersionedCacheableItem.getTags().size() ); s2.remove( readWriteVersionedCacheableItem ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/SharedDomainDataAndQueryResultsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/SharedDomainDataAndQueryResultsTest.java index 95d15cb57e57..96e5f6dbb3a8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/SharedDomainDataAndQueryResultsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/SharedDomainDataAndQueryResultsTest.java @@ -4,37 +4,39 @@ */ package org.hibernate.orm.test.cache; -import java.util.HashSet; -import java.util.List; -import java.util.Set; import jakarta.persistence.ElementCollection; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.NamedQuery; import jakarta.persistence.QueryHint; - import org.hibernate.Hibernate; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cache.spi.CacheImplementor; import org.hibernate.cache.spi.DomainDataRegion; import org.hibernate.cache.spi.QueryResultsCache; import org.hibernate.cache.spi.Region; -import org.hibernate.cfg.AvailableSettings; +import org.hibernate.cfg.Environment; import org.hibernate.stat.CacheRegionStatistics; import org.hibernate.stat.QueryStatistics; import org.hibernate.stat.Statistics; - +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.cache.CachingRegionFactory; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -45,25 +47,39 @@ /** * @author Gail Badner */ -public class SharedDomainDataAndQueryResultsTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + SharedDomainDataAndQueryResultsTest.Dog.class + } +) +@ServiceRegistry( + settings = { + @Setting(name = Environment.USE_SECOND_LEVEL_CACHE, value = "true"), + @Setting(name = Environment.USE_QUERY_CACHE, value = "true"), + @Setting(name = Environment.CACHE_REGION_PREFIX, value = SharedDomainDataAndQueryResultsTest.PREFIX), + @Setting(name = Environment.CACHE_REGION_FACTORY, value = "org.hibernate.testing.cache.CachingRegionFactory"), + } +) +@SessionFactory(generateStatistics = true) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +public class SharedDomainDataAndQueryResultsTest { private static final String QUERY = "SELECT a FROM Dog a"; private static final String REGION = "TheRegion"; - private static final String PREFIX = "test"; + static final String PREFIX = "test"; + @Order( 2 ) @Test - @JiraKey( value = "HHH-13586") - public void testAllCachedStatistics() { - - final Statistics statistics = sessionFactory().getStatistics(); + @JiraKey(value = "HHH-13586") + public void testAllCachedStatistics(SessionFactoryScope scope) { + final Statistics statistics = scope.getSessionFactory().getStatistics(); statistics.clear(); final CacheRegionStatistics regionStatistics = statistics.getCacheRegionStatistics( REGION ); final QueryStatistics queryStatistics = statistics.getQueryStatistics( QUERY ); - doInHibernate( - this::sessionFactory, session -> { + scope.inTransaction( session -> { Dog yogi = session.get( Dog.class, "Yogi" ); @@ -104,8 +120,7 @@ public void testAllCachedStatistics() { } ); - doInHibernate( - this::sessionFactory, session -> { + scope.inTransaction( session -> { Dog yogi = session.get( Dog.class, "Yogi" ); @@ -147,8 +162,7 @@ public void testAllCachedStatistics() { } ); - doInHibernate( - this::sessionFactory, session -> { + scope.inTransaction( session -> { List dogs = session.createNamedQuery( "Dog.findAll", Dog.class ).list(); @@ -211,8 +225,7 @@ public void testAllCachedStatistics() { } ); - doInHibernate( - this::sessionFactory, session -> { + scope.inTransaction( session -> { List dogs = session.getNamedQuery( "Dog.findAll" ).list(); @@ -271,12 +284,11 @@ public void testAllCachedStatistics() { ); } + @Order( 1 ) @Test - @JiraKey( value = "HHH-13586") - public void testCacheImplementorGetRegion() { - rebuildSessionFactory(); - - final CacheImplementor cache = sessionFactory().getCache(); + @JiraKey(value = "HHH-13586") + public void testCacheImplementorGetRegion(SessionFactoryScope scope) { + final CacheImplementor cache = scope.getSessionFactory().getCache(); final Region domainDataRegion = cache.getRegion( REGION ); assertTrue( DomainDataRegion.class.isInstance( domainDataRegion ) ); assertEquals( REGION, domainDataRegion.getName() ); @@ -285,11 +297,9 @@ public void testCacheImplementorGetRegion() { // the named query is executed. assertNull( cache.getQueryResultsCacheStrictly( REGION ) ); - doInHibernate( - this::sessionFactory, session -> { - session.createNamedQuery( "Dog.findAll", Dog.class ).list(); - } - ); + scope.inTransaction( session -> { + session.createNamedQuery( "Dog.findAll", Dog.class ).list(); + } ); // No there should be a QueryResultsCache named REGION final QueryResultsCache queryResultsCache = cache.getQueryResultsCacheStrictly( REGION ); @@ -301,11 +311,12 @@ public void testCacheImplementorGetRegion() { assertSame( domainDataRegion, cache.getRegion( REGION ) ); } + @Order( 2 ) @Test - @JiraKey( value = "HHH-13586") - public void testEvictCaches() { + @JiraKey(value = "HHH-13586") + public void testEvictCaches(SessionFactoryScope scope) { - final Statistics statistics = sessionFactory().getStatistics(); + final Statistics statistics = scope.getSessionFactory().getStatistics(); statistics.clear(); assertEquals( 0, statistics.getSecondLevelCacheHitCount() ); @@ -316,9 +327,7 @@ public void testEvictCaches() { assertEquals( 0, statistics.getQueryCachePutCount() ); assertEquals( 0, statistics.getQueryCacheMissCount() ); - doInHibernate( - this::sessionFactory, session -> { - + scope.inTransaction( session -> { Dog yogi = session.get( Dog.class, "Yogi" ); assertEquals( 1, statistics.getSecondLevelCacheHitCount() ); assertEquals( 0, statistics.getSecondLevelCachePutCount() ); @@ -345,7 +354,7 @@ public void testEvictCaches() { session.clear(); statistics.clear(); - sessionFactory().getCache().evictRegion( REGION ); + scope.getSessionFactory().getCache().evictRegion( REGION ); session.createNamedQuery( "Dog.findAll", Dog.class ).list(); @@ -356,26 +365,9 @@ public void testEvictCaches() { } - @Override - protected void configureStandardServiceRegistryBuilder(StandardServiceRegistryBuilder ssrb) { - super.configureStandardServiceRegistryBuilder( ssrb ); - ssrb.applySetting( AvailableSettings.USE_SECOND_LEVEL_CACHE, true ); - ssrb.applySetting( AvailableSettings.USE_QUERY_CACHE, true ); - ssrb.applySetting( AvailableSettings.CACHE_REGION_PREFIX, PREFIX ); - ssrb.applySetting( AvailableSettings.CACHE_REGION_FACTORY, new CachingRegionFactory() ); - ssrb.applySetting( AvailableSettings.GENERATE_STATISTICS, "true" ); - } - - @Override - protected void applyMetadataSources(MetadataSources metadataSources) { - super.applyMetadataSources( metadataSources ); - metadataSources.addAnnotatedClass( Dog.class ); - } - - @Before - public void setupData() { - doInHibernate( - this::sessionFactory, session -> { + @BeforeEach + public void setupData(SessionFactoryScope scope) { + scope.inTransaction( session -> { Dog yogi = new Dog( "Yogi" ); yogi.nickNames.add( "The Yog" ); yogi.nickNames.add( "Little Boy" ); @@ -389,16 +381,10 @@ public void setupData() { ); } - @After - public void cleanupData() { - doInHibernate( - this::sessionFactory, session -> { - List dogs = session.createQuery( "from Dog", Dog.class ).getResultList(); - for ( Dog dog : dogs ) { - session.remove( dog ); - } - } - ); + @AfterEach + public void cleanupData(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); + scope.getSessionFactory().getCache().evictAll(); } @Entity(name = "Dog") @@ -408,12 +394,12 @@ public void cleanupData() { @QueryHint(name = "org.hibernate.cacheRegion", value = REGION) } ) - @Cache(usage = CacheConcurrencyStrategy.READ_ONLY, region=REGION) + @Cache(usage = CacheConcurrencyStrategy.READ_ONLY, region = REGION) public static class Dog { @Id private String name; - @Cache(usage = CacheConcurrencyStrategy.READ_ONLY, region=REGION) + @Cache(usage = CacheConcurrencyStrategy.READ_ONLY, region = REGION) @ElementCollection private Set nickNames = new HashSet<>(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/SharedRegionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/SharedRegionTest.java index 26810cfe55f1..bb86b03265c3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/SharedRegionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/SharedRegionTest.java @@ -6,64 +6,58 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; - -import org.hibernate.Session; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.AvailableSettings; - -import org.hibernate.testing.cache.CachingRegionFactory; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.cfg.Environment; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.Test; import static org.junit.Assert.assertNull; /** * @author Steve Ebersole */ -public class SharedRegionTest extends BaseNonConfigCoreFunctionalTestCase { - @Override - protected void configureStandardServiceRegistryBuilder(StandardServiceRegistryBuilder ssrb) { - super.configureStandardServiceRegistryBuilder( ssrb ); - ssrb.applySetting( AvailableSettings.USE_SECOND_LEVEL_CACHE, true ); - ssrb.applySetting( AvailableSettings.CACHE_REGION_FACTORY, new CachingRegionFactory() ); - } - @Override - protected void applyMetadataSources(MetadataSources sources) { - super.applyMetadataSources( sources ); - sources.addAnnotatedClass( StateCodes.class ); - sources.addAnnotatedClass( ZipCodes.class ); - } +@DomainModel( + annotatedClasses = { + SharedRegionTest.StateCodes.class, + SharedRegionTest.ZipCodes.class + } +) +@ServiceRegistry( + settings = { + @Setting(name = Environment.USE_SECOND_LEVEL_CACHE, value = "true"), + @Setting(name = Environment.CACHE_REGION_FACTORY, + value = "org.hibernate.testing.cache.CachingRegionFactory"), + } +) +@SessionFactory +public class SharedRegionTest { @Test - public void test() { + public void test(SessionFactoryScope scope) { // create a StateCodes - Session s = openSession(); - s.beginTransaction(); - s.persist( new StateCodes( 1 ) ); - s.getTransaction().commit(); - s.close(); + scope.inTransaction( s -> { + s.persist( new StateCodes( 1 ) ); + } ); // now try to load a ZipCodes using the same id : should just return null rather than blow up :) - s = openSession(); - s.beginTransaction(); - ZipCodes zc = s.find( ZipCodes.class, 1 ); - assertNull( zc ); - s.getTransaction().commit(); - s.close(); + scope.inTransaction( s -> { + ZipCodes zc = s.find( ZipCodes.class, 1 ); + assertNull( zc ); + } ); - s = openSession(); - s.beginTransaction(); - s.find( ZipCodes.class, 1 ); - s.getTransaction().commit(); - s.close(); + scope.inTransaction( s -> { + s.find( ZipCodes.class, 1 ); + } ); } - @Entity( name="StateCodes" ) - @Cache( region="com.acme.referenceData", usage = CacheConcurrencyStrategy.READ_WRITE ) + @Entity(name = "StateCodes") + @Cache(region = "com.acme.referenceData", usage = CacheConcurrencyStrategy.READ_WRITE) public static class StateCodes { @Id public Integer id; @@ -76,8 +70,8 @@ public StateCodes(Integer id) { } } - @Entity( name = "ZipCodes" ) - @Cache( region="com.acme.referenceData", usage = CacheConcurrencyStrategy.READ_WRITE ) + @Entity(name = "ZipCodes") + @Cache(region = "com.acme.referenceData", usage = CacheConcurrencyStrategy.READ_WRITE) public static class ZipCodes { @Id public Integer id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/SingleRegisteredProviderTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/SingleRegisteredProviderTest.java index bea4b7d4f332..2637828706d9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/SingleRegisteredProviderTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/SingleRegisteredProviderTest.java @@ -4,8 +4,6 @@ */ package org.hibernate.orm.test.cache; -import java.util.Collection; - import org.hibernate.boot.registry.BootstrapServiceRegistry; import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; import org.hibernate.boot.registry.StandardServiceRegistry; @@ -15,25 +13,24 @@ import org.hibernate.cfg.AvailableSettings; import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProvider; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; - -import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import java.util.Collection; + +import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.MatcherAssert.assertThat; /** * @author Steve Ebersole */ -public class SingleRegisteredProviderTest extends BaseUnitTestCase { +public class SingleRegisteredProviderTest { @Test public void testCachingExplicitlyDisabled() { try (final StandardServiceRegistry registry = ServiceRegistryUtil.serviceRegistryBuilder() .applySetting( AvailableSettings.USE_SECOND_LEVEL_CACHE, "false" ) .build()) { - assertThat( registry.getService( RegionFactory.class ), instanceOf( NoCachingRegionFactory.class ) ); + assertThat( registry.getService( RegionFactory.class ) ).isInstanceOf( NoCachingRegionFactory.class ); } } @@ -45,13 +42,13 @@ public void testCachingImplicitlyEnabledRegistered() { .getService( StrategySelector.class ) .getRegisteredStrategyImplementors( RegionFactory.class ); - assertThat( implementors.size(), equalTo( 1 ) ); + assertThat( implementors.size() ).isEqualTo( 1 ); final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder( bsr ) .applySetting( AvailableSettings.USE_SECOND_LEVEL_CACHE, "" ) .build(); - assertThat( ssr.getService( RegionFactory.class ), instanceOf( NoCachingRegionFactory.class ) ); + assertThat( ssr.getService( RegionFactory.class ) ).isInstanceOf( NoCachingRegionFactory.class ); } } @@ -63,7 +60,7 @@ public void testCachingImplicitlyEnabledNoRegistered() { .getService( StrategySelector.class ) .getRegisteredStrategyImplementors( RegionFactory.class ); - assertThat( implementors.size(), equalTo( 1 ) ); + assertThat( implementors.size() ).isEqualTo( 1 ); bsr.getService( StrategySelector.class ).unRegisterStrategyImplementor( RegionFactory.class, @@ -74,7 +71,7 @@ public void testCachingImplicitlyEnabledNoRegistered() { .applySetting( AvailableSettings.USE_SECOND_LEVEL_CACHE, "" ) .build(); - assertThat( ssr.getService( RegionFactory.class ), instanceOf( NoCachingRegionFactory.class ) ); + assertThat( ssr.getService( RegionFactory.class ) ).isInstanceOf( NoCachingRegionFactory.class ); } } @@ -86,7 +83,7 @@ public void testConnectionsRegistered() { .getService( StrategySelector.class ) .getRegisteredStrategyImplementors( ConnectionProvider.class ); - assertThat( implementors.size(), equalTo( 0 ) ); + assertThat( implementors.size() ).isEqualTo( 0 ); bsr.getService( StrategySelector.class ).registerStrategyImplementor( ConnectionProvider.class, @@ -98,7 +95,7 @@ public void testConnectionsRegistered() { final ConnectionProvider configuredProvider = ssr.getService( ConnectionProvider.class ); - assertThat( configuredProvider, instanceOf( DriverManagerConnectionProvider.class ) ); + assertThat( configuredProvider ).isInstanceOf( DriverManagerConnectionProvider.class ); } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/TransactionalConcurrencyCollectionCacheEvictionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/TransactionalConcurrencyCollectionCacheEvictionTest.java index 7f8573585661..a44667a38109 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/TransactionalConcurrencyCollectionCacheEvictionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/TransactionalConcurrencyCollectionCacheEvictionTest.java @@ -4,8 +4,6 @@ */ package org.hibernate.orm.test.cache; -import java.util.HashSet; -import java.util.Set; import jakarta.persistence.Access; import jakarta.persistence.AccessType; import jakarta.persistence.Cacheable; @@ -19,55 +17,52 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; - import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.cache.internal.CollectionCacheInvalidator; -import org.hibernate.cfg.Configuration; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Environment; - +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.HashSet; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; /** * @author Christian Beikov */ @JiraKey(value = "HHH-4910") -public class TransactionalConcurrencyCollectionCacheEvictionTest extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Person.class, Phone.class }; - } - - @Before - public void before() { +@DomainModel( + annotatedClasses = { + TransactionalConcurrencyCollectionCacheEvictionTest.Person.class, + TransactionalConcurrencyCollectionCacheEvictionTest.Phone.class + } +) +@SessionFactory +@ServiceRegistry( + settings = { + @Setting( name = AvailableSettings.FORMAT_SQL, value = "false" ), + @Setting( name = Environment.AUTO_EVICT_COLLECTION_CACHE, value = "true" ), + @Setting( name = Environment.USE_SECOND_LEVEL_CACHE, value = "true" ), + @Setting( name = Environment.USE_QUERY_CACHE, value = "false" ), + } +) +public class TransactionalConcurrencyCollectionCacheEvictionTest { + @BeforeEach + public void before(SessionFactoryScope scope) { CollectionCacheInvalidator.PROPAGATE_EXCEPTION = true; - } - @After - public void after() { - CollectionCacheInvalidator.PROPAGATE_EXCEPTION = false; - } - - @Override - protected void configure(Configuration cfg) { - super.configure( cfg ); - cfg.setProperty( Environment.AUTO_EVICT_COLLECTION_CACHE, true ); - cfg.setProperty( Environment.USE_SECOND_LEVEL_CACHE, true ); - cfg.setProperty( Environment.USE_QUERY_CACHE, false ); - } - - @Override - protected void prepareTest() throws Exception { - doInHibernate( - this::sessionFactory, - s -> { + scope.inTransaction( s -> { Person bart = new Person( 1L, "Bart" ); Person lisa = new Person( 2L, "Lisa" ); Person maggie = new Person( 3L, "Maggie" ); @@ -100,30 +95,22 @@ protected void prepareTest() throws Exception { ); } - @Override - protected void cleanupTest() throws Exception { - doInHibernate( - this::sessionFactory, - s -> { - s.createQuery( "delete from Phone" ).executeUpdate(); - s.createQuery( "delete from Person" ).executeUpdate(); - } - ); + @AfterEach + protected void cleanupTest(SessionFactoryScope scope) throws Exception { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); + scope.getSessionFactory().getCache().evictAll(); + CollectionCacheInvalidator.PROPAGATE_EXCEPTION = false; } @Test - public void testCollectionCacheEvictionInsert() { - doInHibernate( - this::sessionFactory, - s -> { + public void testCollectionCacheEvictionInsert(SessionFactoryScope scope) { + scope.inTransaction( s -> { Person bart = s.find( Person.class, 1L ); assertEquals( 5, bart.getPhones().size() ); s.persist( new Phone( "test", bart ) ); } ); - doInHibernate( - this::sessionFactory, - s -> { + scope.inTransaction( s -> { Person bart = s.find( Person.class, 1L ); assertEquals( 6, bart.getPhones().size() ); } @@ -131,25 +118,19 @@ public void testCollectionCacheEvictionInsert() { } @Test - public void testCollectionCacheEvictionRemove() { - Long phoneId = doInHibernate( - this::sessionFactory, - s -> { + public void testCollectionCacheEvictionRemove(SessionFactoryScope scope) { + Long phoneId = scope.fromTransaction( s -> { Person bart = s.find( Person.class, 1L ); // Lazy load phones assertEquals( 5, bart.getPhones().size() ); return bart.getPhones().iterator().next().getId(); } ); - doInHibernate( - this::sessionFactory, - s -> { + scope.inTransaction( s -> { s.remove( s.getReference( Phone.class, phoneId ) ); } ); - doInHibernate( - this::sessionFactory, - s -> { + scope.inTransaction( s -> { Person bart = s.find( Person.class, 1L ); assertEquals( 4, bart.getPhones().size() ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/cid/NonAggregatedCompositeIdCachingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/cid/NonAggregatedCompositeIdCachingTest.java index 673a82e52f26..7d04ccf010c5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/cid/NonAggregatedCompositeIdCachingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/cid/NonAggregatedCompositeIdCachingTest.java @@ -12,14 +12,13 @@ import org.hibernate.cfg.AvailableSettings; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author Steve Ebersole */ -public class NonAggregatedCompositeIdCachingTest extends BaseUnitTestCase { +public class NonAggregatedCompositeIdCachingTest { @Test @JiraKey( value = "HHH-9913" ) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/caching/mocked/CacheAccessTypeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/caching/mocked/CacheAccessTypeTest.java index d36d826e4b12..3dff3f55e1c3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/caching/mocked/CacheAccessTypeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/caching/mocked/CacheAccessTypeTest.java @@ -4,14 +4,13 @@ */ package org.hibernate.orm.test.caching.mocked; -import org.junit.Test; - import org.hibernate.cache.spi.access.AccessType; import org.hibernate.cache.spi.access.UnknownAccessTypeException; import org.hibernate.testing.orm.junit.JiraKey; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Gail Badner diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/caching/mocked/CacheKeyImplementationHashCodeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/caching/mocked/CacheKeyImplementationHashCodeTest.java index 760816a7a063..e8d4408124e8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/caching/mocked/CacheKeyImplementationHashCodeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/caching/mocked/CacheKeyImplementationHashCodeTest.java @@ -21,9 +21,9 @@ import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; /** * @author Gail Badner @@ -53,7 +53,7 @@ public void test() { .getEntityDescriptor( AnotherEntity.class ), sessionFactory ); - assertFalse( anEntityCacheKey.equals( anotherEntityCacheKey ) ); + assertNotEquals( anEntityCacheKey, anotherEntityCacheKey ); } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/caching/mocked/NaturalIdCacheKeyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/caching/mocked/NaturalIdCacheKeyTest.java index e090c8e6702b..37c5a3a54b18 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/caching/mocked/NaturalIdCacheKeyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/caching/mocked/NaturalIdCacheKeyTest.java @@ -4,11 +4,6 @@ */ package org.hibernate.orm.test.caching.mocked; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; - import org.hibernate.cache.internal.DefaultCacheKeysFactory; import org.hibernate.cache.internal.NaturalIdCacheKey; import org.hibernate.engine.spi.SessionFactoryImplementor; @@ -16,11 +11,15 @@ import org.hibernate.metamodel.mapping.NaturalIdMapping; import org.hibernate.metamodel.spi.RuntimeMetamodelsImplementor; import org.hibernate.persister.entity.EntityPersister; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -56,12 +55,12 @@ public void testSerializationRoundTrip() throws Exception { final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); final NaturalIdCacheKey keyClone = (NaturalIdCacheKey) ois.readObject(); - assertEquals(key, keyClone); - assertEquals(key.hashCode(), keyClone.hashCode()); - assertEquals(key.toString(), keyClone.toString()); - assertEquals(key.getEntityName(), keyClone.getEntityName()); + assertEquals( key, keyClone ); + assertEquals( key.hashCode(), keyClone.hashCode() ); + assertEquals( key.toString(), keyClone.toString() ); + assertEquals( key.getEntityName(), keyClone.getEntityName() ); assertArrayEquals( (Object[]) key.getNaturalIdValues(), (Object[]) keyClone.getNaturalIdValues() ); - assertEquals(key.getTenantId(), keyClone.getTenantId()); + assertEquals( key.getTenantId(), keyClone.getTenantId() ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/caching/mocked/ReadWriteCacheTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/caching/mocked/ReadWriteCacheTest.java index d272c49bb4b4..b85be64ce191 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/caching/mocked/ReadWriteCacheTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/caching/mocked/ReadWriteCacheTest.java @@ -4,79 +4,96 @@ */ package org.hibernate.orm.test.caching.mocked; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Consumer; import jakarta.persistence.Cacheable; import jakarta.persistence.Entity; import jakarta.persistence.Id; - import org.hibernate.Interceptor; import org.hibernate.Session; +import org.hibernate.SessionFactoryObserver; import org.hibernate.Transaction; import org.hibernate.annotations.CacheConcurrencyStrategy; +import org.hibernate.boot.SessionFactoryBuilder; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Configuration; - -import org.hibernate.dialect.CockroachDialect; import org.hibernate.community.dialect.DerbyDialect; +import org.hibernate.dialect.CockroachDialect; import org.hibernate.dialect.HSQLDialect; import org.hibernate.dialect.SybaseASEDialect; - import org.hibernate.testing.SkipForDialect; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Consumer; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Frank Doherty */ -public class ReadWriteCacheTest extends BaseCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + ReadWriteCacheTest.Book.class + } +) +@ServiceRegistry( + settings = { + @Setting(name = AvailableSettings.DEFAULT_CACHE_CONCURRENCY_STRATEGY, value = "read-write"), + @Setting(name = AvailableSettings.JAKARTA_SHARED_CACHE_MODE, value = "ALL"), + } +) +@SessionFactory( + sessionFactoryConfigurer = ReadWriteCacheTest.Configurer.class +) +public class ReadWriteCacheTest { private static final String ORIGINAL_TITLE = "Original Title"; private static final String UPDATED_TITLE = "Updated Title"; - private long bookId; - private CountDownLatch endLatch; - private AtomicBoolean interceptTransaction; - - @Override - public void buildSessionFactory() { - buildSessionFactory( getCacheConfig() ); - } + private static long bookId; + private static CountDownLatch endLatch = new CountDownLatch( 1 ); + private static AtomicBoolean interceptTransaction; - @Before + @BeforeEach public void init() { endLatch = new CountDownLatch( 1 ); interceptTransaction = new AtomicBoolean(); } - @Override - public void rebuildSessionFactory() { - rebuildSessionFactory( getCacheConfig() ); + @AfterEach + void tearDown(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); + scope.getSessionFactory().getCache().evictAll(); } @Test - @SkipForDialect(value = CockroachDialect.class, comment = "CockroachDB uses SERIALIZABLE isolation, and does not support this") - @SkipForDialect(value = HSQLDialect.class, comment = "HSQLDB seems to block on acquiring a SHARE lock when a different TX upgraded a SHARE to EXCLUSIVE lock, maybe the upgrade caused a table lock?") - @SkipForDialect(value = DerbyDialect.class, comment = "HSQLDB seems to block on acquiring a SHARE lock when a different TX upgraded a SHARE to EXCLUSIVE lock, maybe the upgrade caused a table lock?") - @SkipForDialect(value = SybaseASEDialect.class, comment = "Sybase seems to block on acquiring a SHARE lock when a different TX upgraded a SHARE to EXCLUSIVE lock, maybe the upgrade caused a table lock?") - public void testDelete() throws InterruptedException { + @SkipForDialect(value = CockroachDialect.class, + comment = "CockroachDB uses SERIALIZABLE isolation, and does not support this") + @SkipForDialect(value = HSQLDialect.class, + comment = "HSQLDB seems to block on acquiring a SHARE lock when a different TX upgraded a SHARE to EXCLUSIVE lock, maybe the upgrade caused a table lock?") + @SkipForDialect(value = DerbyDialect.class, + comment = "HSQLDB seems to block on acquiring a SHARE lock when a different TX upgraded a SHARE to EXCLUSIVE lock, maybe the upgrade caused a table lock?") + @SkipForDialect(value = SybaseASEDialect.class, + comment = "Sybase seems to block on acquiring a SHARE lock when a different TX upgraded a SHARE to EXCLUSIVE lock, maybe the upgrade caused a table lock?") + public void testDelete(SessionFactoryScope scope) throws InterruptedException { bookId = 1L; - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { createBook( bookId, session ); } ); - doInHibernate( this::sessionFactory, session -> { - log.info( "Delete Book" ); + scope.inTransaction( session -> { Book book = session.get( Book.class, bookId ); session.remove( book ); interceptTransaction.set( true ); @@ -85,22 +102,21 @@ public void testDelete() throws InterruptedException { endLatch.await(); interceptTransaction.set( false ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { assertBookNotFound( bookId, session ); } ); } @Test @JiraKey(value = "HHH-13792") - public void testDeleteHQL() throws InterruptedException { + public void testDeleteHQL(SessionFactoryScope scope) throws InterruptedException { bookId = 2L; - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { createBook( bookId, session ); } ); - doInHibernate( this::sessionFactory, session -> { - log.info( "Delete Book using HQL" ); + scope.inTransaction( session -> { int numRows = session.createQuery( "delete from Book where id = :id" ) .setParameter( "id", bookId ) .executeUpdate(); @@ -111,22 +127,21 @@ public void testDeleteHQL() throws InterruptedException { endLatch.await(); interceptTransaction.set( false ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { assertBookNotFound( bookId, session ); } ); } @Test @JiraKey(value = "HHH-13792") - public void testDeleteNativeQuery() throws InterruptedException { + public void testDeleteNativeQuery(SessionFactoryScope scope) throws InterruptedException { bookId = 3L; - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { createBook( bookId, session ); } ); - doInHibernate( this::sessionFactory, session -> { - log.info( "Delete Book using NativeQuery" ); + scope.inTransaction( session -> { int numRows = session.createNativeQuery( "delete from Book where id = :id" ) .setParameter( "id", bookId ) .addSynchronizedEntityClass( Book.class ) @@ -138,25 +153,28 @@ public void testDeleteNativeQuery() throws InterruptedException { endLatch.await(); interceptTransaction.set( false ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { assertBookNotFound( bookId, session ); } ); } @Test - @SkipForDialect(value = CockroachDialect.class, comment = "CockroachDB uses SERIALIZABLE isolation, and does not support this") - @SkipForDialect(value = HSQLDialect.class, comment = "HSQLDB seems to block on acquiring a SHARE lock when a different TX upgraded a SHARE to EXCLUSIVE lock, maybe the upgrade caused a table lock?") - @SkipForDialect(value = DerbyDialect.class, comment = "HSQLDB seems to block on acquiring a SHARE lock when a different TX upgraded a SHARE to EXCLUSIVE lock, maybe the upgrade caused a table lock?") - @SkipForDialect(value = SybaseASEDialect.class, comment = "Sybase seems to block on acquiring a SHARE lock when a different TX upgraded a SHARE to EXCLUSIVE lock, maybe the upgrade caused a table lock?") - public void testUpdate() throws InterruptedException { + @SkipForDialect(value = CockroachDialect.class, + comment = "CockroachDB uses SERIALIZABLE isolation, and does not support this") + @SkipForDialect(value = HSQLDialect.class, + comment = "HSQLDB seems to block on acquiring a SHARE lock when a different TX upgraded a SHARE to EXCLUSIVE lock, maybe the upgrade caused a table lock?") + @SkipForDialect(value = DerbyDialect.class, + comment = "HSQLDB seems to block on acquiring a SHARE lock when a different TX upgraded a SHARE to EXCLUSIVE lock, maybe the upgrade caused a table lock?") + @SkipForDialect(value = SybaseASEDialect.class, + comment = "Sybase seems to block on acquiring a SHARE lock when a different TX upgraded a SHARE to EXCLUSIVE lock, maybe the upgrade caused a table lock?") + public void testUpdate(SessionFactoryScope scope) throws InterruptedException { bookId = 4L; - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { createBook( bookId, session ); } ); - doInHibernate( this::sessionFactory, session -> { - log.info( "Update Book" ); + scope.inTransaction( session -> { Book book = session.get( Book.class, bookId ); book.setTitle( UPDATED_TITLE ); session.persist( book ); @@ -166,22 +184,21 @@ public void testUpdate() throws InterruptedException { endLatch.await(); interceptTransaction.set( false ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { loadBook( bookId, session ); } ); } @Test @JiraKey(value = "HHH-13792") - public void testUpdateHQL() throws InterruptedException { + public void testUpdateHQL(SessionFactoryScope scope) throws InterruptedException { bookId = 5L; - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { createBook( bookId, session ); } ); - doInHibernate( this::sessionFactory, session -> { - log.info( "Update Book using HQL" ); + scope.inTransaction( session -> { int numRows = session.createQuery( "update Book set title = :title where id = :id" ) .setParameter( "title", UPDATED_TITLE ) .setParameter( "id", bookId ) @@ -193,22 +210,21 @@ public void testUpdateHQL() throws InterruptedException { endLatch.await(); interceptTransaction.set( false ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { loadBook( bookId, session ); } ); } @Test @JiraKey(value = "HHH-13792") - public void testUpdateNativeQuery() throws InterruptedException { + public void testUpdateNativeQuery(SessionFactoryScope scope) throws InterruptedException { bookId = 6L; - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { createBook( bookId, session ); } ); - doInHibernate( this::sessionFactory, session -> { - log.info( "Update Book using NativeQuery" ); + scope.inTransaction( session -> { int numRows = session.createNativeQuery( "update Book set title = :title where id = :id" ) .setParameter( "title", UPDATED_TITLE ) .setParameter( "id", bookId ) @@ -221,31 +237,17 @@ public void testUpdateNativeQuery() throws InterruptedException { endLatch.await(); interceptTransaction.set( false ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { loadBook( bookId, session ); } ); } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Book.class, - }; - } - - @Override - protected String getCacheConcurrencyStrategy() { - return "read-write"; - } - private void assertBookNotFound(long bookId, Session session) { - log.info( "Load Book" ); Book book = session.get( Book.class, bookId ); assertNull( book ); } private void createBook(long bookId, Session session) { - log.info( "Create Book" ); Book book = new Book(); book.setId( bookId ); book.setTitle( ORIGINAL_TITLE ); @@ -257,16 +259,15 @@ private Consumer getCacheConfig() { } private void loadBook(long bookId, Session session) { - log.info( "Load Book" ); Book book = session.get( Book.class, bookId ); assertNotNull( book ); - assertEquals( "Found old value", UPDATED_TITLE, book.getTitle() ); + assertEquals( UPDATED_TITLE, book.getTitle(), "Found old value" ); } @Entity(name = "Book") @Cacheable @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - private static final class Book { + static final class Book { @Id private Long id; @@ -294,24 +295,35 @@ public String toString() { } } - private final class TransactionInterceptor implements Interceptor { + public static class Configurer implements Consumer { + + @Override + public void accept(SessionFactoryBuilder sessionFactoryBuilder) { + TransactionInterceptor transactionInterceptor = new TransactionInterceptor(); + sessionFactoryBuilder.addSessionFactoryObservers( transactionInterceptor ); + sessionFactoryBuilder.applyInterceptor( transactionInterceptor ); + } + } + + private static class TransactionInterceptor implements Interceptor, SessionFactoryObserver { + private org.hibernate.SessionFactory factory; + + @Override + public void sessionFactoryCreated(org.hibernate.SessionFactory factory) { + this.factory = factory; + } + @Override public void beforeTransactionCompletion(Transaction tx) { if ( interceptTransaction.get() ) { try { - log.info( "Fetch Book" ); - - executeSync( () -> { - Session session = sessionFactory() - .openSession(); - Book book = session.get( Book.class, bookId ); - assertNotNull( book ); - log.infof( "Fetched %s", book ); - session.close(); - } ); - - assertTrue( sessionFactory().getCache() - .containsEntity( Book.class, bookId ) ); + Session session = factory.openSession(); + Book book = session.get( Book.class, bookId ); + assertNotNull( book ); + session.close(); + + assertTrue( factory.getCache() + .containsEntity( Book.class, bookId ) ); } finally { endLatch.countDown(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cascade/RefreshLazyOneToManyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cascade/RefreshLazyOneToManyTest.java index 5cb312fa6e20..fc83ab6efce3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cascade/RefreshLazyOneToManyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cascade/RefreshLazyOneToManyTest.java @@ -4,11 +4,6 @@ */ package org.hibernate.orm.test.cascade; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertFalse; - -import java.util.List; - import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -20,26 +15,33 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; - import org.hibernate.Hibernate; - -import org.hibernate.testing.FailureExpected; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.FailureExpected; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; -@JiraKey(value = "HHH-12867") -public class RefreshLazyOneToManyTest extends BaseCoreFunctionalTestCase { +import java.util.List; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ Invoice.class, Tax.class, Line.class }; - } +import static org.junit.jupiter.api.Assertions.assertFalse; + +@JiraKey(value = "HHH-12867") +@DomainModel( + annotatedClasses = { + RefreshLazyOneToManyTest.Invoice.class, + RefreshLazyOneToManyTest.Tax.class, + RefreshLazyOneToManyTest.Line.class + } +) +@SessionFactory +public class RefreshLazyOneToManyTest { @Test - @FailureExpected( jiraKey = "HHH-12867") - public void testRefreshCascade() { - doInHibernate( this::sessionFactory, session -> { + @FailureExpected(jiraKey = "HHH-12867") + public void testRefreshCascade(SessionFactoryScope scope) { + scope.inTransaction( session -> { Invoice invoice = new Invoice( "An invoice for John Smith" ); session.persist( invoice ); @@ -47,20 +49,20 @@ public void testRefreshCascade() { session.persist( new Tax( "21%", invoice ) ); } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { Invoice invoice = session.get( Invoice.class, 1 ); - assertFalse( "Taxes should not be initialized before refresh", - Hibernate.isInitialized( invoice.getTaxes() ) ); - assertFalse( "Lines should not be initialized before refresh", - Hibernate.isInitialized( invoice.getLines() ) ); + assertFalse( Hibernate.isInitialized( invoice.getTaxes() ), + "Taxes should not be initialized before refresh" ); + assertFalse( Hibernate.isInitialized( invoice.getLines() ), + "Lines should not be initialized before refresh" ); session.refresh( invoice ); - assertFalse( "Taxes should not be initialized after refresh", - Hibernate.isInitialized( invoice.getTaxes() ) ); - assertFalse( "Lines should not be initialized after refresh", - Hibernate.isInitialized( invoice.getLines() ) ); + assertFalse( Hibernate.isInitialized( invoice.getTaxes() ), + "Taxes should not be initialized after refresh" ); + assertFalse( Hibernate.isInitialized( invoice.getLines() ), + "Lines should not be initialized after refresh" ); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/event/MergeContextTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/event/MergeContextTest.java index b7db25a7b09b..05d7ae61edf6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/event/MergeContextTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/event/MergeContextTest.java @@ -9,398 +9,415 @@ import java.util.Iterator; import java.util.Map; import java.util.Set; + import jakarta.persistence.Entity; import jakarta.persistence.Id; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; import org.hibernate.event.spi.MergeContext; import org.hibernate.event.spi.EntityCopyObserver; import org.hibernate.event.spi.EventSource; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * 2011/10/20 Unit test for code added in MergeContext for performance improvement. * * @author Wim Ockerman @ CISCO */ -public class MergeContextTest extends BaseCoreFunctionalTestCase { - private EventSource session = null; - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Simple.class }; - } - - @Before - public void setUp() { - session = (EventSource) openSession(); - } - - @After - public void tearDown() { - session.close(); - session = null; - } +@DomainModel( + annotatedClasses = { + MergeContextTest.Simple.class + } +) +@SessionFactory +public class MergeContextTest { @Test - public void testMergeToManagedEntityFillFollowedByInvertMapping() { - MergeContext cache = new MergeContext( session, new DoNothingEntityCopyObserver() ); + public void testMergeToManagedEntityFillFollowedByInvertMapping(SessionFactoryScope scope) { + scope.inSession( session -> { + MergeContext cache = new MergeContext( (EventSource) session, new DoNothingEntityCopyObserver() ); - Object mergeEntity = new Simple( 1 ); - Object managedEntity = new Simple( 2 ); + Object mergeEntity = new Simple( 1 ); + Object managedEntity = new Simple( 2 ); - cache.put(mergeEntity, managedEntity); + cache.put( mergeEntity, managedEntity ); - checkCacheConsistency( cache, 1 ); + checkCacheConsistency( cache, 1 ); - assertTrue( cache.containsKey( mergeEntity ) ); - assertFalse( cache.containsKey( managedEntity ) ); - assertTrue( cache.containsValue( managedEntity ) ); + assertTrue( cache.containsKey( mergeEntity ) ); + assertFalse( cache.containsKey( managedEntity ) ); + assertTrue( cache.containsValue( managedEntity ) ); - assertTrue( cache.invertMap().containsKey( managedEntity ) ); - assertFalse( cache.invertMap().containsKey( mergeEntity ) ); - assertTrue( cache.invertMap().containsValue( mergeEntity ) ); + assertTrue( cache.invertMap().containsKey( managedEntity ) ); + assertFalse( cache.invertMap().containsKey( mergeEntity ) ); + assertTrue( cache.invertMap().containsValue( mergeEntity ) ); - cache.clear(); + cache.clear(); - checkCacheConsistency( cache, 0 ); + checkCacheConsistency( cache, 0 ); - assertFalse(cache.containsKey(mergeEntity)); - assertFalse(cache.invertMap().containsKey(managedEntity)); + assertFalse( cache.containsKey( mergeEntity ) ); + assertFalse( cache.invertMap().containsKey( managedEntity ) ); + } ); } @Test - public void testMergeToManagedEntityFillFollowedByInvert() { - MergeContext cache = new MergeContext( session, new DoNothingEntityCopyObserver() ); + public void testMergeToManagedEntityFillFollowedByInvert(SessionFactoryScope scope) { + scope.inSession( session -> { + MergeContext cache = new MergeContext( (EventSource) session, new DoNothingEntityCopyObserver() ); - Object mergeEntity = new Simple( 1 ); - Object managedEntity = new Simple( 2 ); + Object mergeEntity = new Simple( 1 ); + Object managedEntity = new Simple( 2 ); - cache.put(mergeEntity, managedEntity); + cache.put( mergeEntity, managedEntity ); - checkCacheConsistency( cache, 1 ); + checkCacheConsistency( cache, 1 ); - assertTrue(cache.containsKey(mergeEntity)); - assertFalse( cache.containsKey( managedEntity ) ); + assertTrue( cache.containsKey( mergeEntity ) ); + assertFalse( cache.containsKey( managedEntity ) ); - assertTrue( cache.invertMap().containsKey( managedEntity ) ); - assertFalse( cache.invertMap().containsKey( mergeEntity ) ); + assertTrue( cache.invertMap().containsKey( managedEntity ) ); + assertFalse( cache.invertMap().containsKey( mergeEntity ) ); + } ); } @Test - public void testMergeToManagedEntityFillFollowedByInvertUsingPutAll() { - MergeContext cache = new MergeContext( session, new DoNothingEntityCopyObserver() ); - - Map input = new HashMap(); - Object mergeEntity1 = new Simple( 1 ); - // - Object managedEntity1 = 1; - input.put(mergeEntity1, managedEntity1); - Object mergeEntity2 = new Simple( 3 ); - Object managedEntity2 = 2; - input.put(mergeEntity2, managedEntity2); - cache.putAll(input); - - checkCacheConsistency( cache, 2 ); - - assertTrue(cache.containsKey(mergeEntity1)); - assertFalse(cache.containsKey(managedEntity1)); - assertTrue(cache.containsKey(mergeEntity2)); - assertFalse(cache.containsKey(managedEntity2)); - - assertTrue(cache.invertMap().containsKey(managedEntity1)); - assertFalse(cache.invertMap().containsKey(mergeEntity1)); - - assertTrue(cache.invertMap().containsKey(managedEntity2)); - assertFalse(cache.invertMap().containsKey(mergeEntity2)); + public void testMergeToManagedEntityFillFollowedByInvertUsingPutAll(SessionFactoryScope scope) { + scope.inSession( session -> { + MergeContext cache = new MergeContext( (EventSource) session, new DoNothingEntityCopyObserver() ); + + Map input = new HashMap(); + Object mergeEntity1 = new Simple( 1 ); + // + Object managedEntity1 = 1; + input.put( mergeEntity1, managedEntity1 ); + Object mergeEntity2 = new Simple( 3 ); + Object managedEntity2 = 2; + input.put( mergeEntity2, managedEntity2 ); + cache.putAll( input ); + + checkCacheConsistency( cache, 2 ); + + assertTrue( cache.containsKey( mergeEntity1 ) ); + assertFalse( cache.containsKey( managedEntity1 ) ); + assertTrue( cache.containsKey( mergeEntity2 ) ); + assertFalse( cache.containsKey( managedEntity2 ) ); + + assertTrue( cache.invertMap().containsKey( managedEntity1 ) ); + assertFalse( cache.invertMap().containsKey( mergeEntity1 ) ); + + assertTrue( cache.invertMap().containsKey( managedEntity2 ) ); + assertFalse( cache.invertMap().containsKey( mergeEntity2 ) ); + } ); } @Test - public void testMergeToManagedEntityFillFollowedByInvertUsingPutWithSetOperatedOnArg() { - MergeContext cache = new MergeContext( session, new DoNothingEntityCopyObserver() ); + public void testMergeToManagedEntityFillFollowedByInvertUsingPutWithSetOperatedOnArg(SessionFactoryScope scope) { + scope.inSession( session -> { + MergeContext cache = new MergeContext( (EventSource) session, new DoNothingEntityCopyObserver() ); - Object mergeEntity = new Simple( 1 ); - Object managedEntity = new Simple( 2 ); + Object mergeEntity = new Simple( 1 ); + Object managedEntity = new Simple( 2 ); - cache.put(mergeEntity, managedEntity, true); + cache.put( mergeEntity, managedEntity, true ); - checkCacheConsistency( cache, 1 ); + checkCacheConsistency( cache, 1 ); - assertTrue(cache.containsKey(mergeEntity)); - assertFalse( cache.containsKey( managedEntity ) ); + assertTrue( cache.containsKey( mergeEntity ) ); + assertFalse( cache.containsKey( managedEntity ) ); - assertTrue( cache.invertMap().containsKey( managedEntity ) ); - assertFalse( cache.invertMap().containsKey( mergeEntity ) ); + assertTrue( cache.invertMap().containsKey( managedEntity ) ); + assertFalse( cache.invertMap().containsKey( mergeEntity ) ); - cache.clear(); + cache.clear(); - checkCacheConsistency( cache, 0 ); + checkCacheConsistency( cache, 0 ); - cache.put(mergeEntity, managedEntity, false); - assertFalse( cache.isOperatedOn( mergeEntity ) ); + cache.put( mergeEntity, managedEntity, false ); + assertFalse( cache.isOperatedOn( mergeEntity ) ); - checkCacheConsistency( cache, 1 ); + checkCacheConsistency( cache, 1 ); - assertTrue(cache.containsKey(mergeEntity)); - assertFalse(cache.containsKey(managedEntity)); + assertTrue( cache.containsKey( mergeEntity ) ); + assertFalse( cache.containsKey( managedEntity ) ); + } ); } @Test - public void testMergeToManagedEntityFillFollowedByIterateEntrySet() { - MergeContext cache = new MergeContext( session, new DoNothingEntityCopyObserver() ); + public void testMergeToManagedEntityFillFollowedByIterateEntrySet(SessionFactoryScope scope) { + scope.inSession( session -> { + MergeContext cache = new MergeContext( (EventSource) session, new DoNothingEntityCopyObserver() ); - Object mergeEntity = new Simple( 1 ); - Object managedEntity = new Simple( 2 ); + Object mergeEntity = new Simple( 1 ); + Object managedEntity = new Simple( 2 ); - cache.put( mergeEntity, managedEntity, true ); + cache.put( mergeEntity, managedEntity, true ); - checkCacheConsistency( cache, 1 ); - - Iterator it = cache.entrySet().iterator(); - assertTrue( it.hasNext() ); - Map.Entry entry = ( Map.Entry ) it.next(); - assertSame( mergeEntity, entry.getKey() ); - assertSame( managedEntity, entry.getValue() ); - assertFalse( it.hasNext() ); + checkCacheConsistency( cache, 1 ); + var it = cache.entrySet().iterator(); + assertTrue( it.hasNext() ); + var entry = it.next(); + assertSame( mergeEntity, entry.getKey() ); + assertSame( managedEntity, entry.getValue() ); + assertFalse( it.hasNext() ); + } ); } @Test - public void testMergeToManagedEntityFillFollowedByModifyEntrySet() { - MergeContext cache = new MergeContext( session, new DoNothingEntityCopyObserver() ); - - Object mergeEntity = new Simple( 1 ); - Object managedEntity = new Simple( 2 ); + public void testMergeToManagedEntityFillFollowedByModifyEntrySet(SessionFactoryScope scope) { + scope.inSession( session -> { + MergeContext cache = new MergeContext( (EventSource) session, new DoNothingEntityCopyObserver() ); - cache.put( mergeEntity, managedEntity, true ); + Object mergeEntity = new Simple( 1 ); + Object managedEntity = new Simple( 2 ); - Iterator it = cache.entrySet().iterator(); - try { - it.remove(); - fail( "should have thrown UnsupportedOperationException" ); - } - catch ( UnsupportedOperationException ex ) { - // expected - } - - Map.Entry entry = (Map.Entry) cache.entrySet().iterator().next(); - try { - cache.entrySet().remove( entry ); - fail( "should have thrown UnsupportedOperationException" ); - } - catch ( UnsupportedOperationException ex ) { - // expected - } + cache.put( mergeEntity, managedEntity, true ); - Map.Entry anotherEntry = new Map.Entry() { - private Object key = new Simple( 3 ); - private Object value = 4; - @Override - public Object getKey() { - return key; + var it = cache.entrySet().iterator(); + try { + it.remove(); + fail( "should have thrown UnsupportedOperationException" ); } - - @Override - public Object getValue() { - return value; + catch (UnsupportedOperationException ex) { + // expected } - @Override - public Object setValue(Object value) { - Object oldValue = this.value; - this.value = value; - return oldValue; + var entry = cache.entrySet().iterator().next(); + try { + cache.entrySet().remove( entry ); + fail( "should have thrown UnsupportedOperationException" ); + } + catch (UnsupportedOperationException ex) { + // expected } - }; - try { - cache.entrySet().add( anotherEntry ); - fail( "should have thrown UnsupportedOperationException" ); - } - catch ( UnsupportedOperationException ex ) { - // expected - } + Map.Entry anotherEntry = new Map.Entry() { + private Object key = new Simple( 3 ); + private Object value = 4; + + @Override + public Object getKey() { + return key; + } + + @Override + public Object getValue() { + return value; + } + + @Override + public Object setValue(Object value) { + Object oldValue = this.value; + this.value = value; + return oldValue; + } + }; + try { + cache.entrySet().add( anotherEntry ); + fail( "should have thrown UnsupportedOperationException" ); + } + catch (UnsupportedOperationException ex) { + // expected + } + } ); } @Test - public void testMergeToManagedEntityFillFollowedByModifyKeys() { - MergeContext cache = new MergeContext( session, new DoNothingEntityCopyObserver() ); + public void testMergeToManagedEntityFillFollowedByModifyKeys(SessionFactoryScope scope) { + scope.inSession( session -> { + MergeContext cache = new MergeContext( (EventSource) session, new DoNothingEntityCopyObserver() ); - Object mergeEntity = new Simple( 1 ); - Object managedEntity = new Simple( 2 ); + Object mergeEntity = new Simple( 1 ); + Object managedEntity = new Simple( 2 ); - cache.put( mergeEntity, managedEntity, true ); + cache.put( mergeEntity, managedEntity, true ); - Iterator it = cache.keySet().iterator(); - try { - it.remove(); - fail( "should have thrown UnsupportedOperationException" ); - } - catch ( UnsupportedOperationException ex ) { - // expected - } + Iterator it = cache.keySet().iterator(); + try { + it.remove(); + fail( "should have thrown UnsupportedOperationException" ); + } + catch (UnsupportedOperationException ex) { + // expected + } - try { - cache.keySet().remove( mergeEntity ); - fail( "should have thrown UnsupportedOperationException" ); - } - catch ( UnsupportedOperationException ex ) { - // expected - } + try { + cache.keySet().remove( mergeEntity ); + fail( "should have thrown UnsupportedOperationException" ); + } + catch (UnsupportedOperationException ex) { + // expected + } - Object newmanagedEntity = new Simple( 3 ); - try { - cache.keySet().add( newmanagedEntity ); - fail( "should have thrown UnsupportedOperationException" ); - } - catch ( UnsupportedOperationException ex ) { - // expected - } + Object newmanagedEntity = new Simple( 3 ); + try { + cache.keySet().add( newmanagedEntity ); + fail( "should have thrown UnsupportedOperationException" ); + } + catch (UnsupportedOperationException ex) { + // expected + } + } ); } @Test - public void testMergeToManagedEntityFillFollowedByModifyValues() { - MergeContext cache = new MergeContext( session, new DoNothingEntityCopyObserver() ); + public void testMergeToManagedEntityFillFollowedByModifyValues(SessionFactoryScope scope) { + scope.inSession( session -> { + MergeContext cache = new MergeContext( (EventSource) session, new DoNothingEntityCopyObserver() ); - Object mergeEntity = new Simple( 1 ); - Object managedEntity = new Simple( 2 ); + Object mergeEntity = new Simple( 1 ); + Object managedEntity = new Simple( 2 ); - cache.put( mergeEntity, managedEntity, true ); + cache.put( mergeEntity, managedEntity, true ); - Iterator it = cache.values().iterator(); - try { - it.remove(); - fail( "should have thrown UnsupportedOperationException" ); - } - catch ( UnsupportedOperationException ex ) { - // expected - } + Iterator it = cache.values().iterator(); + try { + it.remove(); + fail( "should have thrown UnsupportedOperationException" ); + } + catch (UnsupportedOperationException ex) { + // expected + } - try { - cache.values().remove( managedEntity ); - fail( "should have thrown UnsupportedOperationException" ); - } - catch ( UnsupportedOperationException ex ) { - // expected - } + try { + cache.values().remove( managedEntity ); + fail( "should have thrown UnsupportedOperationException" ); + } + catch (UnsupportedOperationException ex) { + // expected + } - Object newmanagedEntity = new Simple( 3 ); - try { - cache.values().add( newmanagedEntity ); - fail( "should have thrown UnsupportedOperationException" ); - } - catch ( UnsupportedOperationException ex ) { - // expected - } + Object newmanagedEntity = new Simple( 3 ); + try { + cache.values().add( newmanagedEntity ); + fail( "should have thrown UnsupportedOperationException" ); + } + catch (UnsupportedOperationException ex) { + // expected + } + } ); } @Test - public void testMergeToManagedEntityFillFollowedByModifyKeyOfEntrySetElement() { - MergeContext cache = new MergeContext( session, new DoNothingEntityCopyObserver() ); + public void testMergeToManagedEntityFillFollowedByModifyKeyOfEntrySetElement(SessionFactoryScope scope) { + scope.inSession( session -> { + MergeContext cache = new MergeContext( (EventSource) session, new DoNothingEntityCopyObserver() ); - Simple mergeEntity = new Simple( 1 ); - Simple managedEntity = new Simple( 0 ); - cache.put(mergeEntity, managedEntity, true); + Simple mergeEntity = new Simple( 1 ); + Simple managedEntity = new Simple( 0 ); + cache.put( mergeEntity, managedEntity, true ); - Map.Entry entry = (Map.Entry) cache.entrySet().iterator().next(); - ( ( Simple ) entry.getKey() ).setValue( 2 ); - assertEquals( 2, mergeEntity.getValue() ); + var entry = cache.entrySet().iterator().next(); + ((Simple) entry.getKey()).setValue( 2 ); + assertEquals( 2, mergeEntity.getValue() ); - checkCacheConsistency( cache, 1 ); + checkCacheConsistency( cache, 1 ); - entry = (Map.Entry) cache.entrySet().iterator().next(); - assertSame( mergeEntity, entry.getKey() ); - assertSame( managedEntity, entry.getValue() ); + entry = cache.entrySet().iterator().next(); + assertSame( mergeEntity, entry.getKey() ); + assertSame( managedEntity, entry.getValue() ); + } ); } @Test - public void testMergeToManagedEntityFillFollowedByModifyValueOfEntrySetElement() { - MergeContext cache = new MergeContext( session, new DoNothingEntityCopyObserver() ); + public void testMergeToManagedEntityFillFollowedByModifyValueOfEntrySetElement(SessionFactoryScope scope) { + scope.inSession( session -> { + MergeContext cache = new MergeContext( (EventSource) session, new DoNothingEntityCopyObserver() ); - Simple mergeEntity = new Simple( 1 ); - Simple managedEntity = new Simple( 0 ); - cache.put(mergeEntity, managedEntity, true); + Simple mergeEntity = new Simple( 1 ); + Simple managedEntity = new Simple( 0 ); + cache.put( mergeEntity, managedEntity, true ); - Map.Entry entry = (Map.Entry) cache.entrySet().iterator().next(); - ( ( Simple ) entry.getValue() ).setValue( 2 ); - assertEquals( 2, managedEntity.getValue() ); + var entry = cache.entrySet().iterator().next(); + ((Simple) entry.getValue()).setValue( 2 ); + assertEquals( 2, managedEntity.getValue() ); - checkCacheConsistency( cache, 1 ); + checkCacheConsistency( cache, 1 ); - entry = (Map.Entry) cache.entrySet().iterator().next(); - assertSame( mergeEntity, entry.getKey() ); - assertSame( managedEntity, entry.getValue() ); + entry = cache.entrySet().iterator().next(); + assertSame( mergeEntity, entry.getKey() ); + assertSame( managedEntity, entry.getValue() ); + } ); } @Test - public void testReplaceManagedEntity() { - MergeContext cache = new MergeContext( session, new DoNothingEntityCopyObserver() ); + public void testReplaceManagedEntity(SessionFactoryScope scope) { + scope.inSession( session -> { + MergeContext cache = new MergeContext( (EventSource) session, new DoNothingEntityCopyObserver() ); - Simple mergeEntity = new Simple( 1 ); - Simple managedEntity = new Simple( 0 ); - cache.put(mergeEntity, managedEntity); + Simple mergeEntity = new Simple( 1 ); + Simple managedEntity = new Simple( 0 ); + cache.put( mergeEntity, managedEntity ); - Simple managedEntityNew = new Simple( 0 ); - try { - cache.put( mergeEntity, managedEntityNew ); - } - catch( IllegalArgumentException ex) { - // expected; cannot replace the managed entity result for a particular merge entity. - } + Simple managedEntityNew = new Simple( 0 ); + try { + cache.put( mergeEntity, managedEntityNew ); + } + catch (IllegalArgumentException ex) { + // expected; cannot replace the managed entity result for a particular merge entity. + } + } ); } @Test - public void testManagedEntityAssociatedWithNewAndExistingMergeEntities() { - MergeContext cache = new MergeContext( session, new DoNothingEntityCopyObserver() ); - - session.getTransaction().begin(); - Simple mergeEntity = new Simple( 1 ); - Simple managedEntity = new Simple( 0 ); - cache.put(mergeEntity, managedEntity); - cache.put( new Simple( 1 ), managedEntity ); + public void testManagedEntityAssociatedWithNewAndExistingMergeEntities(SessionFactoryScope scope) { + scope.inSession( session -> { + MergeContext cache = new MergeContext( (EventSource) session, new DoNothingEntityCopyObserver() ); + + session.getTransaction().begin(); + Simple mergeEntity = new Simple( 1 ); + Simple managedEntity = new Simple( 0 ); + cache.put( mergeEntity, managedEntity ); + cache.put( new Simple( 1 ), managedEntity ); + } ); } @Test - public void testManagedAssociatedWith2ExistingMergeEntities() { - MergeContext cache = new MergeContext( session, new DoNothingEntityCopyObserver() ); - - session.getTransaction().begin(); - Simple mergeEntity1 = new Simple( 1 ); - session.persist( mergeEntity1 ); - Simple managedEntity1 = new Simple( 1 ); - cache.put( mergeEntity1, managedEntity1 ); - Simple managedEntity2 = new Simple( 2 ); - - try { - cache.put( mergeEntity1, managedEntity2 ); - fail( "should have thrown IllegalArgumentException"); - } - catch( IllegalArgumentException ex ) { - // expected; cannot change managed entity associated with a merge entity - } - finally { - session.getTransaction().rollback(); - } + public void testManagedAssociatedWith2ExistingMergeEntities(SessionFactoryScope scope) { + scope.inSession( session -> { + MergeContext cache = new MergeContext( (EventSource) session, new DoNothingEntityCopyObserver() ); + + session.getTransaction().begin(); + Simple mergeEntity1 = new Simple( 1 ); + session.persist( mergeEntity1 ); + Simple managedEntity1 = new Simple( 1 ); + cache.put( mergeEntity1, managedEntity1 ); + Simple managedEntity2 = new Simple( 2 ); + + try { + cache.put( mergeEntity1, managedEntity2 ); + fail( "should have thrown IllegalArgumentException" ); + } + catch (IllegalArgumentException ex) { + // expected; cannot change managed entity associated with a merge entity + } + finally { + session.getTransaction().rollback(); + } + } ); } @Test - public void testRemoveNonExistingEntity() { - MergeContext cache = new MergeContext( session, new DoNothingEntityCopyObserver() ); - try { - cache.remove( new Simple( 1 ) ); - } - catch (UnsupportedOperationException ex) { - // expected; remove is not supported. - } + public void testRemoveNonExistingEntity(SessionFactoryScope scope) { + scope.inSession( session -> { + MergeContext cache = new MergeContext( (EventSource) session, new DoNothingEntityCopyObserver() ); + try { + cache.remove( new Simple( 1 ) ); + } + catch (UnsupportedOperationException ex) { + // expected; remove is not supported. + } + } ); } private void checkCacheConsistency(MergeContext cache, int expectedSize) { @@ -416,7 +433,7 @@ private void checkCacheConsistency(MergeContext cache, int expectedSize) { assertEquals( expectedSize, invertedMap.size() ); for ( Object entry : cache.entrySet() ) { - Map.Entry mapEntry = ( Map.Entry ) entry; + Map.Entry mapEntry = (Map.Entry) entry; assertSame( cache.get( mapEntry.getKey() ), mapEntry.getValue() ); assertTrue( cacheKeys.contains( mapEntry.getKey() ) ); assertTrue( cacheValues.contains( mapEntry.getValue() ) ); @@ -425,7 +442,7 @@ private void checkCacheConsistency(MergeContext cache, int expectedSize) { } @Entity - private static class Simple { + static class Simple { @Id private int value; @@ -444,8 +461,8 @@ public void setValue(int value) { @Override public String toString() { return "Simple{" + - "value=" + value + - '}'; + "value=" + value + + '}'; } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/event/PreInsertEventListenerVetoBidirectionalTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/event/PreInsertEventListenerVetoBidirectionalTest.java index 012aedbd906b..860073de67ea 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/event/PreInsertEventListenerVetoBidirectionalTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/event/PreInsertEventListenerVetoBidirectionalTest.java @@ -12,42 +12,46 @@ import jakarta.persistence.OneToOne; import org.hibernate.action.internal.EntityActionVetoException; -import org.hibernate.event.service.spi.EventListenerRegistry; import org.hibernate.event.spi.EventType; import org.hibernate.testing.DialectChecks; import org.hibernate.testing.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * @author Chris Cranford */ @RequiresDialectFeature(DialectChecks.SupportsIdentityColumns.class) @JiraKey(value = "HHH-11721") -public class PreInsertEventListenerVetoBidirectionalTest extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Child.class, Parent.class }; - } +@DomainModel( + annotatedClasses = { + PreInsertEventListenerVetoBidirectionalTest.Child.class, + PreInsertEventListenerVetoBidirectionalTest.Parent.class + } +) +@SessionFactory +public class PreInsertEventListenerVetoBidirectionalTest { - @Override - protected void afterSessionFactoryBuilt() { - super.afterSessionFactoryBuilt(); - EventListenerRegistry registry = sessionFactory().getEventListenerRegistry(); - registry.appendListeners( - EventType.PRE_INSERT, - event -> event.getEntity() instanceof Parent - ); + @AfterEach + public void tearDown(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncate(); } - @Test(expected = EntityActionVetoException.class) - public void testVeto() { - doInHibernate( this::sessionFactory, session -> { + @Test + public void testVeto(SessionFactoryScope scope) { + scope.getSessionFactory().getEventListenerRegistry() + .appendListeners( + EventType.PRE_INSERT, + event -> event.getEntity() instanceof Parent + ); + assertThatThrownBy( () -> scope.inTransaction( session -> { Parent parent = new Parent(); parent.setField1( "f1" ); parent.setfield2( "f2" ); @@ -56,9 +60,7 @@ public void testVeto() { parent.setChild( child ); session.persist( parent ); - } ); - - fail( "Should have thrown EntityActionVetoException!" ); + } ) ).isInstanceOf( EntityActionVetoException.class ); } @Entity(name = "Child") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/event/PreInsertEventListenerVetoUnidirectionalTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/event/PreInsertEventListenerVetoUnidirectionalTest.java index 79c18b3fb36a..b993ff0ac9c2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/event/PreInsertEventListenerVetoUnidirectionalTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/event/PreInsertEventListenerVetoUnidirectionalTest.java @@ -12,42 +12,46 @@ import jakarta.persistence.OneToOne; import org.hibernate.action.internal.EntityActionVetoException; -import org.hibernate.event.service.spi.EventListenerRegistry; import org.hibernate.event.spi.EventType; import org.hibernate.testing.DialectChecks; import org.hibernate.testing.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * @author Chris Cranford */ @RequiresDialectFeature(DialectChecks.SupportsIdentityColumns.class) -@JiraKey( value = "HHH-11721" ) -public class PreInsertEventListenerVetoUnidirectionalTest extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Child.class, Parent.class }; - } +@JiraKey(value = "HHH-11721") +@DomainModel( + annotatedClasses = { + PreInsertEventListenerVetoUnidirectionalTest.Child.class, + PreInsertEventListenerVetoUnidirectionalTest.Parent.class + } +) +@SessionFactory +public class PreInsertEventListenerVetoUnidirectionalTest { - @Override - protected void afterSessionFactoryBuilt() { - super.afterSessionFactoryBuilt(); - EventListenerRegistry registry = sessionFactory().getEventListenerRegistry(); - registry.appendListeners( - EventType.PRE_INSERT, - event -> event.getEntity() instanceof Parent - ); + @AfterEach + public void tearDown(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncate(); } - @Test(expected = EntityActionVetoException.class) - public void testVeto() { - doInHibernate( this::sessionFactory, session -> { + @Test + public void testVeto(SessionFactoryScope scope) { + scope.getSessionFactory().getEventListenerRegistry() + .appendListeners( + EventType.PRE_INSERT, + event -> event.getEntity() instanceof Parent + ); + assertThatThrownBy( () -> scope.inTransaction( session -> { Parent parent = new Parent(); parent.setField1( "f1" ); parent.setfield2( "f2" ); @@ -56,9 +60,7 @@ public void testVeto() { child.setParent( parent ); session.persist( child ); - } ); - - fail( "Should have thrown EntityActionVetoException!" ); + } ) ).isInstanceOf( EntityActionVetoException.class ); } @Entity(name = "Child") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/event/SessionEventListenersManagerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/event/SessionEventListenersManagerTest.java index efb290d6d861..b46771a8c7a0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/event/SessionEventListenersManagerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/event/SessionEventListenersManagerTest.java @@ -7,11 +7,10 @@ import org.hibernate.SessionEventListener; import org.hibernate.engine.internal.SessionEventListenerManagerImpl; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; -public class SessionEventListenersManagerTest extends BaseUnitTestCase { +public class SessionEventListenersManagerTest { @Test public void testListenerAppending() { @@ -23,12 +22,12 @@ public void testListenerAppending() { SessionEventListenerManagerImpl l = new SessionEventListenerManagerImpl( a, b ); l.addListener( c, d ); l.dirtyCalculationEnd( true ); - Assert.assertEquals( "abcd", sb.toString() ); + Assertions.assertEquals( "abcd", sb.toString() ); l.dirtyCalculationEnd( true ); - Assert.assertEquals( "abcdabcd", sb.toString() ); + Assertions.assertEquals( "abcdabcd", sb.toString() ); l.addListener( new TestSessionEventListener( sb , 'e' ) ); l.dirtyCalculationEnd( true ); - Assert.assertEquals( "abcdabcdabcde", sb.toString() ); + Assertions.assertEquals( "abcdabcdabcde", sb.toString() ); } @Test @@ -36,10 +35,10 @@ public void testEmptyListenerAppending() { StringBuilder sb = new StringBuilder(); SessionEventListenerManagerImpl l = new SessionEventListenerManagerImpl(); l.dirtyCalculationEnd( true ); - Assert.assertEquals( "", sb.toString() ); + Assertions.assertEquals( "", sb.toString() ); l.addListener( new TestSessionEventListener( sb , 'e' ) ); l.dirtyCalculationEnd( true ); - Assert.assertEquals( "e", sb.toString() ); + Assertions.assertEquals( "e", sb.toString() ); } private static class TestSessionEventListener implements SessionEventListener { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/AbstractCollectionEventTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/AbstractCollectionEventTest.java index 4f7d225c173a..6e652e436c5f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/AbstractCollectionEventTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/AbstractCollectionEventTest.java @@ -4,73 +4,42 @@ */ package org.hibernate.orm.test.event.collection; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -import jakarta.persistence.criteria.CriteriaBuilder; -import jakarta.persistence.criteria.CriteriaQuery; - import org.hibernate.Session; import org.hibernate.Transaction; -import org.hibernate.collection.spi.PersistentSet; import org.hibernate.collection.spi.PersistentCollection; +import org.hibernate.collection.spi.PersistentSet; import org.hibernate.dialect.HANADialect; import org.hibernate.event.spi.AbstractCollectionEvent; -import org.hibernate.testing.SkipForDialect; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import org.hibernate.orm.test.event.collection.association.bidirectional.manytomany.ChildWithBidirectionalManyToMany; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.SkipForDialect; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import java.util.Collection; +import java.util.concurrent.atomic.AtomicReference; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; /** * @author Gail Badner */ -public abstract class AbstractCollectionEventTest extends BaseCoreFunctionalTestCase { +@DomainModel +@SessionFactory +public abstract class AbstractCollectionEventTest { - @Override protected String getBaseForMappings() { return "org/hibernate/orm/test/"; } - @Override - protected void cleanupTest() { - ParentWithCollection dummyParent = createParent( "dummyParent" ); - dummyParent.newChildren( createCollection() ); - Child dummyChild = dummyParent.addChild( "dummyChild" ); - inTransaction( - s -> { - CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); - List children; - if ( s.getFactory().getRuntimeMetamodels() - .getMappingMetamodel() - .findEntityDescriptor( dummyChild.getClass() ) == null ) { - children = Collections.emptyList(); - } - else { - CriteriaQuery childrenCriteria = criteriaBuilder.createQuery( dummyChild.getClass() ); - childrenCriteria.from( dummyChild.getClass() ); - children = s.createQuery( childrenCriteria ).list(); - } - - CriteriaQuery parentsCriteria = criteriaBuilder.createQuery( dummyParent.getClass() ); - parentsCriteria.from( dummyParent.getClass() ); - List parents = s.createQuery( parentsCriteria ).list(); - for ( Iterator it = parents.iterator(); it.hasNext(); ) { - ParentWithCollection parent = ( ParentWithCollection ) it.next(); - parent.clearChildren(); - s.remove( parent ); - } - for ( Iterator it = children.iterator(); it.hasNext(); ) { - s.remove( it.next() ); - } - } - ); + @AfterEach + protected void cleanupTest(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } public abstract ParentWithCollection createParent(String name); @@ -78,153 +47,167 @@ protected void cleanupTest() { public abstract Collection createCollection(); @Test - @SkipForDialect(value = HANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testSaveParentEmptyChildren() { - CollectionListeners listeners = new CollectionListeners( sessionFactory() ); - ParentWithCollection parent = createParentWithNoChildren( "parent" ); + @SkipForDialect(dialectClass = HANADialect.class, + reason = " HANA doesn't support tables consisting of only a single auto-generated column") + public void testSaveParentEmptyChildren(SessionFactoryScope scope) { + CollectionListeners listeners = new CollectionListeners( scope.getSessionFactory() ); + ParentWithCollection parent = createParentWithNoChildren( "parent", scope ); assertEquals( 0, parent.getChildren().size() ); int index = 0; checkResult( listeners, listeners.getPreCollectionRecreateListener(), parent, index++ ); checkResult( listeners, listeners.getPostCollectionRecreateListener(), parent, index++ ); checkNumberOfResults( listeners, index ); listeners.clear(); - Session s = openSession(); - Transaction tx = s.beginTransaction(); - parent = ( ParentWithCollection ) s.get( parent.getClass(), parent.getId() ); - tx.commit(); - s.close(); - assertNotNull( parent.getChildren() ); + var p = scope.fromTransaction( s -> s.get( parent.getClass(), parent.getId() ) ); + assertNotNull( p.getChildren() ); checkNumberOfResults( listeners, 0 ); } @Test - @SkipForDialect(value = HANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testSaveParentOneChild() { - CollectionListeners listeners = new CollectionListeners( sessionFactory() ); - ParentWithCollection parent = createParentWithOneChild( "parent", "child" ); + @SkipForDialect(dialectClass = HANADialect.class, + reason = " HANA doesn't support tables consisting of only a single auto-generated column") + public void testSaveParentOneChild(SessionFactoryScope scope) { + CollectionListeners listeners = new CollectionListeners( scope.getSessionFactory() ); + ParentWithCollection parent = createParentWithOneChild( "parent", "child", scope ); int index = 0; checkResult( listeners, listeners.getPreCollectionRecreateListener(), parent, index++ ); checkResult( listeners, listeners.getPostCollectionRecreateListener(), parent, index++ ); - Child child = ( Child ) parent.getChildren().iterator().next(); + Child child = (Child) parent.getChildren().iterator().next(); if ( child instanceof ChildWithBidirectionalManyToMany ) { - checkResult( listeners, listeners.getPreCollectionRecreateListener(), ( ChildWithBidirectionalManyToMany ) child, index++ ); - checkResult( listeners, listeners.getPostCollectionRecreateListener(), ( ChildWithBidirectionalManyToMany ) child, index++ ); + checkResult( listeners, listeners.getPreCollectionRecreateListener(), + (ChildWithBidirectionalManyToMany) child, index++ ); + checkResult( listeners, listeners.getPostCollectionRecreateListener(), + (ChildWithBidirectionalManyToMany) child, index++ ); } checkNumberOfResults( listeners, index ); } @Test - @SkipForDialect(value = HANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testUpdateParentNullToOneChild() { - CollectionListeners listeners = new CollectionListeners( sessionFactory() ); - ParentWithCollection parent = createParentWithNullChildren( "parent" ); + @SkipForDialect(dialectClass = HANADialect.class, + reason = "HANA doesn't support tables consisting of only a single auto-generated column") + public void testUpdateParentNullToOneChild(SessionFactoryScope scope) { + CollectionListeners listeners = new CollectionListeners( scope.getSessionFactory() ); + ParentWithCollection parent = createParentWithNullChildren( "parent", scope ); listeners.clear(); assertNull( parent.getChildren() ); - Session s = openSession(); - Transaction tx = s.beginTransaction(); - parent = ( ParentWithCollection ) s.get( parent.getClass(), parent.getId() ); - assertNotNull( parent.getChildren() ); - Child newChild = parent.addChild( "new" ); - tx.commit(); - s.close(); + Class parentClass = parent.getClass(); + Long parentId = parent.getId(); + AtomicReference childRef = new AtomicReference<>(); + parent = scope.fromTransaction( s -> { + var p = (ParentWithCollection) s.get( parentClass, parentId ); + assertNotNull( p.getChildren() ); + Child newChild = p.addChild( "new" ); + childRef.set( newChild ); + return p; + } ); + Child newChild = childRef.get(); int index = 0; - if ( ( ( PersistentCollection ) parent.getChildren() ).wasInitialized() ) { + if ( ((PersistentCollection) parent.getChildren()).wasInitialized() ) { checkResult( listeners, listeners.getInitializeCollectionListener(), parent, index++ ); } checkResult( listeners, listeners.getPreCollectionUpdateListener(), parent, index++ ); checkResult( listeners, listeners.getPostCollectionUpdateListener(), parent, index++ ); if ( newChild instanceof ChildWithBidirectionalManyToMany ) { - checkResult( listeners, listeners.getPreCollectionRecreateListener(), ( ChildWithBidirectionalManyToMany ) newChild, index++ ); - checkResult( listeners, listeners.getPostCollectionRecreateListener(), ( ChildWithBidirectionalManyToMany ) newChild, index++ ); + checkResult( listeners, listeners.getPreCollectionRecreateListener(), + (ChildWithBidirectionalManyToMany) newChild, index++ ); + checkResult( listeners, listeners.getPostCollectionRecreateListener(), + (ChildWithBidirectionalManyToMany) newChild, index++ ); } checkNumberOfResults( listeners, index ); } @Test - @SkipForDialect(value = HANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testUpdateParentNoneToOneChild() { - CollectionListeners listeners = new CollectionListeners( sessionFactory() ); - ParentWithCollection parent = createParentWithNoChildren( "parent" ); + @SkipForDialect(dialectClass = HANADialect.class, + reason = " HANA doesn't support tables consisting of only a single auto-generated column") + public void testUpdateParentNoneToOneChild(SessionFactoryScope scope) { + CollectionListeners listeners = new CollectionListeners( scope.getSessionFactory() ); + ParentWithCollection parent = createParentWithNoChildren( "parent", scope ); listeners.clear(); assertEquals( 0, parent.getChildren().size() ); - Session s = openSession(); + Session s = scope.getSessionFactory().openSession(); Transaction tx = s.beginTransaction(); - parent = ( ParentWithCollection ) s.get( parent.getClass(), parent.getId() ); + parent = (ParentWithCollection) s.get( parent.getClass(), parent.getId() ); Child newChild = parent.addChild( "new" ); tx.commit(); s.close(); int index = 0; - if ( ( ( PersistentCollection ) parent.getChildren() ).wasInitialized() ) { + if ( ((PersistentCollection) parent.getChildren()).wasInitialized() ) { checkResult( listeners, listeners.getInitializeCollectionListener(), parent, index++ ); } checkResult( listeners, listeners.getPreCollectionUpdateListener(), parent, index++ ); checkResult( listeners, listeners.getPostCollectionUpdateListener(), parent, index++ ); if ( newChild instanceof ChildWithBidirectionalManyToMany ) { - checkResult( listeners, listeners.getPreCollectionRecreateListener(), ( ChildWithBidirectionalManyToMany ) newChild, index++ ); - checkResult( listeners, listeners.getPostCollectionRecreateListener(), ( ChildWithBidirectionalManyToMany ) newChild, index++ ); + checkResult( listeners, listeners.getPreCollectionRecreateListener(), + (ChildWithBidirectionalManyToMany) newChild, index++ ); + checkResult( listeners, listeners.getPostCollectionRecreateListener(), + (ChildWithBidirectionalManyToMany) newChild, index++ ); } checkNumberOfResults( listeners, index ); } @Test - @SkipForDialect(value = HANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testUpdateParentOneToTwoChildren() { - CollectionListeners listeners = new CollectionListeners( sessionFactory() ); - ParentWithCollection parent = createParentWithOneChild( "parent", "child" ); + @SkipForDialect(dialectClass = HANADialect.class, + reason = "HANA doesn't support tables consisting of only a single auto-generated column") + public void testUpdateParentOneToTwoChildren(SessionFactoryScope scope) { + CollectionListeners listeners = new CollectionListeners( scope.getSessionFactory() ); + ParentWithCollection parent = createParentWithOneChild( "parent", "child", scope ); assertEquals( 1, parent.getChildren().size() ); listeners.clear(); - Session s = openSession(); + Session s = scope.getSessionFactory().openSession(); Transaction tx = s.beginTransaction(); - parent = ( ParentWithCollection ) s.get( parent.getClass(), parent.getId() ); + parent = (ParentWithCollection) s.get( parent.getClass(), parent.getId() ); Child newChild = parent.addChild( "new2" ); tx.commit(); s.close(); int index = 0; - if ( ( ( PersistentCollection ) parent.getChildren() ).wasInitialized() ) { + if ( ((PersistentCollection) parent.getChildren()).wasInitialized() ) { checkResult( listeners, listeners.getInitializeCollectionListener(), parent, index++ ); } checkResult( listeners, listeners.getPreCollectionUpdateListener(), parent, index++ ); checkResult( listeners, listeners.getPostCollectionUpdateListener(), parent, index++ ); if ( newChild instanceof ChildWithBidirectionalManyToMany ) { - checkResult( listeners, listeners.getPreCollectionRecreateListener(), ( ChildWithBidirectionalManyToMany ) newChild, index++ ); - checkResult( listeners, listeners.getPostCollectionRecreateListener(), ( ChildWithBidirectionalManyToMany ) newChild, index++ ); + checkResult( listeners, listeners.getPreCollectionRecreateListener(), + (ChildWithBidirectionalManyToMany) newChild, index++ ); + checkResult( listeners, listeners.getPostCollectionRecreateListener(), + (ChildWithBidirectionalManyToMany) newChild, index++ ); } checkNumberOfResults( listeners, index ); } @Test - @SkipForDialect(value = HANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testUpdateParentOneToTwoSameChildren() { - CollectionListeners listeners = new CollectionListeners( sessionFactory() ); - ParentWithCollection parent = createParentWithOneChild( "parent", "child" ); - Child child = ( Child ) parent.getChildren().iterator().next(); + @SkipForDialect(dialectClass = HANADialect.class, + reason = " HANA doesn't support tables consisting of only a single auto-generated column") + public void testUpdateParentOneToTwoSameChildren(SessionFactoryScope scope) { + CollectionListeners listeners = new CollectionListeners( scope.getSessionFactory() ); + ParentWithCollection parent = createParentWithOneChild( "parent", "child", scope ); + Child child = (Child) parent.getChildren().iterator().next(); assertEquals( 1, parent.getChildren().size() ); listeners.clear(); - Session s = openSession(); + Session s = scope.getSessionFactory().openSession(); Transaction tx = s.beginTransaction(); - parent = ( ParentWithCollection ) s.get( parent.getClass(), parent.getId() ); + parent = (ParentWithCollection) s.get( parent.getClass(), parent.getId() ); if ( child instanceof Entity ) { - child = ( Child ) s.get( child.getClass(), ( ( Entity ) child ).getId() ); + child = (Child) s.get( child.getClass(), ((Entity) child).getId() ); } parent.addChild( child ); tx.commit(); s.close(); int index = 0; - if ( ( ( PersistentCollection ) parent.getChildren() ).wasInitialized() ) { + if ( ((PersistentCollection) parent.getChildren()).wasInitialized() ) { checkResult( listeners, listeners.getInitializeCollectionListener(), parent, index++ ); } ChildWithBidirectionalManyToMany childWithManyToMany = null; if ( child instanceof ChildWithBidirectionalManyToMany ) { - childWithManyToMany = ( ChildWithBidirectionalManyToMany ) child; - if ( ( ( PersistentCollection ) childWithManyToMany.getParents() ).wasInitialized() ) { + childWithManyToMany = (ChildWithBidirectionalManyToMany) child; + if ( ((PersistentCollection) childWithManyToMany.getParents()).wasInitialized() ) { checkResult( listeners, listeners.getInitializeCollectionListener(), childWithManyToMany, index++ ); } } - if ( !( parent.getChildren() instanceof PersistentSet ) ) { + if ( !(parent.getChildren() instanceof PersistentSet) ) { checkResult( listeners, listeners.getPreCollectionUpdateListener(), parent, index++ ); checkResult( listeners, listeners.getPostCollectionUpdateListener(), parent, index++ ); } - if ( childWithManyToMany != null && !( childWithManyToMany.getParents() instanceof PersistentSet ) ) { + if ( childWithManyToMany != null && !(childWithManyToMany.getParents() instanceof PersistentSet) ) { checkResult( listeners, listeners.getPreCollectionUpdateListener(), childWithManyToMany, index++ ); checkResult( listeners, listeners.getPostCollectionUpdateListener(), childWithManyToMany, index++ ); } @@ -232,29 +215,32 @@ public void testUpdateParentOneToTwoSameChildren() { } @Test - @SkipForDialect(value = HANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testUpdateParentNullToOneChildDiffCollection() { - CollectionListeners listeners = new CollectionListeners( sessionFactory() ); - ParentWithCollection parent = createParentWithNullChildren( "parent" ); + @SkipForDialect(dialectClass = HANADialect.class, + reason = " HANA doesn't support tables consisting of only a single auto-generated column") + public void testUpdateParentNullToOneChildDiffCollection(SessionFactoryScope scope) { + CollectionListeners listeners = new CollectionListeners( scope.getSessionFactory() ); + ParentWithCollection parent = createParentWithNullChildren( "parent", scope ); listeners.clear(); assertNull( parent.getChildren() ); - Session s = openSession(); + Session s = scope.getSessionFactory().openSession(); Transaction tx = s.beginTransaction(); - parent = ( ParentWithCollection ) s.get( parent.getClass(), parent.getId() ); + parent = (ParentWithCollection) s.get( parent.getClass(), parent.getId() ); Collection collectionOrig = parent.getChildren(); parent.newChildren( createCollection() ); Child newChild = parent.addChild( "new" ); tx.commit(); s.close(); int index = 0; - if ( ( ( PersistentCollection ) collectionOrig ).wasInitialized() ) { + if ( ((PersistentCollection) collectionOrig).wasInitialized() ) { checkResult( listeners, listeners.getInitializeCollectionListener(), parent, collectionOrig, index++ ); } checkResult( listeners, listeners.getPreCollectionRemoveListener(), parent, collectionOrig, index++ ); checkResult( listeners, listeners.getPostCollectionRemoveListener(), parent, collectionOrig, index++ ); if ( newChild instanceof ChildWithBidirectionalManyToMany ) { - checkResult( listeners, listeners.getPreCollectionRecreateListener(), ( ChildWithBidirectionalManyToMany ) newChild, index++ ); - checkResult( listeners, listeners.getPostCollectionRecreateListener(), ( ChildWithBidirectionalManyToMany ) newChild, index++ ); + checkResult( listeners, listeners.getPreCollectionRecreateListener(), + (ChildWithBidirectionalManyToMany) newChild, index++ ); + checkResult( listeners, listeners.getPostCollectionRecreateListener(), + (ChildWithBidirectionalManyToMany) newChild, index++ ); } checkResult( listeners, listeners.getPreCollectionRecreateListener(), parent, index++ ); checkResult( listeners, listeners.getPostCollectionRecreateListener(), parent, index++ ); @@ -262,29 +248,32 @@ public void testUpdateParentNullToOneChildDiffCollection() { } @Test - @SkipForDialect(value = HANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testUpdateParentNoneToOneChildDiffCollection() { - CollectionListeners listeners = new CollectionListeners( sessionFactory() ); - ParentWithCollection parent = createParentWithNoChildren( "parent" ); + @SkipForDialect(dialectClass = HANADialect.class, + reason = " HANA doesn't support tables consisting of only a single auto-generated column") + public void testUpdateParentNoneToOneChildDiffCollection(SessionFactoryScope scope) { + CollectionListeners listeners = new CollectionListeners( scope.getSessionFactory() ); + ParentWithCollection parent = createParentWithNoChildren( "parent", scope ); listeners.clear(); assertEquals( 0, parent.getChildren().size() ); - Session s = openSession(); + Session s = scope.getSessionFactory().openSession(); Transaction tx = s.beginTransaction(); - parent = ( ParentWithCollection ) s.get( parent.getClass(), parent.getId() ); + parent = (ParentWithCollection) s.get( parent.getClass(), parent.getId() ); Collection oldCollection = parent.getChildren(); parent.newChildren( createCollection() ); Child newChild = parent.addChild( "new" ); tx.commit(); s.close(); int index = 0; - if ( ( ( PersistentCollection ) oldCollection ).wasInitialized() ) { + if ( ((PersistentCollection) oldCollection).wasInitialized() ) { checkResult( listeners, listeners.getInitializeCollectionListener(), parent, oldCollection, index++ ); } checkResult( listeners, listeners.getPreCollectionRemoveListener(), parent, oldCollection, index++ ); checkResult( listeners, listeners.getPostCollectionRemoveListener(), parent, oldCollection, index++ ); if ( newChild instanceof ChildWithBidirectionalManyToMany ) { - checkResult( listeners, listeners.getPreCollectionRecreateListener(), ( ChildWithBidirectionalManyToMany ) newChild, index++ ); - checkResult( listeners, listeners.getPostCollectionRecreateListener(), ( ChildWithBidirectionalManyToMany ) newChild, index++ ); + checkResult( listeners, listeners.getPreCollectionRecreateListener(), + (ChildWithBidirectionalManyToMany) newChild, index++ ); + checkResult( listeners, listeners.getPostCollectionRecreateListener(), + (ChildWithBidirectionalManyToMany) newChild, index++ ); } checkResult( listeners, listeners.getPreCollectionRecreateListener(), parent, index++ ); checkResult( listeners, listeners.getPostCollectionRecreateListener(), parent, index++ ); @@ -292,18 +281,19 @@ public void testUpdateParentNoneToOneChildDiffCollection() { } @Test - @SkipForDialect(value = HANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testUpdateParentOneChildDiffCollectionSameChild() { - CollectionListeners listeners = new CollectionListeners( sessionFactory() ); - ParentWithCollection parent = createParentWithOneChild( "parent", "child" ); - Child child = ( Child ) parent.getChildren().iterator().next(); + @SkipForDialect(dialectClass = HANADialect.class, + reason = " HANA doesn't support tables consisting of only a single auto-generated column") + public void testUpdateParentOneChildDiffCollectionSameChild(SessionFactoryScope scope) { + CollectionListeners listeners = new CollectionListeners( scope.getSessionFactory() ); + ParentWithCollection parent = createParentWithOneChild( "parent", "child", scope ); + Child child = (Child) parent.getChildren().iterator().next(); listeners.clear(); assertEquals( 1, parent.getChildren().size() ); - Session s = openSession(); + Session s = scope.getSessionFactory().openSession(); Transaction tx = s.beginTransaction(); - parent = ( ParentWithCollection ) s.get( parent.getClass(), parent.getId() ); + parent = (ParentWithCollection) s.get( parent.getClass(), parent.getId() ); if ( child instanceof Entity ) { - child = ( Child ) s.get( child.getClass(), ( ( Entity ) child).getId() ); + child = (Child) s.get( child.getClass(), ((Entity) child).getId() ); } Collection oldCollection = parent.getChildren(); parent.newChildren( createCollection() ); @@ -311,12 +301,12 @@ public void testUpdateParentOneChildDiffCollectionSameChild() { tx.commit(); s.close(); int index = 0; - if ( ( ( PersistentCollection ) oldCollection ).wasInitialized() ) { + if ( ((PersistentCollection) oldCollection).wasInitialized() ) { checkResult( listeners, listeners.getInitializeCollectionListener(), parent, oldCollection, index++ ); } if ( child instanceof ChildWithBidirectionalManyToMany ) { - ChildWithBidirectionalManyToMany childWithManyToMany = ( ChildWithBidirectionalManyToMany ) child; - if ( ( ( PersistentCollection ) childWithManyToMany.getParents() ).wasInitialized() ) { + ChildWithBidirectionalManyToMany childWithManyToMany = (ChildWithBidirectionalManyToMany) child; + if ( ((PersistentCollection) childWithManyToMany.getParents()).wasInitialized() ) { checkResult( listeners, listeners.getInitializeCollectionListener(), childWithManyToMany, index++ ); } } @@ -325,8 +315,10 @@ public void testUpdateParentOneChildDiffCollectionSameChild() { if ( child instanceof ChildWithBidirectionalManyToMany ) { // hmmm, the same parent was removed and re-added to the child's collection; // should this be considered an update? - checkResult( listeners, listeners.getPreCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) child, index++ ); - checkResult( listeners, listeners.getPostCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) child, index++ ); + checkResult( listeners, listeners.getPreCollectionUpdateListener(), + (ChildWithBidirectionalManyToMany) child, index++ ); + checkResult( listeners, listeners.getPostCollectionUpdateListener(), + (ChildWithBidirectionalManyToMany) child, index++ ); } checkResult( listeners, listeners.getPreCollectionRecreateListener(), parent, index++ ); checkResult( listeners, listeners.getPostCollectionRecreateListener(), parent, index++ ); @@ -334,18 +326,19 @@ public void testUpdateParentOneChildDiffCollectionSameChild() { } @Test - @SkipForDialect(value = HANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testUpdateParentOneChildDiffCollectionDiffChild() { - CollectionListeners listeners = new CollectionListeners( sessionFactory() ); - ParentWithCollection parent = createParentWithOneChild( "parent", "child" ); - Child oldChild = ( Child ) parent.getChildren().iterator().next(); + @SkipForDialect(dialectClass = HANADialect.class, + reason = " HANA doesn't support tables consisting of only a single auto-generated column") + public void testUpdateParentOneChildDiffCollectionDiffChild(SessionFactoryScope scope) { + CollectionListeners listeners = new CollectionListeners( scope.getSessionFactory() ); + ParentWithCollection parent = createParentWithOneChild( "parent", "child", scope ); + Child oldChild = (Child) parent.getChildren().iterator().next(); listeners.clear(); assertEquals( 1, parent.getChildren().size() ); - Session s = openSession(); + Session s = scope.getSessionFactory().openSession(); Transaction tx = s.beginTransaction(); - parent = ( ParentWithCollection ) s.get( parent.getClass(), parent.getId() ); + parent = (ParentWithCollection) s.get( parent.getClass(), parent.getId() ); if ( oldChild instanceof Entity ) { - oldChild = ( Child ) s.get( oldChild.getClass(), ( ( Entity ) oldChild).getId() ); + oldChild = (Child) s.get( oldChild.getClass(), ((Entity) oldChild).getId() ); } Collection oldCollection = parent.getChildren(); parent.newChildren( createCollection() ); @@ -353,22 +346,26 @@ public void testUpdateParentOneChildDiffCollectionDiffChild() { tx.commit(); s.close(); int index = 0; - if ( ( (PersistentCollection) oldCollection ).wasInitialized() ) { + if ( ((PersistentCollection) oldCollection).wasInitialized() ) { checkResult( listeners, listeners.getInitializeCollectionListener(), parent, oldCollection, index++ ); } if ( oldChild instanceof ChildWithBidirectionalManyToMany ) { - ChildWithBidirectionalManyToMany oldChildWithManyToMany = ( ChildWithBidirectionalManyToMany ) oldChild; - if ( ( ( PersistentCollection ) oldChildWithManyToMany.getParents() ).wasInitialized() ) { + ChildWithBidirectionalManyToMany oldChildWithManyToMany = (ChildWithBidirectionalManyToMany) oldChild; + if ( ((PersistentCollection) oldChildWithManyToMany.getParents()).wasInitialized() ) { checkResult( listeners, listeners.getInitializeCollectionListener(), oldChildWithManyToMany, index++ ); } } checkResult( listeners, listeners.getPreCollectionRemoveListener(), parent, oldCollection, index++ ); checkResult( listeners, listeners.getPostCollectionRemoveListener(), parent, oldCollection, index++ ); if ( oldChild instanceof ChildWithBidirectionalManyToMany ) { - checkResult( listeners, listeners.getPreCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) oldChild, index++ ); - checkResult( listeners, listeners.getPostCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) oldChild, index++ ); - checkResult( listeners, listeners.getPreCollectionRecreateListener(), ( ChildWithBidirectionalManyToMany ) newChild, index++ ); - checkResult( listeners, listeners.getPostCollectionRecreateListener(), ( ChildWithBidirectionalManyToMany ) newChild, index++ ); + checkResult( listeners, listeners.getPreCollectionUpdateListener(), + (ChildWithBidirectionalManyToMany) oldChild, index++ ); + checkResult( listeners, listeners.getPostCollectionUpdateListener(), + (ChildWithBidirectionalManyToMany) oldChild, index++ ); + checkResult( listeners, listeners.getPreCollectionRecreateListener(), + (ChildWithBidirectionalManyToMany) newChild, index++ ); + checkResult( listeners, listeners.getPostCollectionRecreateListener(), + (ChildWithBidirectionalManyToMany) newChild, index++ ); } checkResult( listeners, listeners.getPreCollectionRecreateListener(), parent, index++ ); checkResult( listeners, listeners.getPostCollectionRecreateListener(), parent, index++ ); @@ -376,129 +373,139 @@ public void testUpdateParentOneChildDiffCollectionDiffChild() { } @Test - @SkipForDialect(value = HANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testUpdateParentOneChildToNoneByRemove() { - CollectionListeners listeners = new CollectionListeners( sessionFactory() ); - ParentWithCollection parent = createParentWithOneChild( "parent", "child" ); + @SkipForDialect(dialectClass = HANADialect.class, + reason = " HANA doesn't support tables consisting of only a single auto-generated column") + public void testUpdateParentOneChildToNoneByRemove(SessionFactoryScope scope) { + CollectionListeners listeners = new CollectionListeners( scope.getSessionFactory() ); + ParentWithCollection parent = createParentWithOneChild( "parent", "child", scope ); assertEquals( 1, parent.getChildren().size() ); - Child child = ( Child ) parent.getChildren().iterator().next(); + Child child = (Child) parent.getChildren().iterator().next(); listeners.clear(); - Session s = openSession(); + Session s = scope.getSessionFactory().openSession(); Transaction tx = s.beginTransaction(); - parent = ( ParentWithCollection ) s.get( parent.getClass(), parent.getId() ); + parent = (ParentWithCollection) s.get( parent.getClass(), parent.getId() ); if ( child instanceof Entity ) { - child = ( Child ) s.get( child.getClass(), ( ( Entity ) child ).getId() ); + child = (Child) s.get( child.getClass(), ((Entity) child).getId() ); } parent.removeChild( child ); tx.commit(); s.close(); int index = 0; - if ( ( ( PersistentCollection ) parent.getChildren() ).wasInitialized() ) { + if ( ((PersistentCollection) parent.getChildren()).wasInitialized() ) { checkResult( listeners, listeners.getInitializeCollectionListener(), parent, index++ ); } if ( child instanceof ChildWithBidirectionalManyToMany ) { - ChildWithBidirectionalManyToMany childWithManyToMany = ( ChildWithBidirectionalManyToMany ) child; - if ( ( ( PersistentCollection ) childWithManyToMany.getParents( ) ).wasInitialized() ) { + ChildWithBidirectionalManyToMany childWithManyToMany = (ChildWithBidirectionalManyToMany) child; + if ( ((PersistentCollection) childWithManyToMany.getParents()).wasInitialized() ) { checkResult( listeners, listeners.getInitializeCollectionListener(), childWithManyToMany, index++ ); } } checkResult( listeners, listeners.getPreCollectionUpdateListener(), parent, index++ ); checkResult( listeners, listeners.getPostCollectionUpdateListener(), parent, index++ ); if ( child instanceof ChildWithBidirectionalManyToMany ) { - checkResult( listeners, listeners.getPreCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) child, index++ ); - checkResult( listeners, listeners.getPostCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) child, index++ ); + checkResult( listeners, listeners.getPreCollectionUpdateListener(), + (ChildWithBidirectionalManyToMany) child, index++ ); + checkResult( listeners, listeners.getPostCollectionUpdateListener(), + (ChildWithBidirectionalManyToMany) child, index++ ); } checkNumberOfResults( listeners, index ); } @Test - @SkipForDialect(value = HANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testUpdateParentOneChildToNoneByClear() { - CollectionListeners listeners = new CollectionListeners( sessionFactory() ); - ParentWithCollection parent = createParentWithOneChild( "parent", "child" ); + @SkipForDialect(dialectClass = HANADialect.class, + reason = " HANA doesn't support tables consisting of only a single auto-generated column") + public void testUpdateParentOneChildToNoneByClear(SessionFactoryScope scope) { + CollectionListeners listeners = new CollectionListeners( scope.getSessionFactory() ); + ParentWithCollection parent = createParentWithOneChild( "parent", "child", scope ); assertEquals( 1, parent.getChildren().size() ); - Child child = ( Child ) parent.getChildren().iterator().next(); + Child child = (Child) parent.getChildren().iterator().next(); listeners.clear(); - Session s = openSession(); + Session s = scope.getSessionFactory().openSession(); Transaction tx = s.beginTransaction(); - parent = ( ParentWithCollection ) s.get( parent.getClass(), parent.getId() ); + parent = (ParentWithCollection) s.get( parent.getClass(), parent.getId() ); if ( child instanceof Entity ) { - child = ( Child ) s.get( child.getClass(), ( ( Entity ) child ).getId() ); + child = (Child) s.get( child.getClass(), ((Entity) child).getId() ); } parent.clearChildren(); tx.commit(); s.close(); int index = 0; - if ( ( ( PersistentCollection ) parent.getChildren() ).wasInitialized() ) { + if ( ((PersistentCollection) parent.getChildren()).wasInitialized() ) { checkResult( listeners, listeners.getInitializeCollectionListener(), parent, index++ ); } if ( child instanceof ChildWithBidirectionalManyToMany ) { - ChildWithBidirectionalManyToMany childWithManyToMany = ( ChildWithBidirectionalManyToMany ) child; - if ( ( ( PersistentCollection ) childWithManyToMany.getParents() ).wasInitialized() ) { + ChildWithBidirectionalManyToMany childWithManyToMany = (ChildWithBidirectionalManyToMany) child; + if ( ((PersistentCollection) childWithManyToMany.getParents()).wasInitialized() ) { checkResult( listeners, listeners.getInitializeCollectionListener(), childWithManyToMany, index++ ); } } checkResult( listeners, listeners.getPreCollectionUpdateListener(), parent, index++ ); checkResult( listeners, listeners.getPostCollectionUpdateListener(), parent, index++ ); if ( child instanceof ChildWithBidirectionalManyToMany ) { - checkResult( listeners, listeners.getPreCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) child, index++ ); - checkResult( listeners, listeners.getPostCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) child, index++ ); + checkResult( listeners, listeners.getPreCollectionUpdateListener(), + (ChildWithBidirectionalManyToMany) child, index++ ); + checkResult( listeners, listeners.getPostCollectionUpdateListener(), + (ChildWithBidirectionalManyToMany) child, index++ ); } checkNumberOfResults( listeners, index ); } @Test - @SkipForDialect(value = HANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testUpdateParentTwoChildrenToOne() { - CollectionListeners listeners = new CollectionListeners( sessionFactory() ); - ParentWithCollection parent = createParentWithOneChild( "parent", "child" ); + @SkipForDialect(dialectClass = HANADialect.class, + reason = " HANA doesn't support tables consisting of only a single auto-generated column") + public void testUpdateParentTwoChildrenToOne(SessionFactoryScope scope) { + CollectionListeners listeners = new CollectionListeners( scope.getSessionFactory() ); + ParentWithCollection parent = createParentWithOneChild( "parent", "child", scope ); assertEquals( 1, parent.getChildren().size() ); - Child oldChild = ( Child ) parent.getChildren().iterator().next(); + Child oldChild = (Child) parent.getChildren().iterator().next(); listeners.clear(); - Session s = openSession(); + Session s = scope.getSessionFactory().openSession(); Transaction tx = s.beginTransaction(); - parent = ( ParentWithCollection ) s.get( parent.getClass(), parent.getId() ); + parent = (ParentWithCollection) s.get( parent.getClass(), parent.getId() ); parent.addChild( "new" ); tx.commit(); s.close(); listeners.clear(); - s = openSession(); + s = scope.getSessionFactory().openSession(); tx = s.beginTransaction(); - parent = ( ParentWithCollection ) s.get( parent.getClass(), parent.getId() ); + parent = (ParentWithCollection) s.get( parent.getClass(), parent.getId() ); if ( oldChild instanceof Entity ) { - oldChild = ( Child ) s.get( oldChild.getClass(), ( ( Entity ) oldChild ).getId() ); + oldChild = (Child) s.get( oldChild.getClass(), ((Entity) oldChild).getId() ); } parent.removeChild( oldChild ); tx.commit(); s.close(); int index = 0; - if ( ( ( PersistentCollection ) parent.getChildren() ).wasInitialized() ) { + if ( ((PersistentCollection) parent.getChildren()).wasInitialized() ) { checkResult( listeners, listeners.getInitializeCollectionListener(), parent, index++ ); } if ( oldChild instanceof ChildWithBidirectionalManyToMany ) { - ChildWithBidirectionalManyToMany oldChildWithManyToMany = ( ChildWithBidirectionalManyToMany ) oldChild; - if ( ( ( PersistentCollection ) oldChildWithManyToMany.getParents() ).wasInitialized() ) { + ChildWithBidirectionalManyToMany oldChildWithManyToMany = (ChildWithBidirectionalManyToMany) oldChild; + if ( ((PersistentCollection) oldChildWithManyToMany.getParents()).wasInitialized() ) { checkResult( listeners, listeners.getInitializeCollectionListener(), oldChildWithManyToMany, index++ ); } } checkResult( listeners, listeners.getPreCollectionUpdateListener(), parent, index++ ); checkResult( listeners, listeners.getPostCollectionUpdateListener(), parent, index++ ); if ( oldChild instanceof ChildWithBidirectionalManyToMany ) { - checkResult( listeners, listeners.getPreCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) oldChild, index++ ); - checkResult( listeners, listeners.getPostCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) oldChild, index++ ); + checkResult( listeners, listeners.getPreCollectionUpdateListener(), + (ChildWithBidirectionalManyToMany) oldChild, index++ ); + checkResult( listeners, listeners.getPostCollectionUpdateListener(), + (ChildWithBidirectionalManyToMany) oldChild, index++ ); } checkNumberOfResults( listeners, index ); } @Test - @SkipForDialect(value = HANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testDeleteParentWithNullChildren() { - CollectionListeners listeners = new CollectionListeners( sessionFactory() ); - ParentWithCollection parent = createParentWithNullChildren( "parent" ); + @SkipForDialect(dialectClass = HANADialect.class, + reason = " HANA doesn't support tables consisting of only a single auto-generated column") + public void testDeleteParentWithNullChildren(SessionFactoryScope scope) { + CollectionListeners listeners = new CollectionListeners( scope.getSessionFactory() ); + ParentWithCollection parent = createParentWithNullChildren( "parent", scope ); listeners.clear(); - Session s = openSession(); + Session s = scope.getSessionFactory().openSession(); Transaction tx = s.beginTransaction(); - parent = ( ParentWithCollection ) s.get( parent.getClass(), parent.getId() ); + parent = (ParentWithCollection) s.get( parent.getClass(), parent.getId() ); s.remove( parent ); tx.commit(); s.close(); @@ -510,14 +517,15 @@ public void testDeleteParentWithNullChildren() { } @Test - @SkipForDialect(value = HANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testDeleteParentWithNoChildren() { - CollectionListeners listeners = new CollectionListeners( sessionFactory() ); - ParentWithCollection parent = createParentWithNoChildren( "parent" ); + @SkipForDialect(dialectClass = HANADialect.class, + reason = " HANA doesn't support tables consisting of only a single auto-generated column") + public void testDeleteParentWithNoChildren(SessionFactoryScope scope) { + CollectionListeners listeners = new CollectionListeners( scope.getSessionFactory() ); + ParentWithCollection parent = createParentWithNoChildren( "parent", scope ); listeners.clear(); - Session s = openSession(); + Session s = scope.getSessionFactory().openSession(); Transaction tx = s.beginTransaction(); - parent = ( ParentWithCollection ) s.get( parent.getClass(), parent.getId() ); + parent = (ParentWithCollection) s.get( parent.getClass(), parent.getId() ); s.remove( parent ); tx.commit(); s.close(); @@ -529,17 +537,18 @@ public void testDeleteParentWithNoChildren() { } @Test - @SkipForDialect(value = HANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testDeleteParentAndChild() { - CollectionListeners listeners = new CollectionListeners( sessionFactory() ); - ParentWithCollection parent = createParentWithOneChild( "parent", "child" ); - Child child = ( Child ) parent.getChildren().iterator().next(); + @SkipForDialect(dialectClass = HANADialect.class, + reason = " HANA doesn't support tables consisting of only a single auto-generated column") + public void testDeleteParentAndChild(SessionFactoryScope scope) { + CollectionListeners listeners = new CollectionListeners( scope.getSessionFactory() ); + ParentWithCollection parent = createParentWithOneChild( "parent", "child", scope ); + Child child = (Child) parent.getChildren().iterator().next(); listeners.clear(); - Session s = openSession(); + Session s = scope.getSessionFactory().openSession(); Transaction tx = s.beginTransaction(); - parent = ( ParentWithCollection ) s.get( parent.getClass(), parent.getId() ); + parent = (ParentWithCollection) s.get( parent.getClass(), parent.getId() ); if ( child instanceof Entity ) { - child = ( Child ) s.get( child.getClass(), ( ( Entity ) child ).getId() ); + child = (Child) s.get( child.getClass(), ((Entity) child).getId() ); } parent.removeChild( child ); if ( child instanceof Entity ) { @@ -551,44 +560,49 @@ public void testDeleteParentAndChild() { int index = 0; checkResult( listeners, listeners.getInitializeCollectionListener(), parent, index++ ); if ( child instanceof ChildWithBidirectionalManyToMany ) { - checkResult( listeners, listeners.getInitializeCollectionListener(), ( ChildWithBidirectionalManyToMany ) child, index++ ); + checkResult( listeners, listeners.getInitializeCollectionListener(), + (ChildWithBidirectionalManyToMany) child, index++ ); } checkResult( listeners, listeners.getPreCollectionRemoveListener(), parent, index++ ); checkResult( listeners, listeners.getPostCollectionRemoveListener(), parent, index++ ); if ( child instanceof ChildWithBidirectionalManyToMany ) { - checkResult( listeners, listeners.getPreCollectionRemoveListener(), ( ChildWithBidirectionalManyToMany ) child, index++ ); - checkResult( listeners, listeners.getPostCollectionRemoveListener(), ( ChildWithBidirectionalManyToMany ) child, index++ ); + checkResult( listeners, listeners.getPreCollectionRemoveListener(), + (ChildWithBidirectionalManyToMany) child, index++ ); + checkResult( listeners, listeners.getPostCollectionRemoveListener(), + (ChildWithBidirectionalManyToMany) child, index++ ); } checkNumberOfResults( listeners, index ); } @Test - @SkipForDialect(value = HANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testMoveChildToDifferentParent() { - CollectionListeners listeners = new CollectionListeners( sessionFactory() ); - ParentWithCollection parent = createParentWithOneChild( "parent", "child" ); - ParentWithCollection otherParent = createParentWithOneChild( "otherParent", "otherChild" ); - Child child = ( Child ) parent.getChildren().iterator().next(); + @SkipForDialect(dialectClass = HANADialect.class, + reason = " HANA doesn't support tables consisting of only a single auto-generated column") + public void testMoveChildToDifferentParent(SessionFactoryScope scope) { + CollectionListeners listeners = new CollectionListeners( scope.getSessionFactory() ); + ParentWithCollection parent = createParentWithOneChild( "parent", "child", scope ); + ParentWithCollection otherParent = createParentWithOneChild( "otherParent", "otherChild", scope ); + Child child = (Child) parent.getChildren().iterator().next(); listeners.clear(); - Session s = openSession(); + Session s = scope.getSessionFactory().openSession(); Transaction tx = s.beginTransaction(); - parent = ( ParentWithCollection ) s.get( parent.getClass(), parent.getId() ); - otherParent = ( ParentWithCollection ) s.get( otherParent.getClass(), otherParent.getId() ); + parent = (ParentWithCollection) s.get( parent.getClass(), parent.getId() ); + otherParent = (ParentWithCollection) s.get( otherParent.getClass(), otherParent.getId() ); if ( child instanceof Entity ) { - child = ( Child ) s.get( child.getClass(), ( ( Entity ) child ).getId() ); + child = (Child) s.get( child.getClass(), ((Entity) child).getId() ); } parent.removeChild( child ); otherParent.addChild( child ); tx.commit(); s.close(); int index = 0; - if ( ( ( PersistentCollection ) parent.getChildren() ).wasInitialized() ) { + if ( ((PersistentCollection) parent.getChildren()).wasInitialized() ) { checkResult( listeners, listeners.getInitializeCollectionListener(), parent, index++ ); } if ( child instanceof ChildWithBidirectionalManyToMany ) { - checkResult( listeners, listeners.getInitializeCollectionListener(), ( ChildWithBidirectionalManyToMany ) child, index++ ); + checkResult( listeners, listeners.getInitializeCollectionListener(), + (ChildWithBidirectionalManyToMany) child, index++ ); } - if ( ( ( PersistentCollection ) otherParent.getChildren() ).wasInitialized() ) { + if ( ((PersistentCollection) otherParent.getChildren()).wasInitialized() ) { checkResult( listeners, listeners.getInitializeCollectionListener(), otherParent, index++ ); } checkResult( listeners, listeners.getPreCollectionUpdateListener(), parent, index++ ); @@ -596,63 +610,70 @@ public void testMoveChildToDifferentParent() { checkResult( listeners, listeners.getPreCollectionUpdateListener(), otherParent, index++ ); checkResult( listeners, listeners.getPostCollectionUpdateListener(), otherParent, index++ ); if ( child instanceof ChildWithBidirectionalManyToMany ) { - checkResult( listeners, listeners.getPreCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) child, index++ ); - checkResult( listeners, listeners.getPostCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) child, index++ ); + checkResult( listeners, listeners.getPreCollectionUpdateListener(), + (ChildWithBidirectionalManyToMany) child, index++ ); + checkResult( listeners, listeners.getPostCollectionUpdateListener(), + (ChildWithBidirectionalManyToMany) child, index++ ); } checkNumberOfResults( listeners, index ); } @Test - @SkipForDialect(value = HANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testMoveAllChildrenToDifferentParent() { - CollectionListeners listeners = new CollectionListeners( sessionFactory() ); - ParentWithCollection parent = createParentWithOneChild( "parent", "child" ); - ParentWithCollection otherParent = createParentWithOneChild( "otherParent", "otherChild" ); - Child child = ( Child ) parent.getChildren().iterator().next(); + @SkipForDialect(dialectClass = HANADialect.class, + reason = " HANA doesn't support tables consisting of only a single auto-generated column") + public void testMoveAllChildrenToDifferentParent(SessionFactoryScope scope) { + CollectionListeners listeners = new CollectionListeners( scope.getSessionFactory() ); + ParentWithCollection parent = createParentWithOneChild( "parent", "child", scope ); + ParentWithCollection otherParent = createParentWithOneChild( "otherParent", "otherChild", scope ); + Child child = (Child) parent.getChildren().iterator().next(); listeners.clear(); - Session s = openSession(); + Session s = scope.getSessionFactory().openSession(); Transaction tx = s.beginTransaction(); - parent = ( ParentWithCollection ) s.get( parent.getClass(), parent.getId() ); - otherParent = ( ParentWithCollection ) s.get( otherParent.getClass(), otherParent.getId() ); + parent = (ParentWithCollection) s.get( parent.getClass(), parent.getId() ); + otherParent = (ParentWithCollection) s.get( otherParent.getClass(), otherParent.getId() ); if ( child instanceof Entity ) { - child = ( Child ) s.get( child.getClass(), ( ( Entity ) child ).getId() ); + child = (Child) s.get( child.getClass(), ((Entity) child).getId() ); } otherParent.addAllChildren( parent.getChildren() ); parent.clearChildren(); tx.commit(); s.close(); int index = 0; - if ( ( ( PersistentCollection ) parent.getChildren() ).wasInitialized() ) { + if ( ((PersistentCollection) parent.getChildren()).wasInitialized() ) { checkResult( listeners, listeners.getInitializeCollectionListener(), parent, index++ ); } - if ( ( ( PersistentCollection ) otherParent.getChildren() ).wasInitialized() ) { + if ( ((PersistentCollection) otherParent.getChildren()).wasInitialized() ) { checkResult( listeners, listeners.getInitializeCollectionListener(), otherParent, index++ ); } if ( child instanceof ChildWithBidirectionalManyToMany ) { - checkResult( listeners, listeners.getInitializeCollectionListener(), ( ChildWithBidirectionalManyToMany ) child, index++ ); + checkResult( listeners, listeners.getInitializeCollectionListener(), + (ChildWithBidirectionalManyToMany) child, index++ ); } checkResult( listeners, listeners.getPreCollectionUpdateListener(), parent, index++ ); checkResult( listeners, listeners.getPostCollectionUpdateListener(), parent, index++ ); checkResult( listeners, listeners.getPreCollectionUpdateListener(), otherParent, index++ ); checkResult( listeners, listeners.getPostCollectionUpdateListener(), otherParent, index++ ); if ( child instanceof ChildWithBidirectionalManyToMany ) { - checkResult( listeners, listeners.getPreCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) child, index++ ); - checkResult( listeners, listeners.getPostCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) child, index++ ); + checkResult( listeners, listeners.getPreCollectionUpdateListener(), + (ChildWithBidirectionalManyToMany) child, index++ ); + checkResult( listeners, listeners.getPostCollectionUpdateListener(), + (ChildWithBidirectionalManyToMany) child, index++ ); } checkNumberOfResults( listeners, index ); } @Test - @SkipForDialect(value = HANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testMoveCollectionToDifferentParent() { - CollectionListeners listeners = new CollectionListeners( sessionFactory() ); - ParentWithCollection parent = createParentWithOneChild( "parent", "child" ); - ParentWithCollection otherParent = createParentWithOneChild( "otherParent", "otherChild" ); + @SkipForDialect(dialectClass = HANADialect.class, + reason = " HANA doesn't support tables consisting of only a single auto-generated column") + public void testMoveCollectionToDifferentParent(SessionFactoryScope scope) { + CollectionListeners listeners = new CollectionListeners( scope.getSessionFactory() ); + ParentWithCollection parent = createParentWithOneChild( "parent", "child", scope ); + ParentWithCollection otherParent = createParentWithOneChild( "otherParent", "otherChild", scope ); listeners.clear(); - Session s = openSession(); + Session s = scope.getSessionFactory().openSession(); Transaction tx = s.beginTransaction(); - parent = ( ParentWithCollection ) s.get( parent.getClass(), parent.getId() ); - otherParent = ( ParentWithCollection ) s.get( otherParent.getClass(), otherParent.getId() ); + parent = (ParentWithCollection) s.get( parent.getClass(), parent.getId() ); + otherParent = (ParentWithCollection) s.get( otherParent.getClass(), otherParent.getId() ); Collection otherCollectionOrig = otherParent.getChildren(); otherParent.newChildren( parent.getChildren() ); parent.newChildren( null ); @@ -660,27 +681,38 @@ public void testMoveCollectionToDifferentParent() { s.close(); int index = 0; Child otherChildOrig = null; - if ( ( ( PersistentCollection ) otherCollectionOrig ).wasInitialized() ) { - checkResult( listeners, listeners.getInitializeCollectionListener(), otherParent, otherCollectionOrig, index++ ); - otherChildOrig = ( Child ) otherCollectionOrig.iterator().next(); + if ( ((PersistentCollection) otherCollectionOrig).wasInitialized() ) { + checkResult( listeners, listeners.getInitializeCollectionListener(), otherParent, otherCollectionOrig, + index++ ); + otherChildOrig = (Child) otherCollectionOrig.iterator().next(); if ( otherChildOrig instanceof ChildWithBidirectionalManyToMany ) { - checkResult( listeners, listeners.getInitializeCollectionListener(), ( ChildWithBidirectionalManyToMany ) otherChildOrig, index++ ); + checkResult( listeners, listeners.getInitializeCollectionListener(), + (ChildWithBidirectionalManyToMany) otherChildOrig, index++ ); } } - checkResult( listeners, listeners.getInitializeCollectionListener(), parent, otherParent.getChildren(), index++ ); - Child otherChild = ( Child ) otherParent.getChildren().iterator().next(); + checkResult( listeners, listeners.getInitializeCollectionListener(), parent, otherParent.getChildren(), + index++ ); + Child otherChild = (Child) otherParent.getChildren().iterator().next(); if ( otherChild instanceof ChildWithBidirectionalManyToMany ) { - checkResult( listeners, listeners.getInitializeCollectionListener(), ( ChildWithBidirectionalManyToMany ) otherChild, index++ ); + checkResult( listeners, listeners.getInitializeCollectionListener(), + (ChildWithBidirectionalManyToMany) otherChild, index++ ); } - checkResult( listeners, listeners.getPreCollectionRemoveListener(), parent, otherParent.getChildren(), index++ ); - checkResult( listeners, listeners.getPostCollectionRemoveListener(), parent, otherParent.getChildren(), index++ ); + checkResult( listeners, listeners.getPreCollectionRemoveListener(), parent, otherParent.getChildren(), + index++ ); + checkResult( listeners, listeners.getPostCollectionRemoveListener(), parent, otherParent.getChildren(), + index++ ); checkResult( listeners, listeners.getPreCollectionRemoveListener(), otherParent, otherCollectionOrig, index++ ); - checkResult( listeners, listeners.getPostCollectionRemoveListener(), otherParent, otherCollectionOrig, index++ ); + checkResult( listeners, listeners.getPostCollectionRemoveListener(), otherParent, otherCollectionOrig, + index++ ); if ( otherChild instanceof ChildWithBidirectionalManyToMany ) { - checkResult( listeners, listeners.getPreCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) otherChildOrig, index++ ); - checkResult( listeners, listeners.getPostCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) otherChildOrig, index++ ); - checkResult( listeners, listeners.getPreCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) otherChild, index++ ); - checkResult( listeners, listeners.getPostCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) otherChild, index++ ); + checkResult( listeners, listeners.getPreCollectionUpdateListener(), + (ChildWithBidirectionalManyToMany) otherChildOrig, index++ ); + checkResult( listeners, listeners.getPostCollectionUpdateListener(), + (ChildWithBidirectionalManyToMany) otherChildOrig, index++ ); + checkResult( listeners, listeners.getPreCollectionUpdateListener(), + (ChildWithBidirectionalManyToMany) otherChild, index++ ); + checkResult( listeners, listeners.getPostCollectionUpdateListener(), + (ChildWithBidirectionalManyToMany) otherChild, index++ ); } checkResult( listeners, listeners.getPreCollectionRecreateListener(), otherParent, index++ ); checkResult( listeners, listeners.getPostCollectionRecreateListener(), otherParent, index++ ); @@ -690,18 +722,19 @@ public void testMoveCollectionToDifferentParent() { } @Test - @SkipForDialect(value = HANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testMoveCollectionToDifferentParentFlushMoveToDifferentParent() { - CollectionListeners listeners = new CollectionListeners( sessionFactory() ); - ParentWithCollection parent = createParentWithOneChild( "parent", "child" ); - ParentWithCollection otherParent = createParentWithOneChild( "otherParent", "otherChild" ); - ParentWithCollection otherOtherParent = createParentWithNoChildren( "otherParent" ); + @SkipForDialect(dialectClass = HANADialect.class, + reason = " HANA doesn't support tables consisting of only a single auto-generated column") + public void testMoveCollectionToDifferentParentFlushMoveToDifferentParent(SessionFactoryScope scope) { + CollectionListeners listeners = new CollectionListeners( scope.getSessionFactory() ); + ParentWithCollection parent = createParentWithOneChild( "parent", "child", scope ); + ParentWithCollection otherParent = createParentWithOneChild( "otherParent", "otherChild", scope ); + ParentWithCollection otherOtherParent = createParentWithNoChildren( "otherParent", scope ); listeners.clear(); - Session s = openSession(); + Session s = scope.getSessionFactory().openSession(); Transaction tx = s.beginTransaction(); - parent = ( ParentWithCollection ) s.get( parent.getClass(), parent.getId() ); - otherParent = ( ParentWithCollection ) s.get( otherParent.getClass(), otherParent.getId() ); - otherOtherParent = ( ParentWithCollection ) s.get( otherOtherParent.getClass(), otherOtherParent.getId() ); + parent = (ParentWithCollection) s.get( parent.getClass(), parent.getId() ); + otherParent = (ParentWithCollection) s.get( otherParent.getClass(), otherParent.getId() ); + otherOtherParent = (ParentWithCollection) s.get( otherOtherParent.getClass(), otherOtherParent.getId() ); Collection otherCollectionOrig = otherParent.getChildren(); Collection otherOtherCollectionOrig = otherOtherParent.getChildren(); otherParent.newChildren( parent.getChildren() ); @@ -713,40 +746,60 @@ public void testMoveCollectionToDifferentParentFlushMoveToDifferentParent() { s.close(); int index = 0; Child otherChildOrig = null; - if ( ( ( PersistentCollection ) otherCollectionOrig ).wasInitialized() ) { - checkResult( listeners, listeners.getInitializeCollectionListener(), otherParent, otherCollectionOrig, index++ ); - otherChildOrig = ( Child ) otherCollectionOrig.iterator().next(); + if ( ((PersistentCollection) otherCollectionOrig).wasInitialized() ) { + checkResult( listeners, listeners.getInitializeCollectionListener(), otherParent, otherCollectionOrig, + index++ ); + otherChildOrig = (Child) otherCollectionOrig.iterator().next(); if ( otherChildOrig instanceof ChildWithBidirectionalManyToMany ) { - checkResult( listeners, listeners.getInitializeCollectionListener(), ( ChildWithBidirectionalManyToMany ) otherChildOrig, index++ ); + checkResult( listeners, listeners.getInitializeCollectionListener(), + (ChildWithBidirectionalManyToMany) otherChildOrig, index++ ); } } - checkResult( listeners, listeners.getInitializeCollectionListener(), parent, otherOtherParent.getChildren(), index++ ); - Child otherOtherChild = ( Child ) otherOtherParent.getChildren().iterator().next(); + checkResult( listeners, listeners.getInitializeCollectionListener(), parent, otherOtherParent.getChildren(), + index++ ); + Child otherOtherChild = (Child) otherOtherParent.getChildren().iterator().next(); if ( otherOtherChild instanceof ChildWithBidirectionalManyToMany ) { - checkResult( listeners, listeners.getInitializeCollectionListener(), ( ChildWithBidirectionalManyToMany ) otherOtherChild, index++ ); + checkResult( listeners, listeners.getInitializeCollectionListener(), + (ChildWithBidirectionalManyToMany) otherOtherChild, index++ ); } - checkResult( listeners, listeners.getPreCollectionRemoveListener(), parent, otherOtherParent.getChildren(), index++ ); - checkResult( listeners, listeners.getPostCollectionRemoveListener(), parent, otherOtherParent.getChildren(), index++ ); + checkResult( listeners, listeners.getPreCollectionRemoveListener(), parent, otherOtherParent.getChildren(), + index++ ); + checkResult( listeners, listeners.getPostCollectionRemoveListener(), parent, otherOtherParent.getChildren(), + index++ ); checkResult( listeners, listeners.getPreCollectionRemoveListener(), otherParent, otherCollectionOrig, index++ ); - checkResult( listeners, listeners.getPostCollectionRemoveListener(), otherParent, otherCollectionOrig, index++ ); + checkResult( listeners, listeners.getPostCollectionRemoveListener(), otherParent, otherCollectionOrig, + index++ ); if ( otherOtherChild instanceof ChildWithBidirectionalManyToMany ) { - checkResult( listeners, listeners.getPreCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) otherChildOrig, index++ ); - checkResult( listeners, listeners.getPostCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) otherChildOrig, index++ ); - checkResult( listeners, listeners.getPreCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) otherOtherChild, index++ ); - checkResult( listeners, listeners.getPostCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) otherOtherChild, index++ ); - } - checkResult( listeners, listeners.getPreCollectionRecreateListener(), otherParent, otherOtherParent.getChildren(), index++ ); - checkResult( listeners, listeners.getPostCollectionRecreateListener(), otherParent, otherOtherParent.getChildren(), index++ ); - if ( ( ( PersistentCollection ) otherOtherCollectionOrig ).wasInitialized() ) { - checkResult( listeners, listeners.getInitializeCollectionListener(), otherOtherParent, otherOtherCollectionOrig, index++ ); - } - checkResult( listeners, listeners.getPreCollectionRemoveListener(), otherParent, otherOtherParent.getChildren(), index++ ); - checkResult( listeners, listeners.getPostCollectionRemoveListener(), otherParent, otherOtherParent.getChildren(), index++ ); - checkResult( listeners, listeners.getPreCollectionRemoveListener(), otherOtherParent, otherOtherCollectionOrig, index++ ); - checkResult( listeners, listeners.getPostCollectionRemoveListener(), otherOtherParent, otherOtherCollectionOrig, index++ ); + checkResult( listeners, listeners.getPreCollectionUpdateListener(), + (ChildWithBidirectionalManyToMany) otherChildOrig, index++ ); + checkResult( listeners, listeners.getPostCollectionUpdateListener(), + (ChildWithBidirectionalManyToMany) otherChildOrig, index++ ); + checkResult( listeners, listeners.getPreCollectionUpdateListener(), + (ChildWithBidirectionalManyToMany) otherOtherChild, index++ ); + checkResult( listeners, listeners.getPostCollectionUpdateListener(), + (ChildWithBidirectionalManyToMany) otherOtherChild, index++ ); + } + checkResult( listeners, listeners.getPreCollectionRecreateListener(), otherParent, + otherOtherParent.getChildren(), index++ ); + checkResult( listeners, listeners.getPostCollectionRecreateListener(), otherParent, + otherOtherParent.getChildren(), index++ ); + if ( ((PersistentCollection) otherOtherCollectionOrig).wasInitialized() ) { + checkResult( listeners, listeners.getInitializeCollectionListener(), otherOtherParent, + otherOtherCollectionOrig, index++ ); + } + checkResult( listeners, listeners.getPreCollectionRemoveListener(), otherParent, otherOtherParent.getChildren(), + index++ ); + checkResult( listeners, listeners.getPostCollectionRemoveListener(), otherParent, + otherOtherParent.getChildren(), index++ ); + checkResult( listeners, listeners.getPreCollectionRemoveListener(), otherOtherParent, otherOtherCollectionOrig, + index++ ); + checkResult( listeners, listeners.getPostCollectionRemoveListener(), otherOtherParent, otherOtherCollectionOrig, + index++ ); if ( otherOtherChild instanceof ChildWithBidirectionalManyToMany ) { - checkResult( listeners, listeners.getPreCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) otherOtherChild, index++ ); - checkResult( listeners, listeners.getPostCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) otherOtherChild, index++ ); + checkResult( listeners, listeners.getPreCollectionUpdateListener(), + (ChildWithBidirectionalManyToMany) otherOtherChild, index++ ); + checkResult( listeners, listeners.getPostCollectionUpdateListener(), + (ChildWithBidirectionalManyToMany) otherOtherChild, index++ ); } checkResult( listeners, listeners.getPreCollectionRecreateListener(), otherOtherParent, index++ ); checkResult( listeners, listeners.getPostCollectionRecreateListener(), otherOtherParent, index++ ); @@ -755,37 +808,31 @@ public void testMoveCollectionToDifferentParentFlushMoveToDifferentParent() { checkNumberOfResults( listeners, index ); } - protected ParentWithCollection createParentWithNullChildren(String parentName) { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - ParentWithCollection parent = createParent( parentName ); - s.persist( parent ); - tx.commit(); - s.close(); - return parent; + protected ParentWithCollection createParentWithNullChildren(String parentName, SessionFactoryScope scope) { + return scope.fromTransaction( s -> { + ParentWithCollection parent = createParent( parentName ); + s.persist( parent ); + return parent; + } ); } - protected ParentWithCollection createParentWithNoChildren(String parentName) { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - ParentWithCollection parent = createParent( parentName ); - parent.newChildren( createCollection() ); - s.persist( parent ); - tx.commit(); - s.close(); - return parent; + protected ParentWithCollection createParentWithNoChildren(String parentName, SessionFactoryScope scope) { + return scope.fromTransaction( s -> { + ParentWithCollection parent = createParent( parentName ); + parent.newChildren( createCollection() ); + s.persist( parent ); + return parent; + } ); } - protected ParentWithCollection createParentWithOneChild(String parentName, String ChildName) { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - ParentWithCollection parent = createParent( parentName ); - parent.newChildren( createCollection() ); - parent.addChild( ChildName ); - s.persist( parent ); - tx.commit(); - s.close(); - return parent; + protected ParentWithCollection createParentWithOneChild(String parentName, String ChildName, SessionFactoryScope scope) { + return scope.fromTransaction( s -> { + ParentWithCollection parent = createParent( parentName ); + parent.newChildren( createCollection() ); + parent.addChild( ChildName ); + s.persist( parent ); + return parent; + } ); } protected void checkResult(CollectionListeners listeners, @@ -794,6 +841,7 @@ protected void checkResult(CollectionListeners listeners, int index) { checkResult( listeners, listenerExpected, parent, parent.getChildren(), index ); } + protected void checkResult(CollectionListeners listeners, CollectionListeners.Listener listenerExpected, ChildWithBidirectionalManyToMany child, @@ -809,18 +857,18 @@ protected void checkResult(CollectionListeners listeners, assertSame( listenerExpected, listeners.getListenersCalled().get( index ) ); assertSame( ownerExpected, - ( ( AbstractCollectionEvent ) listeners.getEvents().get( index ) ).getAffectedOwnerOrNull() + ((AbstractCollectionEvent) listeners.getEvents().get( index )).getAffectedOwnerOrNull() ); assertEquals( ownerExpected.getId(), - ( ( AbstractCollectionEvent ) listeners.getEvents().get( index ) ).getAffectedOwnerIdOrNull() + ((AbstractCollectionEvent) listeners.getEvents().get( index )).getAffectedOwnerIdOrNull() ); assertEquals( ownerExpected.getClass().getName(), - ( ( AbstractCollectionEvent ) listeners.getEvents().get( index ) ).getAffectedOwnerEntityName() + ((AbstractCollectionEvent) listeners.getEvents().get( index )).getAffectedOwnerEntityName() ); assertSame( - collExpected, ( (AbstractCollectionEvent) listeners.getEvents().get( index ) ).getCollection() + collExpected, ((AbstractCollectionEvent) listeners.getEvents().get( index )).getCollection() ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/BrokenCollectionEventTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/BrokenCollectionEventTest.java index c673601400a8..d65ee6db1123 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/BrokenCollectionEventTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/BrokenCollectionEventTest.java @@ -3,31 +3,27 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.event.collection; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; - -import jakarta.persistence.criteria.CriteriaBuilder; -import jakarta.persistence.criteria.CriteriaQuery; -import org.junit.Test; - -import org.hibernate.Session; -import org.hibernate.Transaction; import org.hibernate.collection.spi.PersistentCollection; import org.hibernate.event.spi.AbstractCollectionEvent; -import org.hibernate.orm.test.event.collection.association.bidirectional.manytomany.ChildWithBidirectionalManyToMany; import org.hibernate.orm.test.event.collection.association.unidirectional.ParentWithCollectionOfEntities; -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.FailureExpected; -import org.hibernate.testing.RequiresDialectFeature; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.hibernate.testing.orm.junit.DialectFeatureChecks; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.FailureExpected; +import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import java.util.Collection; +import java.util.HashSet; +import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; /** * These tests are known to fail. When the functionality is corrected, the @@ -35,49 +31,18 @@ * * @author Gail Badner */ -@RequiresDialectFeature(DialectChecks.SupportsNoColumnInsert.class) -public class BrokenCollectionEventTest extends BaseCoreFunctionalTestCase { - - - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } - - @Override - public String[] getMappings() { - return new String[] { "event/collection/association/unidirectional/onetomany/UnidirectionalOneToManySetMapping.hbm.xml" }; - } - - @Override - protected void cleanupTest() { - ParentWithCollection dummyParent = createParent( "dummyParent" ); - dummyParent.setChildren( createCollection() ); - Child dummyChild = dummyParent.addChild( "dummyChild" ); - inTransaction( - s -> { - CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); - CriteriaQuery childrenCriteria = criteriaBuilder.createQuery( dummyChild.getClass() ); - childrenCriteria.from( dummyChild.getClass() ); - List children = s.createQuery( childrenCriteria ).list(); -// List children = s.createCriteria( dummyChild.getClass() ).list(); - - CriteriaQuery parentsCriteria = criteriaBuilder.createQuery( dummyParent.getClass() ); - childrenCriteria.from( dummyParent.getClass() ); - List parents = s.createQuery( parentsCriteria ).list(); +@DomainModel( + xmlMappings = "org/hibernate/orm/test/event/collection/association/unidirectional/onetomany/UnidirectionalOneToManySetMapping.hbm.xml" +) +@SessionFactory +@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsNoColumnInsert.class) +public class BrokenCollectionEventTest { -// List children = s.createCriteria( dummyChild.getClass() ).list(); -// List parents = s.createCriteria( dummyParent.getClass() ).list(); - for ( Iterator it = parents.iterator(); it.hasNext(); ) { - ParentWithCollection parent = ( ParentWithCollection ) it.next(); - parent.clearChildren(); - s.remove( parent ); - } - for ( Iterator it = children.iterator(); it.hasNext(); ) { - s.remove( it.next() ); - } - } - ); + @AfterEach + protected void cleanupTest(SessionFactoryScope scope) { + scope.inTransaction( s -> { + s.getSessionFactory().getSchemaManager().truncateMappedObjects(); + } ); } public ParentWithCollection createParent(String name) { @@ -85,67 +50,36 @@ public ParentWithCollection createParent(String name) { } public Collection createCollection() { - return new HashSet(); + return new HashSet<>(); } @Test - @FailureExpected( jiraKey = "unknown" ) - public void testUpdateDetachedParentNoChildrenToNull() { - CollectionListeners listeners = new CollectionListeners( sessionFactory() ); - ParentWithCollection parent = createParentWithNoChildren( "parent" ); + @FailureExpected(jiraKey = "unknown") + public void testUpdateDetachedParentNoChildrenToNull(SessionFactoryScope scope) { + CollectionListeners listeners = new CollectionListeners( scope.getSessionFactory() ); + ParentWithCollection parent = createParentWithNoChildren( scope, "parent" ); listeners.clear(); assertEquals( 0, parent.getChildren().size() ); - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Collection oldCollection = parent.getChildren(); - parent.newChildren( null ); - s.merge( parent ); - tx.commit(); - s.close(); - int index = 0; - checkResult( listeners, listeners.getPreCollectionRemoveListener(), parent, oldCollection, index++ ); - checkResult( listeners, listeners.getPostCollectionRemoveListener(), parent, oldCollection, index++ ); - // pre- and post- collection recreate events should be created when updating an entity with a "null" collection - checkResult( listeners, listeners.getPreCollectionRecreateListener(), parent, index++ ); - checkResult( listeners, listeners.getPostCollectionRecreateListener(), parent, index++ ); - checkNumberOfResults( listeners, index ); - } - - // The following fails for the same reason as testUpdateDetachedParentNoChildrenToNullFailureExpected - // When that issue is fixed, this one should also be fixed and moved into AbstractCollectionEventTest. - /* - public void testUpdateDetachedParentOneChildToNullFailureExpected() { - CollectionListeners listeners = new CollectionListeners( sessionFactory() ); - ParentWithCollection parent = createParentWithOneChild( "parent", "child" ); - Child oldChild = ( Child ) parent.getChildren().iterator().next(); - assertEquals( 1, parent.getChildren().size() ); - listeners.clear(); - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Collection oldCollection = parent.getChildren(); - parent.newChildren( null ); - s.update( parent ); - tx.commit(); - s.close(); + var oldCollection = scope.fromTransaction( s -> { + Collection oc = parent.getChildren(); + parent.newChildren( null ); + s.merge( parent ); + return oc; + } ); int index = 0; checkResult( listeners, listeners.getPreCollectionRemoveListener(), parent, oldCollection, index++ ); checkResult( listeners, listeners.getPostCollectionRemoveListener(), parent, oldCollection, index++ ); - if ( oldChild instanceof ChildWithBidirectionalManyToMany ) { - checkResult( listeners, listeners.getPreCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) oldChild, index++ ); - checkResult( listeners, listeners.getPostCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) oldChild, index++ ); - } // pre- and post- collection recreate events should be created when updating an entity with a "null" collection checkResult( listeners, listeners.getPreCollectionRecreateListener(), parent, index++ ); checkResult( listeners, listeners.getPostCollectionRecreateListener(), parent, index++ ); checkNumberOfResults( listeners, index ); } - */ @Test - @FailureExpected( jiraKey = "unknown" ) - public void testSaveParentNullChildren() { - CollectionListeners listeners = new CollectionListeners( sessionFactory() ); - ParentWithCollection parent = createParentWithNullChildren( "parent" ); + @FailureExpected(jiraKey = "unknown") + public void testSaveParentNullChildren(SessionFactoryScope scope) { + CollectionListeners listeners = new CollectionListeners( scope.getSessionFactory() ); + ParentWithCollection parent = createParentWithNullChildren( scope, "parent" ); assertNull( parent.getChildren() ); int index = 0; // pre- and post- collection recreate events should be created when creating an entity with a "null" collection @@ -153,31 +87,32 @@ public void testSaveParentNullChildren() { checkResult( listeners, listeners.getPostCollectionRecreateListener(), parent, index++ ); checkNumberOfResults( listeners, index ); listeners.clear(); - Session s = openSession(); - Transaction tx = s.beginTransaction(); - parent = ( ParentWithCollection ) s.get( parent.getClass(), parent.getId() ); - tx.commit(); - s.close(); - assertNotNull( parent.getChildren() ); + var p = scope.fromTransaction( s -> { + return (ParentWithCollection) s.get( parent.getClass(), parent.getId() ); + } ); + assertNotNull( p.getChildren() ); checkNumberOfResults( listeners, 0 ); } @Test - @FailureExpected( jiraKey = "unknown" ) - public void testUpdateParentNoChildrenToNull() { - CollectionListeners listeners = new CollectionListeners( sessionFactory() ); - ParentWithCollection parent = createParentWithNoChildren( "parent" ); + @FailureExpected(jiraKey = "unknown") + public void testUpdateParentNoChildrenToNull(SessionFactoryScope scope) { + CollectionListeners listeners = new CollectionListeners( scope.getSessionFactory() ); + ParentWithCollection parent = createParentWithNoChildren( scope, "parent" ); listeners.clear(); assertEquals( 0, parent.getChildren().size() ); - Session s = openSession(); - Transaction tx = s.beginTransaction(); - parent = ( ParentWithCollection ) s.get( parent.getClass(), parent.getId() ); - Collection oldCollection = parent.getChildren(); - parent.newChildren( null ); - tx.commit(); - s.close(); + Long id = parent.getId(); + + var data = scope.fromTransaction( s -> { + var p = (ParentWithCollection) s.get( ParentWithCollection.class, id ); + Collection oldCollection = p.getChildren(); + p.newChildren( null ); + return List.of( p, oldCollection ); + } ); int index = 0; - if ( ( (PersistentCollection) oldCollection ).wasInitialized() ) { + Collection oldCollection = (Collection) data.get( 1 ); + parent = (ParentWithCollection) data.get( 0 ); + if ( ((PersistentCollection) oldCollection).wasInitialized() ) { checkResult( listeners, listeners.getInitializeCollectionListener(), parent, oldCollection, index++ ); } checkResult( listeners, listeners.getPreCollectionRemoveListener(), parent, oldCollection, index++ ); @@ -188,114 +123,21 @@ public void testUpdateParentNoChildrenToNull() { checkNumberOfResults( listeners, index ); } - - // The following two tests fail for the same reason as testUpdateParentNoChildrenToNullFailureExpected - // When that issue is fixed, this one should also be fixed and moved into AbstractCollectionEventTest. - /* - public void testUpdateParentOneChildToNullFailureExpected() { - CollectionListeners listeners = new CollectionListeners( sessionFactory() ); - ParentWithCollection parent = createParentWithOneChild( "parent", "child" ); - Child oldChild = ( Child ) parent.getChildren().iterator().next(); - assertEquals( 1, parent.getChildren().size() ); - listeners.clear(); - Session s = openSession(); - Transaction tx = s.beginTransaction(); - parent = ( AbstractParentWithCollection ) s.get( parent.getClass(), parent.getId() ); - if ( oldChild instanceof ChildEntity ) { - oldChild = ( Child ) s.get( oldChild.getClass(), ( ( ChildEntity ) oldChild ).getId() ); - } - Collection oldCollection = parent.getChildren(); - parent.newChildren( null ); - tx.commit(); - s.close(); - int index = 0; - if ( ( ( PersistentCollection ) oldCollection ).wasInitialized() ) { - checkResult( listeners, listeners.getInitializeCollectionListener(), parent, oldCollection, index++ ); - } - ChildWithBidirectionalManyToMany oldChildWithManyToMany = null; - if ( oldChild instanceof ChildWithBidirectionalManyToMany ) { - oldChildWithManyToMany = ( ChildWithBidirectionalManyToMany ) oldChild; - if ( ( ( PersistentCollection ) oldChildWithManyToMany.getParents() ).wasInitialized() ) { - checkResult( listeners, listeners.getInitializeCollectionListener(), oldChildWithManyToMany, index++ ); - } - } - checkResult( listeners, listeners.getPreCollectionRemoveListener(), parent, oldCollection, index++ ); - checkResult( listeners, listeners.getPostCollectionRemoveListener(), parent, oldCollection, index++ ); - if ( oldChildWithManyToMany != null ) { - checkResult( listeners, listeners.getPreCollectionUpdateListener(), oldChildWithManyToMany, index++ ); - checkResult( listeners, listeners.getPostCollectionUpdateListener(), oldChildWithManyToMany, index++ ); - } - // pre- and post- collection recreate events should be created when updating an entity with a "null" collection - checkResult( listeners, listeners.getPreCollectionRecreateListener(), parent, index++ ); - checkResult( listeners, listeners.getPostCollectionRecreateListener(), parent, index++ ); - checkNumberOfResults( listeners, index ); + private ParentWithCollection createParentWithNullChildren(SessionFactoryScope scope, String parentName) { + return scope.fromTransaction( s -> { + ParentWithCollection parent = createParent( parentName ); + s.persist( parent ); + return parent; + } ); } - public void testUpdateMergedParentOneChildToNullFailureExpected() { - CollectionListeners listeners = new CollectionListeners( sessionFactory() ); - ParentWithCollection parent = createParentWithOneChild( "parent", "child" ); - assertEquals( 1, parent.getChildren().size() ); - listeners.clear(); - Session s = openSession(); - Transaction tx = s.beginTransaction(); - parent = ( AbstractParentWithCollection ) s.merge( parent ); - Collection oldCollection = parent.getChildren(); - parent.newChildren( null ); - tx.commit(); - s.close(); - int index = 0; - Child oldChild = ( Child ) oldCollection.iterator().next(); - ChildWithBidirectionalManyToMany oldChildWithManyToMany = null; - if ( oldChild instanceof ChildWithBidirectionalManyToMany ) { - oldChildWithManyToMany = ( ChildWithBidirectionalManyToMany ) oldChild; - if ( ( ( PersistentCollection ) oldChildWithManyToMany.getParents() ).wasInitialized() ) { - } - checkResult( listeners, listeners.getInitializeCollectionListener(), oldChildWithManyToMany, index++ ); - } - checkResult( listeners, listeners.getPreCollectionRemoveListener(), parent, oldCollection, index++ ); - checkResult( listeners, listeners.getPostCollectionRemoveListener(), parent, oldCollection, index++ ); - if ( oldChildWithManyToMany != null ) { - checkResult( listeners, listeners.getPreCollectionUpdateListener(), oldChildWithManyToMany, index++ ); - checkResult( listeners, listeners.getPostCollectionUpdateListener(), oldChildWithManyToMany, index++ ); - } - // pre- and post- collection recreate events should be created when updating an entity with a "null" collection - checkResult( listeners, listeners.getPreCollectionRecreateListener(), parent, index++ ); - checkResult( listeners, listeners.getPostCollectionRecreateListener(), parent, index++ ); - checkNumberOfResults( listeners, index ); - } - */ - - private ParentWithCollection createParentWithNullChildren(String parentName) { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - ParentWithCollection parent = createParent( parentName ); - s.persist( parent ); - tx.commit(); - s.close(); - return parent; - } - - private ParentWithCollection createParentWithNoChildren(String parentName) { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - ParentWithCollection parent = createParent( parentName ); - parent.setChildren( createCollection() ); - s.persist( parent ); - tx.commit(); - s.close(); - return parent; - } - - private ParentWithCollection createParentWithOneChild(String parentName, String ChildName) { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - ParentWithCollection parent = createParent( parentName ); - parent.setChildren( createCollection() ); - parent.addChild( ChildName ); - s.persist( parent ); - tx.commit(); - s.close(); - return parent; + private ParentWithCollection createParentWithNoChildren(SessionFactoryScope scope, String parentName) { + return scope.fromTransaction( s -> { + ParentWithCollection parent = createParent( parentName ); + parent.setChildren( createCollection() ); + s.persist( parent ); + return parent; + } ); } protected void checkResult(CollectionListeners listeners, @@ -304,12 +146,6 @@ protected void checkResult(CollectionListeners listeners, int index) { checkResult( listeners, listenerExpected, parent, parent.getChildren(), index ); } - protected void checkResult(CollectionListeners listeners, - CollectionListeners.Listener listenerExpected, - ChildWithBidirectionalManyToMany child, - int index) { - checkResult( listeners, listenerExpected, child, child.getParents(), index ); - } protected void checkResult(CollectionListeners listeners, CollectionListeners.Listener listenerExpected, @@ -319,18 +155,18 @@ protected void checkResult(CollectionListeners listeners, assertSame( listenerExpected, listeners.getListenersCalled().get( index ) ); assertSame( ownerExpected, - ( ( AbstractCollectionEvent ) listeners.getEvents().get( index ) ).getAffectedOwnerOrNull() + ((AbstractCollectionEvent) listeners.getEvents().get( index )).getAffectedOwnerOrNull() ); assertEquals( ownerExpected.getId(), - ( ( AbstractCollectionEvent ) listeners.getEvents().get( index ) ).getAffectedOwnerIdOrNull() + ((AbstractCollectionEvent) listeners.getEvents().get( index )).getAffectedOwnerIdOrNull() ); assertEquals( ownerExpected.getClass().getName(), - ( (AbstractCollectionEvent) listeners.getEvents().get( index ) ).getAffectedOwnerEntityName() + ((AbstractCollectionEvent) listeners.getEvents().get( index )).getAffectedOwnerEntityName() ); assertSame( - collExpected, ( ( AbstractCollectionEvent ) listeners.getEvents().get( index ) ).getCollection() + collExpected, ((AbstractCollectionEvent) listeners.getEvents().get( index )).getCollection() ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/AbstractAssociationCollectionEventTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/AbstractAssociationCollectionEventTest.java index fe2d52245526..2e38f6c18e32 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/AbstractAssociationCollectionEventTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/AbstractAssociationCollectionEventTest.java @@ -3,7 +3,6 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.event.collection.association; -import org.junit.Test; import org.hibernate.Session; import org.hibernate.Transaction; @@ -13,24 +12,26 @@ import org.hibernate.orm.test.event.collection.CollectionListeners; import org.hibernate.orm.test.event.collection.ParentWithCollection; import org.hibernate.orm.test.event.collection.association.bidirectional.manytomany.ChildWithBidirectionalManyToMany; - -import org.hibernate.testing.SkipForDialect; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.SkipForDialect; +import org.junit.jupiter.api.Test; /** * @author Gail Badner */ public abstract class AbstractAssociationCollectionEventTest extends AbstractCollectionEventTest { @Test - @SkipForDialect(value = HANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testDeleteParentButNotChild() { - CollectionListeners listeners = new CollectionListeners( sessionFactory() ); - ParentWithCollection parent = createParentWithOneChild( "parent", "child" ); - ChildEntity child = ( ChildEntity ) parent.getChildren().iterator().next(); + @SkipForDialect(dialectClass = HANADialect.class, + reason = " HANA doesn't support tables consisting of only a single auto-generated column") + public void testDeleteParentButNotChild(SessionFactoryScope scope) { + CollectionListeners listeners = new CollectionListeners( scope.getSessionFactory() ); + ParentWithCollection parent = createParentWithOneChild( "parent", "child", scope ); + ChildEntity child = (ChildEntity) parent.getChildren().iterator().next(); listeners.clear(); - Session s = openSession(); + Session s = scope.getSessionFactory().openSession(); Transaction tx = s.beginTransaction(); - parent = ( ParentWithCollection ) s.get( parent.getClass(), parent.getId() ); - child = ( ChildEntity ) s.get( child.getClass(), child.getId() ); + parent = (ParentWithCollection) s.get( parent.getClass(), parent.getId() ); + child = (ChildEntity) s.get( child.getClass(), child.getId() ); parent.removeChild( child ); s.remove( parent ); tx.commit(); @@ -38,13 +39,16 @@ public void testDeleteParentButNotChild() { int index = 0; checkResult( listeners, listeners.getInitializeCollectionListener(), parent, index++ ); if ( child instanceof ChildWithBidirectionalManyToMany ) { - checkResult( listeners, listeners.getInitializeCollectionListener(), ( ChildWithBidirectionalManyToMany ) child, index++ ); + checkResult( listeners, listeners.getInitializeCollectionListener(), + (ChildWithBidirectionalManyToMany) child, index++ ); } checkResult( listeners, listeners.getPreCollectionRemoveListener(), parent, index++ ); checkResult( listeners, listeners.getPostCollectionRemoveListener(), parent, index++ ); if ( child instanceof ChildWithBidirectionalManyToMany ) { - checkResult( listeners, listeners.getPreCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) child, index++ ); - checkResult( listeners, listeners.getPostCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) child, index++ ); + checkResult( listeners, listeners.getPreCollectionUpdateListener(), + (ChildWithBidirectionalManyToMany) child, index++ ); + checkResult( listeners, listeners.getPostCollectionUpdateListener(), + (ChildWithBidirectionalManyToMany) child, index++ ); } checkNumberOfResults( listeners, index ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/bidirectional/manytomany/BidirectionalManyToManyBagToSetCollectionEventTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/bidirectional/manytomany/BidirectionalManyToManyBagToSetCollectionEventTest.java index fcbffe0e89e5..3c60d1d60fac 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/bidirectional/manytomany/BidirectionalManyToManyBagToSetCollectionEventTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/bidirectional/manytomany/BidirectionalManyToManyBagToSetCollectionEventTest.java @@ -3,21 +3,21 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.event.collection.association.bidirectional.manytomany; + import java.util.ArrayList; import java.util.Collection; import org.hibernate.orm.test.event.collection.ParentWithCollection; import org.hibernate.orm.test.event.collection.association.AbstractAssociationCollectionEventTest; +import org.hibernate.testing.orm.junit.DomainModel; /** * * @author Gail Badner */ +@DomainModel( + xmlMappings = "org/hibernate/orm/test/event/collection/association/bidirectional/manytomany/BidirectionalManyToManyBagToSetMapping.hbm.xml") public class BidirectionalManyToManyBagToSetCollectionEventTest extends AbstractAssociationCollectionEventTest { - @Override - public String[] getMappings() { - return new String[] { "event/collection/association/bidirectional/manytomany/BidirectionalManyToManyBagToSetMapping.hbm.xml" }; - } @Override public ParentWithCollection createParent(String name) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/bidirectional/manytomany/BidirectionalManyToManySetToSetCollectionEventTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/bidirectional/manytomany/BidirectionalManyToManySetToSetCollectionEventTest.java index d4a4e8f69d74..55a7d9662014 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/bidirectional/manytomany/BidirectionalManyToManySetToSetCollectionEventTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/bidirectional/manytomany/BidirectionalManyToManySetToSetCollectionEventTest.java @@ -8,16 +8,14 @@ import org.hibernate.orm.test.event.collection.ParentWithCollection; import org.hibernate.orm.test.event.collection.association.AbstractAssociationCollectionEventTest; +import org.hibernate.testing.orm.junit.DomainModel; /** * * @author Gail Badner */ +@DomainModel(xmlMappings = "org/hibernate/orm/test/event/collection/association/bidirectional/manytomany/BidirectionalManyToManySetToSetMapping.hbm.xml") public class BidirectionalManyToManySetToSetCollectionEventTest extends AbstractAssociationCollectionEventTest { - @Override - public String[] getMappings() { - return new String[] { "event/collection/association/bidirectional/manytomany/BidirectionalManyToManySetToSetMapping.hbm.xml" }; - } @Override public ParentWithCollection createParent(String name) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/bidirectional/onetomany/BidirectionalOneToManyBagCollectionEventTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/bidirectional/onetomany/BidirectionalOneToManyBagCollectionEventTest.java index 8a6c36cd680d..0843c8f62c15 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/bidirectional/onetomany/BidirectionalOneToManyBagCollectionEventTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/bidirectional/onetomany/BidirectionalOneToManyBagCollectionEventTest.java @@ -9,16 +9,14 @@ import org.hibernate.orm.test.event.collection.Child; import org.hibernate.orm.test.event.collection.ParentWithCollection; import org.hibernate.orm.test.event.collection.association.AbstractAssociationCollectionEventTest; +import org.hibernate.testing.orm.junit.DomainModel; /** * * @author Gail Badner */ +@DomainModel(xmlMappings = "org/hibernate/orm/test/event/collection/association/bidirectional/onetomany/BidirectionalOneToManyBagMapping.hbm.xml") public class BidirectionalOneToManyBagCollectionEventTest extends AbstractAssociationCollectionEventTest { - @Override - public String[] getMappings() { - return new String[] { "event/collection/association/bidirectional/onetomany/BidirectionalOneToManyBagMapping.hbm.xml" }; - } @Override public ParentWithCollection createParent(String name) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/bidirectional/onetomany/BidirectionalOneToManyBagSubclassCollectionEventTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/bidirectional/onetomany/BidirectionalOneToManyBagSubclassCollectionEventTest.java index 1ede2256c682..9b6045015822 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/bidirectional/onetomany/BidirectionalOneToManyBagSubclassCollectionEventTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/bidirectional/onetomany/BidirectionalOneToManyBagSubclassCollectionEventTest.java @@ -5,15 +5,13 @@ package org.hibernate.orm.test.event.collection.association.bidirectional.onetomany; import org.hibernate.orm.test.event.collection.ParentWithCollection; +import org.hibernate.testing.orm.junit.DomainModel; /** * @author Gail Badner */ +@DomainModel(xmlMappings = "org/hibernate/orm/test/event/collection/association/bidirectional/onetomany/BidirectionalOneToManyBagSubclassMapping.hbm.xml") public class BidirectionalOneToManyBagSubclassCollectionEventTest extends BidirectionalOneToManyBagCollectionEventTest { - @Override - public String[] getMappings() { - return new String[] { "event/collection/association/bidirectional/onetomany/BidirectionalOneToManyBagSubclassMapping.hbm.xml" }; - } @Override public ParentWithCollection createParent(String name) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/bidirectional/onetomany/BidirectionalOneToManySetCollectionEventTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/bidirectional/onetomany/BidirectionalOneToManySetCollectionEventTest.java index 821f9b7c543c..27b7a2512f4f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/bidirectional/onetomany/BidirectionalOneToManySetCollectionEventTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/bidirectional/onetomany/BidirectionalOneToManySetCollectionEventTest.java @@ -9,15 +9,13 @@ import org.hibernate.orm.test.event.collection.Child; import org.hibernate.orm.test.event.collection.ParentWithCollection; import org.hibernate.orm.test.event.collection.association.AbstractAssociationCollectionEventTest; +import org.hibernate.testing.orm.junit.DomainModel; /** * @author Gail Badner */ +@DomainModel(xmlMappings = "org/hibernate/orm/test/event/collection/association/bidirectional/onetomany/BidirectionalOneToManySetMapping.hbm.xml") public class BidirectionalOneToManySetCollectionEventTest extends AbstractAssociationCollectionEventTest { - @Override - public String[] getMappings() { - return new String[] { "event/collection/association/bidirectional/onetomany/BidirectionalOneToManySetMapping.hbm.xml" }; - } @Override public ParentWithCollection createParent(String name) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/unidirectional/manytomany/UnidirectionalManyToManyBagCollectionEventTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/unidirectional/manytomany/UnidirectionalManyToManyBagCollectionEventTest.java index 5f460f736d65..4b156a22ca6b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/unidirectional/manytomany/UnidirectionalManyToManyBagCollectionEventTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/unidirectional/manytomany/UnidirectionalManyToManyBagCollectionEventTest.java @@ -12,15 +12,13 @@ import org.hibernate.orm.test.event.collection.ParentWithCollection; import org.hibernate.orm.test.event.collection.association.AbstractAssociationCollectionEventTest; import org.hibernate.orm.test.event.collection.association.unidirectional.ParentWithCollectionOfEntities; +import org.hibernate.testing.orm.junit.DomainModel; /** * @author Gail Badner */ +@DomainModel(xmlMappings = "org/hibernate/orm/test/event/collection/association/unidirectional/manytomany/UnidirectionalManyToManyBagMapping.hbm.xml") public class UnidirectionalManyToManyBagCollectionEventTest extends AbstractAssociationCollectionEventTest { - @Override - public String[] getMappings() { - return new String[] { "event/collection/association/unidirectional/manytomany/UnidirectionalManyToManyBagMapping.hbm.xml" }; - } @Override public ParentWithCollection createParent(String name) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/unidirectional/onetomany/UnidirectionalOneToManyBagCollectionEventTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/unidirectional/onetomany/UnidirectionalOneToManyBagCollectionEventTest.java index ad888b4ce961..f42a0ce4f78b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/unidirectional/onetomany/UnidirectionalOneToManyBagCollectionEventTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/unidirectional/onetomany/UnidirectionalOneToManyBagCollectionEventTest.java @@ -12,16 +12,14 @@ import org.hibernate.orm.test.event.collection.ParentWithCollection; import org.hibernate.orm.test.event.collection.association.AbstractAssociationCollectionEventTest; import org.hibernate.orm.test.event.collection.association.unidirectional.ParentWithCollectionOfEntities; +import org.hibernate.testing.orm.junit.DomainModel; /** * * @author Gail Badner */ +@DomainModel(xmlMappings = "org/hibernate/orm/test/event/collection/association/unidirectional/onetomany/UnidirectionalOneToManyBagMapping.hbm.xml") public class UnidirectionalOneToManyBagCollectionEventTest extends AbstractAssociationCollectionEventTest { - @Override - public String[] getMappings() { - return new String[] { "event/collection/association/unidirectional/onetomany/UnidirectionalOneToManyBagMapping.hbm.xml" }; - } @Override public ParentWithCollection createParent(String name) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/unidirectional/onetomany/UnidirectionalOneToManySetCollectionEventTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/unidirectional/onetomany/UnidirectionalOneToManySetCollectionEventTest.java index b3e193ea38dd..bde5fcea6d9d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/unidirectional/onetomany/UnidirectionalOneToManySetCollectionEventTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/unidirectional/onetomany/UnidirectionalOneToManySetCollectionEventTest.java @@ -10,15 +10,13 @@ import org.hibernate.orm.test.event.collection.ParentWithCollection; import org.hibernate.orm.test.event.collection.association.AbstractAssociationCollectionEventTest; import org.hibernate.orm.test.event.collection.association.unidirectional.ParentWithCollectionOfEntities; +import org.hibernate.testing.orm.junit.DomainModel; /** * @author Gail Badner */ +@DomainModel(xmlMappings = "org/hibernate/orm/test/event/collection/association/unidirectional/onetomany/UnidirectionalOneToManySetMapping.hbm.xml") public class UnidirectionalOneToManySetCollectionEventTest extends AbstractAssociationCollectionEventTest { - @Override - public String[] getMappings() { - return new String[] { "event/collection/association/unidirectional/onetomany/UnidirectionalOneToManySetMapping.hbm.xml" }; - } @Override public ParentWithCollection createParent(String name) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/detached/AggregatedCollectionEventListener.java b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/detached/AggregatedCollectionEventListener.java index b8d8d609e736..b9671de05fb6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/detached/AggregatedCollectionEventListener.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/detached/AggregatedCollectionEventListener.java @@ -133,6 +133,10 @@ public Serializable getSnapshotAtTimeOfEventHandling() { public static class IntegratorImpl implements Integrator { private AggregatedCollectionEventListener listener; + public IntegratorImpl() { + System.err.println( "created" ); + } + public AggregatedCollectionEventListener getListener() { if ( listener == null ) { throw new HibernateException( "Integrator not yet processed" ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/detached/BadMergeHandlingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/detached/BadMergeHandlingTest.java index f080ed9abef1..d5dce2e47602 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/detached/BadMergeHandlingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/detached/BadMergeHandlingTest.java @@ -4,95 +4,86 @@ */ package org.hibernate.orm.test.event.collection.detached; -import java.util.List; - -import org.hibernate.Session; -import org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl; -import org.hibernate.cfg.Configuration; -import org.hibernate.metamodel.CollectionClassification; - +import org.hibernate.cfg.AvailableSettings; +import org.hibernate.cfg.Environment; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.Test; + +import java.util.List; -import static org.hibernate.cfg.AvailableSettings.DEFAULT_LIST_SEMANTICS; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Steve Ebersole */ -@JiraKey( value = "HHH-7928" ) -public class BadMergeHandlingTest extends BaseCoreFunctionalTestCase { - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - configuration.setImplicitNamingStrategy( ImplicitNamingStrategyLegacyJpaImpl.INSTANCE ); - configuration.setProperty( DEFAULT_LIST_SEMANTICS, CollectionClassification.BAG ); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Character.class, Alias.class }; - } +@JiraKey(value = "HHH-7928") +@DomainModel( + annotatedClasses = { + Character.class, Alias.class + } +) +@ServiceRegistry( + settings = { + @Setting(name = AvailableSettings.IMPLICIT_NAMING_STRATEGY, value = "legacy-jpa"), + @Setting(name = Environment.DEFAULT_LIST_SEMANTICS, value = "bag"), // CollectionClassification.BAG + } +) +@SessionFactory +public class BadMergeHandlingTest { @Test - @JiraKey( value = "HHH-7928" ) - public void testMergeAndHold() { - Session s = openSession(); - s.beginTransaction(); - + @JiraKey(value = "HHH-7928") + public void testMergeAndHold(SessionFactoryScope scope) { Character paul = new Character( 1, "Paul Atreides" ); - s.persist( paul ); Character paulo = new Character( 2, "Paulo Atreides" ); - s.persist( paulo ); - Alias alias1 = new Alias( 1, "Paul Muad'Dib" ); - s.persist( alias1 ); - Alias alias2 = new Alias( 2, "Usul" ); - s.persist( alias2 ); - Alias alias3 = new Alias( 3, "The Preacher" ); - s.persist( alias3 ); - - s.getTransaction().commit(); - s.close(); - // set up relationships - s = openSession(); - s.beginTransaction(); - - // customer 1 - alias1.getCharacters().add( paul ); - s.merge( alias1 ); - alias2.getCharacters().add( paul ); - s.merge( alias2 ); - alias3.getCharacters().add( paul ); - s.merge( alias3 ); + scope.inTransaction( s -> { + s.persist( paul ); + s.persist( paulo ); + s.persist( alias1 ); + s.persist( alias2 ); + s.persist( alias3 ); - s.flush(); + } ); - // customer 2 - alias1.getCharacters().add( paulo ); - s.merge( alias1 ); - alias2.getCharacters().add( paulo ); - s.merge( alias2 ); - alias3.getCharacters().add( paulo ); - s.merge( alias3 ); - s.flush(); - - s.getTransaction().commit(); - s.close(); + // set up relationships + scope.inTransaction( s -> { + + // customer 1 + alias1.getCharacters().add( paul ); + s.merge( alias1 ); + alias2.getCharacters().add( paul ); + s.merge( alias2 ); + alias3.getCharacters().add( paul ); + s.merge( alias3 ); + + s.flush(); + + // customer 2 + alias1.getCharacters().add( paulo ); + s.merge( alias1 ); + alias2.getCharacters().add( paulo ); + s.merge( alias2 ); + alias3.getCharacters().add( paulo ); + s.merge( alias3 ); + s.flush(); + } ); // now try to read them back (I guess) - s = openSession(); - s.beginTransaction(); - List results = s.createQuery( "select c from Character c join c.aliases a where a.alias = :aParam" ) - .setParameter( "aParam", "Usul" ) - .list(); - assertEquals( 2, results.size() ); - s.getTransaction().commit(); - s.close(); + scope.inTransaction( s -> { + List results = s.createQuery( "select c from Character c join c.aliases a where a.alias = :aParam" ) + .setParameter( "aParam", "Usul" ) + .list(); + assertEquals( 2, results.size() ); + } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/detached/DetachedMultipleCollectionChangeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/detached/DetachedMultipleCollectionChangeTest.java index d5eab14e3fec..6e7ca59d8711 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/detached/DetachedMultipleCollectionChangeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/detached/DetachedMultipleCollectionChangeTest.java @@ -4,20 +4,26 @@ */ package org.hibernate.orm.test.event.collection.detached; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -import org.hibernate.Session; +import org.hibernate.cfg.AvailableSettings; +import org.hibernate.cfg.Environment; import org.hibernate.event.spi.AbstractCollectionEvent; import org.hibernate.event.spi.PostCollectionRecreateEvent; import org.hibernate.event.spi.PreCollectionRemoveEvent; import org.hibernate.event.spi.PreCollectionUpdateEvent; import org.hibernate.orm.test.event.collection.Entity; - +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -29,195 +35,170 @@ * * @author Erik-Berndt Scheper */ -@JiraKey( value = "HHH-6361" ) -public class DetachedMultipleCollectionChangeTest extends BaseCoreFunctionalTestCase { - - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } - - @Override - public String[] getMappings() { - return new String[] { "event/collection/detached/MultipleCollectionBagMapping.hbm.xml" }; - } +@JiraKey(value = "HHH-6361") +@DomainModel( + xmlMappings = "org/hibernate/orm/test/event/collection/detached/MultipleCollectionBagMapping.hbm.xml" +) +@ServiceRegistry( + settings = { + @Setting(name = AvailableSettings.IMPLICIT_NAMING_STRATEGY, value = "legacy-jpa"), + @Setting(name = Environment.DEFAULT_LIST_SEMANTICS, value = "bag"), // CollectionClassification.BAG + } +) +@SessionFactory +public class DetachedMultipleCollectionChangeTest { - @Override - protected void cleanupTest() { - Session s = null; - s = openSession(); - s.beginTransaction(); - s.createQuery("delete MultipleCollectionRefEntity1").executeUpdate(); - s.createQuery("delete MultipleCollectionRefEntity2").executeUpdate(); - s.createQuery("delete MultipleCollectionEntity").executeUpdate(); - s.getTransaction().commit(); - s.close(); + @AfterEach + public void tearDown(SessionFactoryScope scope) throws Exception { + scope.dropData(); } @Test - public void testMergeMultipleCollectionChangeEvents() { + public void testMergeMultipleCollectionChangeEvents(SessionFactoryScope scope) { MultipleCollectionListeners listeners = new MultipleCollectionListeners( - sessionFactory()); + scope.getSessionFactory() ); listeners.clear(); int eventCount = 0; - List oldRefentities1 - = new ArrayList(); - List oldRefentities2 - = new ArrayList(); + List oldRefentities1 = new ArrayList(); + List oldRefentities2 = new ArrayList(); - Session s = openSession(); - s.beginTransaction(); + final AtomicReference mce = new AtomicReference<>( new MultipleCollectionEntity() ); + scope.inTransaction( s -> { + mce.get().setText( "MultipleCollectionEntity-1" ); + s.persist( mce.get() ); + } ); - MultipleCollectionEntity mce = new MultipleCollectionEntity(); - mce.setText("MultipleCollectionEntity-1"); + checkListener( listeners, listeners.getPreCollectionRecreateListener(), + mce.get(), oldRefentities1, eventCount++ ); + checkListener( listeners, listeners.getPostCollectionRecreateListener(), + mce.get(), oldRefentities1, eventCount++ ); + checkListener( listeners, listeners.getPreCollectionRecreateListener(), + mce.get(), oldRefentities2, eventCount++ ); + checkListener( listeners, listeners.getPostCollectionRecreateListener(), + mce.get(), oldRefentities2, eventCount++ ); + checkEventCount( listeners, eventCount ); - s.persist(mce); - s.getTransaction().commit(); - checkListener(listeners, listeners.getPreCollectionRecreateListener(), - mce, oldRefentities1, eventCount++); - checkListener(listeners, listeners.getPostCollectionRecreateListener(), - mce, oldRefentities1, eventCount++); - checkListener(listeners, listeners.getPreCollectionRecreateListener(), - mce, oldRefentities2, eventCount++); - checkListener(listeners, listeners.getPostCollectionRecreateListener(), - mce, oldRefentities2, eventCount++); - checkEventCount(listeners, eventCount); - - s.close(); - - Long mceId1 = mce.getId(); - assertNotNull(mceId1); + Long mceId1 = mce.get().getId(); + assertNotNull( mceId1 ); // add new entities to both collections - MultipleCollectionEntity prevMce = mce.deepCopy(); + MultipleCollectionEntity prevMce = mce.get().deepCopy(); oldRefentities1 = prevMce.getRefEntities1(); oldRefentities2 = prevMce.getRefEntities2(); listeners.clear(); eventCount = 0; - s = openSession(); - s.beginTransaction(); - MultipleCollectionRefEntity1 re1_1 = new MultipleCollectionRefEntity1(); - re1_1.setText("MultipleCollectionRefEntity1-1"); - re1_1.setMultipleCollectionEntity(mce); - MultipleCollectionRefEntity1 re1_2 = new MultipleCollectionRefEntity1(); - re1_2.setText("MultipleCollectionRefEntity1-2"); - re1_2.setMultipleCollectionEntity(mce); - mce.addRefEntity1(re1_1); - mce.addRefEntity1(re1_2); + mce.set( scope.fromTransaction( s -> { + re1_1.setText( "MultipleCollectionRefEntity1-1" ); + re1_1.setMultipleCollectionEntity( mce.get() ); - mce = (MultipleCollectionEntity) s.merge(mce); + re1_2.setText( "MultipleCollectionRefEntity1-2" ); + re1_2.setMultipleCollectionEntity( mce.get() ); - s.getTransaction().commit(); - s.close(); + mce.get().addRefEntity1( re1_1 ); + mce.get().addRefEntity1( re1_2 ); - checkListener(listeners, listeners.getInitializeCollectionListener(), - mce, null, eventCount++); - checkListener(listeners, listeners.getPreCollectionUpdateListener(), - mce, oldRefentities1, eventCount++); - checkListener(listeners, listeners.getPostCollectionUpdateListener(), - mce, mce.getRefEntities1(), eventCount++); + return s.merge( mce.get() ); - s = openSession(); - s.beginTransaction(); + } ) ); - MultipleCollectionRefEntity2 re2_1 = new MultipleCollectionRefEntity2(); - re2_1.setText("MultipleCollectionRefEntity2-1"); - re2_1.setMultipleCollectionEntity(mce); + checkListener( listeners, listeners.getInitializeCollectionListener(), + mce.get(), null, eventCount++ ); + checkListener( listeners, listeners.getPreCollectionUpdateListener(), + mce.get(), oldRefentities1, eventCount++ ); + checkListener( listeners, listeners.getPostCollectionUpdateListener(), + mce.get(), mce.get().getRefEntities1(), eventCount++ ); + MultipleCollectionRefEntity2 re2_1 = new MultipleCollectionRefEntity2(); MultipleCollectionRefEntity2 re2_2 = new MultipleCollectionRefEntity2(); - re2_2.setText("MultipleCollectionRefEntity2-2"); - re2_2.setMultipleCollectionEntity(mce); - mce.addRefEntity2(re2_1); - mce.addRefEntity2(re2_2); + mce.set( scope.fromTransaction( s -> { + re2_1.setText( "MultipleCollectionRefEntity2-1" ); + re2_1.setMultipleCollectionEntity( mce.get() ); - mce = (MultipleCollectionEntity) s.merge(mce); + re2_2.setText( "MultipleCollectionRefEntity2-2" ); + re2_2.setMultipleCollectionEntity( mce.get() ); - s.getTransaction().commit(); + mce.get().addRefEntity2( re2_1 ); + mce.get().addRefEntity2( re2_2 ); - checkListener(listeners, listeners.getInitializeCollectionListener(), - mce, null, eventCount++); - checkListener(listeners, listeners.getPreCollectionUpdateListener(), - mce, oldRefentities2, eventCount++); - checkListener(listeners, listeners.getPostCollectionUpdateListener(), - mce, mce.getRefEntities2(), eventCount++); - checkEventCount(listeners, eventCount); + return s.merge( mce.get() ); + } ) ); - s.close(); + checkListener( listeners, listeners.getInitializeCollectionListener(), + mce.get(), null, eventCount++ ); + checkListener( listeners, listeners.getPreCollectionUpdateListener(), + mce.get(), oldRefentities2, eventCount++ ); + checkListener( listeners, listeners.getPostCollectionUpdateListener(), + mce.get(), mce.get().getRefEntities2(), eventCount++ ); + checkEventCount( listeners, eventCount ); - for (MultipleCollectionRefEntity1 refEnt1 : mce.getRefEntities1()) { - assertNotNull(refEnt1.getId()); + for ( MultipleCollectionRefEntity1 refEnt1 : mce.get().getRefEntities1() ) { + assertNotNull( refEnt1.getId() ); } - for (MultipleCollectionRefEntity2 refEnt2 : mce.getRefEntities2()) { - assertNotNull(refEnt2.getId()); + for ( MultipleCollectionRefEntity2 refEnt2 : mce.get().getRefEntities2() ) { + assertNotNull( refEnt2.getId() ); } // remove and add entities in both collections - prevMce = mce.deepCopy(); + prevMce = mce.get().deepCopy(); oldRefentities1 = prevMce.getRefEntities1(); oldRefentities2 = prevMce.getRefEntities2(); listeners.clear(); eventCount = 0; - s = openSession(); - s.beginTransaction(); - - assertEquals(2, mce.getRefEntities1().size()); - assertEquals(2, mce.getRefEntities2().size()); - - mce.removeRefEntity1(re1_2); + mce.set( scope.fromTransaction( s -> { + assertEquals( 2, mce.get().getRefEntities1().size() ); + assertEquals( 2, mce.get().getRefEntities2().size() ); - MultipleCollectionRefEntity1 re1_3 = new MultipleCollectionRefEntity1(); - re1_3.setText("MultipleCollectionRefEntity1-3"); - re1_3.setMultipleCollectionEntity(mce); - mce.addRefEntity1(re1_3); + mce.get().removeRefEntity1( re1_2 ); - mce = (MultipleCollectionEntity) s.merge(mce); + MultipleCollectionRefEntity1 re1_3 = new MultipleCollectionRefEntity1(); + re1_3.setText( "MultipleCollectionRefEntity1-3" ); + re1_3.setMultipleCollectionEntity( mce.get() ); + mce.get().addRefEntity1( re1_3 ); - s.getTransaction().commit(); - s.close(); + return s.merge( mce.get() ); - checkListener(listeners, listeners.getInitializeCollectionListener(), - mce, null, eventCount++); - checkListener(listeners, listeners.getPreCollectionUpdateListener(), - mce, oldRefentities1, eventCount++); - checkListener(listeners, listeners.getPostCollectionUpdateListener(), - mce, mce.getRefEntities1(), eventCount++); + } ) ); - s = openSession(); - s.beginTransaction(); + checkListener( listeners, listeners.getInitializeCollectionListener(), + mce.get(), null, eventCount++ ); + checkListener( listeners, listeners.getPreCollectionUpdateListener(), + mce.get(), oldRefentities1, eventCount++ ); + checkListener( listeners, listeners.getPostCollectionUpdateListener(), + mce.get(), mce.get().getRefEntities1(), eventCount++ ); - mce.removeRefEntity2(re2_2); + mce.set( scope.fromTransaction( s -> { - MultipleCollectionRefEntity2 re2_3 = new MultipleCollectionRefEntity2(); - re2_3.setText("MultipleCollectionRefEntity2-3"); - re2_3.setMultipleCollectionEntity(mce); - mce.addRefEntity2(re2_3); + mce.get().removeRefEntity2( re2_2 ); - mce = (MultipleCollectionEntity) s.merge(mce); + MultipleCollectionRefEntity2 re2_3 = new MultipleCollectionRefEntity2(); + re2_3.setText( "MultipleCollectionRefEntity2-3" ); + re2_3.setMultipleCollectionEntity( mce.get() ); + mce.get().addRefEntity2( re2_3 ); - s.getTransaction().commit(); + return s.merge( mce.get() ); - checkListener(listeners, listeners.getInitializeCollectionListener(), - mce, null, eventCount++); - checkListener(listeners, listeners.getPreCollectionUpdateListener(), - mce, oldRefentities2, eventCount++); - checkListener(listeners, listeners.getPostCollectionUpdateListener(), - mce, mce.getRefEntities2(), eventCount++); + } ) ); - checkEventCount(listeners, eventCount); + checkListener( listeners, listeners.getInitializeCollectionListener(), + mce.get(), null, eventCount++ ); + checkListener( listeners, listeners.getPreCollectionUpdateListener(), + mce.get(), oldRefentities2, eventCount++ ); + checkListener( listeners, listeners.getPostCollectionUpdateListener(), + mce.get(), mce.get().getRefEntities2(), eventCount++ ); - s.close(); + checkEventCount( listeners, eventCount ); } protected void checkListener( @@ -227,33 +208,33 @@ protected void checkListener( List expectedCollectionEntrySnapshot, int index) { AbstractCollectionEvent event = listeners - .getEvents().get(index); + .getEvents().get( index ); - assertSame(listenerExpected, listeners.getListenersCalled().get(index)); - assertEquals(ownerExpected, event.getAffectedOwnerOrNull()); - assertEquals(ownerExpected.getId(), event.getAffectedOwnerIdOrNull()); - assertEquals(ownerExpected.getClass().getName(), - event.getAffectedOwnerEntityName()); + assertSame( listenerExpected, listeners.getListenersCalled().get( index ) ); + assertEquals( ownerExpected, event.getAffectedOwnerOrNull() ); + assertEquals( ownerExpected.getId(), event.getAffectedOwnerIdOrNull() ); + assertEquals( ownerExpected.getClass().getName(), + event.getAffectedOwnerEntityName() ); - if (event instanceof PreCollectionUpdateEvent) { - Serializable snapshot = listeners.getSnapshots().get(index); - assertEquals(expectedCollectionEntrySnapshot, snapshot); + if ( event instanceof PreCollectionUpdateEvent ) { + Serializable snapshot = listeners.getSnapshots().get( index ); + assertEquals( expectedCollectionEntrySnapshot, snapshot ); } - if (event instanceof PreCollectionRemoveEvent) { - Serializable snapshot = listeners.getSnapshots().get(index); - assertEquals(expectedCollectionEntrySnapshot, snapshot); + if ( event instanceof PreCollectionRemoveEvent ) { + Serializable snapshot = listeners.getSnapshots().get( index ); + assertEquals( expectedCollectionEntrySnapshot, snapshot ); } - if (event instanceof PostCollectionRecreateEvent) { - Serializable snapshot = listeners.getSnapshots().get(index); - assertEquals(expectedCollectionEntrySnapshot, snapshot); + if ( event instanceof PostCollectionRecreateEvent ) { + Serializable snapshot = listeners.getSnapshots().get( index ); + assertEquals( expectedCollectionEntrySnapshot, snapshot ); } } private void checkEventCount(MultipleCollectionListeners listeners, - int nEventsExpected) { - assertEquals(nEventsExpected, listeners.getListenersCalled().size()); - assertEquals(nEventsExpected, listeners.getEvents().size()); + int nEventsExpected) { + assertEquals( nEventsExpected, listeners.getListenersCalled().size() ); + assertEquals( nEventsExpected, listeners.getEvents().size() ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/detached/MergeCollectionEventTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/detached/MergeCollectionEventTest.java index 487532f4801b..70b615653cdf 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/detached/MergeCollectionEventTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/detached/MergeCollectionEventTest.java @@ -4,82 +4,81 @@ */ package org.hibernate.orm.test.event.collection.detached; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.hibernate.Session; -import org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl; -import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; -import org.hibernate.cfg.Configuration; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.spi.BootstrapContext; +import org.hibernate.cfg.AvailableSettings; +import org.hibernate.cfg.Environment; +import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.event.spi.AbstractCollectionEvent; import org.hibernate.event.spi.PostCollectionRecreateEvent; import org.hibernate.event.spi.PostCollectionUpdateEvent; import org.hibernate.event.spi.PreCollectionRecreateEvent; import org.hibernate.event.spi.PreCollectionRemoveEvent; import org.hibernate.event.spi.PreCollectionUpdateEvent; -import org.hibernate.metamodel.CollectionClassification; - +import org.hibernate.integrator.spi.Integrator; +import org.hibernate.service.spi.SessionFactoryServiceRegistry; +import org.hibernate.testing.orm.junit.BootstrapServiceRegistry; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; -import static org.hibernate.cfg.AvailableSettings.DEFAULT_LIST_SEMANTICS; import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; import static org.junit.Assert.assertEquals; /** * @author Steve Ebersole */ -@JiraKey( value = "HHH-7928" ) -public class MergeCollectionEventTest extends BaseCoreFunctionalTestCase { - - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - configuration.setImplicitNamingStrategy( ImplicitNamingStrategyLegacyJpaImpl.INSTANCE ); - configuration.setProperty( DEFAULT_LIST_SEMANTICS, CollectionClassification.BAG ); - } +@JiraKey(value = "HHH-7928") +@DomainModel( + annotatedClasses = { + Character.class, Alias.class + } +) +@ServiceRegistry( + settings = { + @Setting(name = AvailableSettings.IMPLICIT_NAMING_STRATEGY, value = "legacy-jpa"), + @Setting(name = Environment.DEFAULT_LIST_SEMANTICS, value = "bag"), // CollectionClassification.BAG + } +) +@BootstrapServiceRegistry(integrators = MergeCollectionEventTest.ConfigurerIntegrator.class) +@SessionFactory +public class MergeCollectionEventTest { - private AggregatedCollectionEventListener.IntegratorImpl collectionListenerIntegrator = - new AggregatedCollectionEventListener.IntegratorImpl(); + private static AggregatedCollectionEventListener.IntegratorImpl collectionListenerIntegrator; - @Before - public void resetListener() { + @BeforeEach + void setUp(SessionFactoryScope scope) { + SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); collectionListenerIntegrator.getListener().reset(); } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Character.class, Alias.class }; - } - - @Override - protected void prepareBootstrapRegistryBuilder(BootstrapServiceRegistryBuilder builder) { - super.prepareBootstrapRegistryBuilder( builder ); - builder.applyIntegrator( collectionListenerIntegrator ); - } - - @Override - protected void cleanupTestData() throws Exception { - sessionFactory().getSchemaManager().truncate(); + @AfterEach + void cleanupTestData(SessionFactoryScope scope) throws Exception { + scope.getSessionFactory().getSchemaManager().truncate(); } @Test - public void testCollectionEventHandlingOnMerge() { + public void testCollectionEventHandlingOnMerge(SessionFactoryScope scope) { final AggregatedCollectionEventListener listener = collectionListenerIntegrator.getListener(); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // This first bit really is just preparing the entities. There is generally no collection // events of real interest during this part - Session s = openSession(); - s.beginTransaction(); Character paul = new Character( 1, "Paul Atreides" ); - s.persist( paul ); - s.getTransaction().commit(); - s.close(); + scope.inTransaction( s -> { + s.persist( paul ); + } ); assertEquals( 2, listener.getEventEntryList().size() ); checkListener( 0, PreCollectionRecreateEvent.class, paul, Collections.EMPTY_LIST ); @@ -87,12 +86,10 @@ public void testCollectionEventHandlingOnMerge() { listener.reset(); - s = openSession(); - s.beginTransaction(); Character paulo = new Character( 2, "Paulo Atreides" ); - s.persist( paulo ); - s.getTransaction().commit(); - s.close(); + scope.inTransaction( s -> { + s.persist( paulo ); + } ); assertEquals( 2, listener.getEventEntryList().size() ); checkListener( 0, PreCollectionRecreateEvent.class, paulo, Collections.EMPTY_LIST ); @@ -100,12 +97,10 @@ public void testCollectionEventHandlingOnMerge() { listener.reset(); - s = openSession(); - s.beginTransaction(); Alias alias1 = new Alias( 1, "Paul Muad'Dib" ); - s.persist( alias1 ); - s.getTransaction().commit(); - s.close(); + scope.inTransaction( s -> { + s.persist( alias1 ); + } ); assertEquals( 2, listener.getEventEntryList().size() ); checkListener( 0, PreCollectionRecreateEvent.class, alias1, Collections.EMPTY_LIST ); @@ -113,12 +108,10 @@ public void testCollectionEventHandlingOnMerge() { listener.reset(); - s = openSession(); - s.beginTransaction(); Alias alias2 = new Alias( 2, "Usul" ); - s.persist( alias2 ); - s.getTransaction().commit(); - s.close(); + scope.inTransaction( s -> { + s.persist( alias2 ); + } ); assertEquals( 2, listener.getEventEntryList().size() ); checkListener( 0, PreCollectionRecreateEvent.class, alias2, Collections.EMPTY_LIST ); @@ -137,48 +130,46 @@ public void testCollectionEventHandlingOnMerge() { paulo.associateAlias( alias1 ); paulo.associateAlias( alias2 ); - s = openSession(); - s.beginTransaction(); - s.merge( alias1 ); + scope.inTransaction( s -> { + s.merge( alias1 ); - assertEquals( 0, listener.getEventEntryList().size() ); + assertEquals( 0, listener.getEventEntryList().size() ); - // this is where HHH-7928 (problem with HHH-6361 fix) shows up... - s.flush(); + // this is where HHH-7928 (problem with HHH-6361 fix) shows up... + s.flush(); - assertEquals( 8, listener.getEventEntryList().size() ); // 4 collections x 2 events per - checkListener( 0, PreCollectionUpdateEvent.class, alias1, Collections.EMPTY_LIST ); - checkListener( 1, PostCollectionUpdateEvent.class, alias1, alias1.getCharacters() ); - checkListener( 2, PreCollectionUpdateEvent.class, paul, Collections.EMPTY_LIST ); - checkListener( 3, PostCollectionUpdateEvent.class, paul, paul.getAliases() ); - checkListener( 4, PreCollectionUpdateEvent.class, alias2, Collections.EMPTY_LIST ); - checkListener( 5, PostCollectionUpdateEvent.class, alias2, alias2.getCharacters() ); - checkListener( 6, PreCollectionUpdateEvent.class, paulo, Collections.EMPTY_LIST ); - checkListener( 7, PostCollectionUpdateEvent.class, paulo, paul.getAliases() ); + assertEquals( 8, listener.getEventEntryList().size() ); // 4 collections x 2 events per + checkListener( 0, PreCollectionUpdateEvent.class, alias1, Collections.EMPTY_LIST ); + checkListener( 1, PostCollectionUpdateEvent.class, alias1, alias1.getCharacters() ); + checkListener( 2, PreCollectionUpdateEvent.class, paul, Collections.EMPTY_LIST ); + checkListener( 3, PostCollectionUpdateEvent.class, paul, paul.getAliases() ); + checkListener( 4, PreCollectionUpdateEvent.class, alias2, Collections.EMPTY_LIST ); + checkListener( 5, PostCollectionUpdateEvent.class, alias2, alias2.getCharacters() ); + checkListener( 6, PreCollectionUpdateEvent.class, paulo, Collections.EMPTY_LIST ); + checkListener( 7, PostCollectionUpdateEvent.class, paulo, paul.getAliases() ); - List alias1CharactersSnapshot = copy( alias1.getCharacters() ); - List alias2CharactersSnapshot = copy( alias2.getCharacters() ); + List alias1CharactersSnapshot = copy( alias1.getCharacters() ); + List alias2CharactersSnapshot = copy( alias2.getCharacters() ); - listener.reset(); + listener.reset(); - s.merge( alias2 ); + s.merge( alias2 ); - assertEquals( 0, listener.getEventEntryList().size() ); + assertEquals( 0, listener.getEventEntryList().size() ); - s.flush(); + s.flush(); - assertEquals( 8, listener.getEventEntryList().size() ); // 4 collections x 2 events per - checkListener( 0, PreCollectionUpdateEvent.class, alias1, alias1CharactersSnapshot ); - checkListener( 1, PostCollectionUpdateEvent.class, alias1, alias1CharactersSnapshot ); + assertEquals( 8, listener.getEventEntryList().size() ); // 4 collections x 2 events per + checkListener( 0, PreCollectionUpdateEvent.class, alias1, alias1CharactersSnapshot ); + checkListener( 1, PostCollectionUpdateEvent.class, alias1, alias1CharactersSnapshot ); // checkListener( 2, PreCollectionUpdateEvent.class, paul, Collections.EMPTY_LIST ); // checkListener( 3, PostCollectionUpdateEvent.class, paul, paul.getAliases() ); - checkListener( 4, PreCollectionUpdateEvent.class, alias2, alias2CharactersSnapshot ); - checkListener( 5, PostCollectionUpdateEvent.class, alias2, alias2.getCharacters() ); + checkListener( 4, PreCollectionUpdateEvent.class, alias2, alias2CharactersSnapshot ); + checkListener( 5, PostCollectionUpdateEvent.class, alias2, alias2.getCharacters() ); // checkListener( 6, PreCollectionUpdateEvent.class, paulo, Collections.EMPTY_LIST ); // checkListener( 7, PostCollectionUpdateEvent.class, paulo, paul.getAliases() ); - s.getTransaction().commit(); - s.close(); + } ); // // checkListener(listeners, listeners.getInitializeCollectionListener(), @@ -208,8 +199,8 @@ protected void checkListener( assertEquals( expectedOwner.getId(), event.getAffectedOwnerIdOrNull() ); if ( event instanceof PreCollectionUpdateEvent - || event instanceof PreCollectionRemoveEvent - || event instanceof PostCollectionRecreateEvent ) { + || event instanceof PreCollectionRemoveEvent + || event instanceof PostCollectionRecreateEvent ) { List snapshot = (List) eventEntry.getSnapshotAtTimeOfEventHandling(); assertEquals( expectedCollectionEntrySnapshot.size(), snapshot.size() ); for ( int i = 0; i < expectedCollectionEntrySnapshot.size(); i++ ) { @@ -226,4 +217,21 @@ private List copy(List source) { copy.addAll( source ); return copy; } + + public static class ConfigurerIntegrator implements Integrator { + public ConfigurerIntegrator() { + collectionListenerIntegrator = new AggregatedCollectionEventListener.IntegratorImpl(); + } + + @Override + public void integrate(Metadata metadata, BootstrapContext bootstrapContext, SessionFactoryImplementor sessionFactory) { + collectionListenerIntegrator.integrate( metadata, bootstrapContext, sessionFactory ); + } + + @Override + public void disintegrate(SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) { + collectionListenerIntegrator.disintegrate( sessionFactory, serviceRegistry ); + collectionListenerIntegrator = null; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/values/ValuesBagCollectionEventTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/values/ValuesBagCollectionEventTest.java index dbd4f42b8cd1..8fe62820e451 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/values/ValuesBagCollectionEventTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/values/ValuesBagCollectionEventTest.java @@ -9,16 +9,14 @@ import org.hibernate.orm.test.event.collection.AbstractCollectionEventTest; import org.hibernate.orm.test.event.collection.ParentWithCollection; +import org.hibernate.testing.orm.junit.DomainModel; /** * * @author Gail Badner */ +@DomainModel(xmlMappings = "org/hibernate/orm/test/event/collection/values/ValuesBagMapping.hbm.xml") public class ValuesBagCollectionEventTest extends AbstractCollectionEventTest { - @Override - public String[] getMappings() { - return new String[] { "event/collection/values/ValuesBagMapping.hbm.xml" }; - } @Override public ParentWithCollection createParent(String name) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/event/entity/MergeListPreAndPostPersistTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/event/entity/MergeListPreAndPostPersistTest.java index cae2ee7cc653..c5c4b74ffac1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/event/entity/MergeListPreAndPostPersistTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/event/entity/MergeListPreAndPostPersistTest.java @@ -6,13 +6,13 @@ import java.util.ArrayList; import java.util.List; + import jakarta.persistence.Basic; import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.OneToMany; -import org.hibernate.Session; import org.hibernate.annotations.processing.Exclude; import org.hibernate.event.service.spi.EventListenerRegistry; import org.hibernate.event.spi.EventType; @@ -22,29 +22,31 @@ import org.hibernate.event.spi.PreInsertEventListener; import org.hibernate.persister.entity.EntityPersister; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Gail Badner */ -@JiraKey( value = "HHH-9979") +@JiraKey(value = "HHH-9979") @Exclude -public class MergeListPreAndPostPersistTest extends BaseCoreFunctionalTestCase { - - protected Class[] getAnnotatedClasses() { - return new Class[] { - Order.class, - Item.class - }; - } +@DomainModel( + annotatedClasses = { + MergeListPreAndPostPersistTest.Order.class, + MergeListPreAndPostPersistTest.Item.class + } +) +@SessionFactory +public class MergeListPreAndPostPersistTest { @Test - @JiraKey( value = "HHH-9979") - public void testAllPropertiesCopied() { + @JiraKey(value = "HHH-9979") + public void testAllPropertiesCopied(SessionFactoryScope scope) { final Order order = new Order(); order.id = 1L; order.name = "order"; @@ -53,23 +55,19 @@ public void testAllPropertiesCopied() { item.name = "item"; order.items.add( item ); - addEntityListeners( order ); + addEntityListeners( scope, order ); - Session s = openSession(); - s.getTransaction().begin(); - s.merge( order ); - s.getTransaction().commit(); - s.close(); + scope.inTransaction( s -> { + s.merge( order ); + } ); - s = openSession(); - s.getTransaction().begin(); - s.remove( order ); - s.getTransaction().commit(); - s.close(); + scope.inTransaction( s -> { + s.remove( order ); + } ); } @Entity(name = "`Order`") - private static class Order { + static class Order { @Id public Long id; @@ -101,7 +99,7 @@ public int hashCode() { } @Entity(name = "Item") - private static class Item { + static class Item { @Id public Long id; @@ -128,17 +126,17 @@ public int hashCode() { } } - private void addEntityListeners(final Order order) { + private void addEntityListeners(SessionFactoryScope scope, final Order order) { - EventListenerRegistry registry = sessionFactory().getEventListenerRegistry(); + EventListenerRegistry registry = scope.getSessionFactory().getEventListenerRegistry(); registry.setListeners( EventType.PRE_INSERT, new PreInsertEventListener() { @Override public boolean onPreInsert(PreInsertEvent event) { if ( event.getEntity() instanceof Order ) { - assertEquals( order, event.getEntity()); - assertEquals( order.items, ( (Order) event.getEntity() ).items ); + assertEquals( order, event.getEntity() ); + assertEquals( order.items, ((Order) event.getEntity()).items ); } return false; } @@ -150,8 +148,8 @@ public boolean onPreInsert(PreInsertEvent event) { new PostInsertEventListener() { public void onPostInsert(PostInsertEvent event) { if ( event.getEntity() instanceof Order ) { - assertEquals( order, event.getEntity()); - assertEquals( order.items, ( (Order) event.getEntity() ).items ); + assertEquals( order, event.getEntity() ); + assertEquals( order.items, ((Order) event.getEntity()).items ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/event/entity/MergeListPreAndPostPersistWithIdentityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/event/entity/MergeListPreAndPostPersistWithIdentityTest.java index 588deeb40602..39fd0d18ead6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/event/entity/MergeListPreAndPostPersistWithIdentityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/event/entity/MergeListPreAndPostPersistWithIdentityTest.java @@ -4,8 +4,6 @@ */ package org.hibernate.orm.test.event.entity; -import java.util.ArrayList; -import java.util.List; import jakarta.persistence.Basic; import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; @@ -13,10 +11,6 @@ import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.OneToMany; - -import org.junit.Test; - -import org.hibernate.Session; import org.hibernate.event.service.spi.EventListenerRegistry; import org.hibernate.event.spi.EventType; import org.hibernate.event.spi.PostInsertEvent; @@ -24,32 +18,38 @@ import org.hibernate.event.spi.PreInsertEvent; import org.hibernate.event.spi.PreInsertEventListener; import org.hibernate.persister.entity.EntityPersister; -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.FailureExpected; -import org.hibernate.testing.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.DialectFeatureChecks; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.FailureExpected; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Gail Badner */ -@JiraKey( value = "HHH-9979") -@RequiresDialectFeature( value = DialectChecks.SupportsIdentityColumns.class, jiraKey = "HHH-9918") -public class MergeListPreAndPostPersistWithIdentityTest extends BaseCoreFunctionalTestCase { - - protected Class[] getAnnotatedClasses() { - return new Class[] { - Order.class, - Item.class - }; - } +@JiraKey(value = "HHH-9979") +@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsIdentityColumns.class, jiraKey = "HHH-9918") +@DomainModel( + annotatedClasses = { + MergeListPreAndPostPersistWithIdentityTest.Order.class, + MergeListPreAndPostPersistWithIdentityTest.Item.class + } +) +@SessionFactory +public class MergeListPreAndPostPersistWithIdentityTest { @Test - @JiraKey( value = "HHH-9979") - @FailureExpected( jiraKey = "HHH-9979") - public void testAllPropertiesCopied() { + @JiraKey(value = "HHH-9979") + @FailureExpected(jiraKey = "HHH-9979") + public void testAllPropertiesCopied(SessionFactoryScope scope) { final Order order = new Order(); order.id = 1L; order.name = "order"; @@ -58,23 +58,19 @@ public void testAllPropertiesCopied() { item.name = "item"; order.items.add( item ); - addEntityListeners( order ); + addEntityListeners( scope, order ); - Session s = openSession(); - s.getTransaction().begin(); - s.merge( order ); - s.getTransaction().commit(); - s.close(); + scope.inTransaction( s -> { + s.merge( order ); + } ); - s = openSession(); - s.getTransaction().begin(); - s.remove( order ); - s.getTransaction().commit(); - s.close(); + scope.inTransaction( s -> { + s.remove( order ); + } ); } @Entity - private static class Order { + static class Order { @Id public Long id; @@ -106,7 +102,7 @@ public int hashCode() { } @Entity - private static class Item { + static class Item { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public Long id; @@ -134,17 +130,17 @@ public int hashCode() { } } - private void addEntityListeners(final Order order) { + private void addEntityListeners(SessionFactoryScope scope, final Order order) { - EventListenerRegistry registry = sessionFactory().getEventListenerRegistry(); + EventListenerRegistry registry = scope.getSessionFactory().getEventListenerRegistry(); registry.setListeners( EventType.PRE_INSERT, new PreInsertEventListener() { @Override public boolean onPreInsert(PreInsertEvent event) { - if ( Order.class.isInstance( event.getEntity() ) ) { - assertEquals( order, event.getEntity()); - assertEquals( order.items, ( (Order) event.getEntity() ).items ); + if ( event.getEntity() instanceof Order ) { + assertEquals( order, event.getEntity() ); + assertEquals( order.items, ((Order) event.getEntity()).items ); } return false; } @@ -155,9 +151,9 @@ public boolean onPreInsert(PreInsertEvent event) { EventType.POST_INSERT, new PostInsertEventListener() { public void onPostInsert(PostInsertEvent event) { - if ( Order.class.isInstance( event.getEntity() ) ) { - assertEquals( order, event.getEntity()); - assertEquals( order.items, ( (Order) event.getEntity() ).items ); + if ( event.getEntity() instanceof Order ) { + assertEquals( order, event.getEntity() ); + assertEquals( order.items, ((Order) event.getEntity()).items ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/events/CallbackTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/events/CallbackTest.java index e59f82d71bab..1b814c86cadd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/events/CallbackTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/events/CallbackTest.java @@ -7,25 +7,21 @@ import org.hibernate.HibernateException; import org.hibernate.SessionFactory; import org.hibernate.SessionFactoryObserver; -import org.hibernate.boot.Metadata; -import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; -import org.hibernate.boot.spi.BootstrapContext; -import org.hibernate.cfg.Configuration; +import org.hibernate.boot.SessionFactoryBuilder; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.event.spi.DeleteContext; import org.hibernate.event.spi.DeleteEvent; import org.hibernate.event.spi.DeleteEventListener; import org.hibernate.event.spi.EventType; -import org.hibernate.integrator.spi.Integrator; -import org.hibernate.service.spi.SessionFactoryServiceRegistry; - import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import org.hibernate.testing.orm.junit.JiraKeyGroup; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; + +import java.util.function.Consumer; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** @@ -33,68 +29,35 @@ * * @author Steve Ebersole */ -@JiraKeyGroup( value = { - @JiraKey( value = "HHH-2884" ), - @JiraKey( value = "HHH-10674" ), - @JiraKey( value = "HHH-14541" ) -} ) -public class CallbackTest extends BaseCoreFunctionalTestCase { - private TestingObserver observer = new TestingObserver(); - private TestingListener listener = new TestingListener(); - - @Override - public String[] getMappings() { - return NO_MAPPINGS; - } - - @Override - public void configure(Configuration cfg) { - cfg.setSessionFactoryObserver( observer ); - } - - @Override - protected void prepareBootstrapRegistryBuilder(BootstrapServiceRegistryBuilder builder) { - super.prepareBootstrapRegistryBuilder( builder ); - builder.applyIntegrator( - new Integrator() { - @Override - public void integrate( - Metadata metadata, - BootstrapContext bootstrapContext, - SessionFactoryImplementor sessionFactory) { - integrate( sessionFactory ); - } - - private void integrate(SessionFactoryImplementor sessionFactory) { - sessionFactory.getEventListenerRegistry().setListeners( - EventType.DELETE, - listener - ); - listener.initialize(); - } - - @Override - public void disintegrate( - SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) { - listener.cleanup(); - } - } - ); - } +@JiraKeyGroup(value = { + @JiraKey(value = "HHH-2884"), + @JiraKey(value = "HHH-10674"), + @JiraKey(value = "HHH-14541") +}) +@org.hibernate.testing.orm.junit.SessionFactory(sessionFactoryConfigurer = CallbackTest.Configurer.class) +public class CallbackTest { + private static TestingObserver observer = new TestingObserver(); + private static TestingListener listener = new TestingListener(); @Test - public void testCallbacks() { + public void testCallbacks(SessionFactoryScope scope) { + SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); + sessionFactory.getEventListenerRegistry().setListeners( + EventType.DELETE, + listener + ); + listener.initialize(); // test pre-assertions assert observer.closingCount == 0; assert observer.closedCount == 0; - assertEquals( "observer not notified of creation", 1, observer.creationCount ); - assertEquals( "listener not notified of creation", 1, listener.initCount ); + assertEquals( 1, observer.creationCount, "observer not notified of creation" ); + assertEquals( 1, listener.initCount, "listener not notified of creation" ); - sessionFactory().close(); + sessionFactory.close(); - assertEquals( "observer not notified of closing", 1, observer.closingCount ); - assertEquals( "observer not notified of close", 1, observer.closedCount ); - assertEquals( "listener not notified of close", 1, listener.destoryCount ); + assertEquals( 1, observer.closingCount, "observer not notified of closing" ); + assertEquals( 1, observer.closedCount, "observer not notified of close" ); + assertEquals( 1, listener.destoryCount, "listener not notified of close" ); } private static class TestingObserver implements SessionFactoryObserver { @@ -119,6 +82,7 @@ public void sessionFactoryClosing(SessionFactory factory) { public void sessionFactoryClosed(SessionFactory factory) { assertThat( factory.isClosed() ).isTrue(); closedCount++; + listener.cleanup(); } } @@ -140,4 +104,11 @@ public void onDelete(DeleteEvent event) throws HibernateException { public void onDelete(DeleteEvent event, DeleteContext transientEntities) throws HibernateException { } } + + public static class Configurer implements Consumer { + @Override + public void accept(SessionFactoryBuilder sessionFactoryBuilder) { + sessionFactoryBuilder.addSessionFactoryObservers( observer ); + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/events/DefaultEntityListenerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/events/DefaultEntityListenerTest.java index 6485ac1e32ba..a843660ee01d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/events/DefaultEntityListenerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/events/DefaultEntityListenerTest.java @@ -9,78 +9,72 @@ import jakarta.persistence.ExcludeSuperclassListeners; import jakarta.persistence.Id; import jakarta.persistence.ManyToOne; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static junit.framework.TestCase.assertNull; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import static org.junit.jupiter.api.Assertions.assertNull; /** * @author Vlad Mihalcea */ -public class DefaultEntityListenerTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Book.class, - Publisher.class - }; - } - - @Override - protected String[] getMappings() { - return new String[] { "org/hibernate/orm/test/events/DefaultEntityListener-orm.xml" }; - } +@DomainModel( + annotatedClasses = { + DefaultEntityListenerTest.Person.class, + DefaultEntityListenerTest.Book.class, + DefaultEntityListenerTest.Publisher.class + }, + xmlMappings = "org/hibernate/orm/test/events/DefaultEntityListener-orm.xml" +) +@SessionFactory +public class DefaultEntityListenerTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(SessionFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::events-default-listener-persist-example[] Person author = new Person(); - author.setId(1L); - author.setName("Vlad Mihalcea"); + author.setId( 1L ); + author.setName( "Vlad Mihalcea" ); - entityManager.persist(author); + entityManager.persist( author ); Book book = new Book(); - book.setId(1L); - book.setTitle("High-Performance Java Persistence"); - book.setAuthor(author); + book.setId( 1L ); + book.setTitle( "High-Performance Java Persistence" ); + book.setAuthor( author ); - entityManager.persist(book); + entityManager.persist( book ); //end::events-default-listener-persist-example[] - }); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::events-default-listener-update-example[] - Person author = entityManager.find(Person.class, 1L); - author.setName("Vlad-Alexandru Mihalcea"); + Person author = entityManager.find( Person.class, 1L ); + author.setName( "Vlad-Alexandru Mihalcea" ); - Book book = entityManager.find(Book.class, 1L); - book.setTitle("High-Performance Java Persistence 2nd Edition"); + Book book = entityManager.find( Book.class, 1L ); + book.setTitle( "High-Performance Java Persistence 2nd Edition" ); //end::events-default-listener-update-example[] - }); + } ); } @Test - public void testExclude() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testExclude(SessionFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::events-exclude-default-listener-persist-example[] Publisher publisher = new Publisher(); - publisher.setId(1L); - publisher.setName("Amazon"); + publisher.setId( 1L ); + publisher.setName( "Amazon" ); - entityManager.persist(publisher); + entityManager.persist( publisher ); //end::events-exclude-default-listener-persist-example[] - }); - doInJPA(this::entityManagerFactory, entityManager -> { - Publisher publisher = entityManager.find(Publisher.class, 1L); - assertNull(publisher.getCreatedOn()); - }); + } ); + scope.inTransaction( entityManager -> { + Publisher publisher = entityManager.find( Publisher.class, 1L ); + assertNull( publisher.getCreatedOn() ); + } ); } //tag::events-default-listener-mapping-example[] @@ -152,7 +146,7 @@ public void setAuthor(Person author) { } //tag::events-default-listener-mapping-example[] } - //end::events-default-listener-mapping-example[] + //end::events-default-listener-mapping-example[] //tag::events-exclude-default-listener-mapping-example[] @Entity(name = "Publisher") @@ -184,7 +178,7 @@ public void setName(String name) { this.name = name; } - //tag::events-exclude-default-listener-mapping-example[] + //tag::events-exclude-default-listener-mapping-example[] } //end::events-exclude-default-listener-mapping-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/events/EventEngineContributionsTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/events/EventEngineContributionsTests.java index 094253eff496..091396d3f11e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/events/EventEngineContributionsTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/events/EventEngineContributionsTests.java @@ -4,10 +4,6 @@ */ package org.hibernate.orm.test.events; -import java.util.Collection; -import java.util.Collections; - -import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; import org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl; import org.hibernate.event.service.spi.EventListenerGroup; import org.hibernate.event.service.spi.EventListenerRegistry; @@ -15,57 +11,62 @@ import org.hibernate.event.spi.EventEngineContributions; import org.hibernate.event.spi.EventEngineContributor; import org.hibernate.event.spi.EventType; - +import org.hibernate.testing.orm.junit.BootstrapServiceRegistry; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.sameInstance; -import static org.hamcrest.MatcherAssert.assertThat; +import java.util.Collection; +import java.util.Collections; + +import static org.assertj.core.api.Assertions.assertThat; /** * @author Steve Ebersole */ -@JiraKey( value = "HHH-13890") -public class EventEngineContributionsTests extends BaseNonConfigCoreFunctionalTestCase { - - @Override - protected void configureBootstrapServiceRegistryBuilder(BootstrapServiceRegistryBuilder bsrb) { - super.configureBootstrapServiceRegistryBuilder( bsrb ); - bsrb.applyClassLoaderService( new TestingClassLoaderService() ); - } +@JiraKey(value = "HHH-13890") +@BootstrapServiceRegistry( + javaServices = @BootstrapServiceRegistry.JavaService(role = EventEngineContributor.class, + impl = EventEngineContributionsTests.ConfiguredContributor.class) +) +@SessionFactory +public class EventEngineContributionsTests { @Test - public void testCustomEventAccess() { - final EventEngine eventEngine = sessionFactory().getEventEngine(); + public void testCustomEventAccess(SessionFactoryScope scope) { + final EventEngine eventEngine = scope.getSessionFactory().getEventEngine(); { - final EventType saveEventType = eventEngine.findRegisteredEventType( SexyRxySaveListener.EVENT_NAME ); - assertThat( saveEventType, sameInstance( TheContributor.INSTANCE.saveEventType ) ); - assertThat( saveEventType.isStandardEvent(), is( false ) ); + final EventType saveEventType = eventEngine.findRegisteredEventType( + SexyRxySaveListener.EVENT_NAME ); + assertThat( saveEventType ).isSameAs( TheContributor.INSTANCE.saveEventType ); + assertThat( saveEventType.isStandardEvent() ).isFalse(); final EventListenerRegistry listenerRegistry = eventEngine.getListenerRegistry(); - final EventListenerGroup listenerGroup = listenerRegistry.getEventListenerGroup( saveEventType ); - assertThat( listenerGroup.count(), is( 1 ) ); + final EventListenerGroup listenerGroup = listenerRegistry.getEventListenerGroup( + saveEventType ); + assertThat( listenerGroup.count() ).isEqualTo( 1 ); listenerGroup.fireEventOnEachListener( RxySaveEvent.INSTANCE, SexyRxySaveListener::doIt ); - assertThat( SexyRxySaveListener.INSTANCE.didIt, is(true ) ); + assertThat( SexyRxySaveListener.INSTANCE.didIt ).isTrue(); } { - final EventType persistEventType = eventEngine.findRegisteredEventType( SexyRxyPersistListener.EVENT_NAME ); - assertThat( persistEventType, sameInstance( TheContributor.INSTANCE.persistEventType ) ); - assertThat( persistEventType.isStandardEvent(), is( false ) ); + final EventType persistEventType = eventEngine.findRegisteredEventType( + SexyRxyPersistListener.EVENT_NAME ); + assertThat( persistEventType ).isSameAs( TheContributor.INSTANCE.persistEventType ); + assertThat( persistEventType.isStandardEvent() ).isFalse(); final EventListenerRegistry listenerRegistry = eventEngine.getListenerRegistry(); - final EventListenerGroup listenerGroup = listenerRegistry.getEventListenerGroup( persistEventType ); - assertThat( listenerGroup.count(), is( 1 ) ); + final EventListenerGroup listenerGroup = listenerRegistry.getEventListenerGroup( + persistEventType ); + assertThat( listenerGroup.count() ).isEqualTo( 1 ); listenerGroup.fireEventOnEachListener( RxyPersistEvent.INSTANCE, SexyRxyPersistListener::doIt ); - assertThat( SexyRxyPersistListener.INSTANCE.didIt, is(true ) ); + assertThat( SexyRxyPersistListener.INSTANCE.didIt ).isTrue(); } } @@ -104,6 +105,14 @@ public void doIt(RxyPersistEvent event) { } } + public static class ConfiguredContributor implements EventEngineContributor { + + @Override + public void contribute(EventEngineContributions target) { + TheContributor.INSTANCE.contribute( target ); + } + } + public static class TheContributor implements EventEngineContributor { /** * Singleton access diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/events/InterceptorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/events/InterceptorTest.java index 399e2006fa98..e0918a1fbf12 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/events/InterceptorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/events/InterceptorTest.java @@ -6,6 +6,7 @@ import java.io.Serializable; import java.util.Arrays; + import jakarta.persistence.Entity; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.GeneratedValue; @@ -15,55 +16,52 @@ import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.MetadataSources; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.testing.util.ServiceRegistryUtil; import org.hibernate.type.Type; -import org.junit.Before; -import org.junit.Test; - import org.jboss.logging.Logger; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class InterceptorTest extends BaseEntityManagerFunctionalTestCase { - - private static final Logger LOGGER = Logger.getLogger(InterceptorTest.class); +@DomainModel( + annotatedClasses = { + InterceptorTest.Customer.class + } +) +@org.hibernate.testing.orm.junit.SessionFactory +public class InterceptorTest { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Customer.class - }; - } + private static final Logger LOGGER = Logger.getLogger( InterceptorTest.class ); - @Before - public void init() { - doInJPA(this::entityManagerFactory, entityManager -> { - entityManager.persist(new Customer("John Doe")); + @BeforeEach + public void init(SessionFactoryScope scope) { + scope.inTransaction( entityManager -> { + entityManager.persist( new Customer( "John Doe" ) ); Customer customer = new Customer(); - entityManager.persist(customer); - }); + entityManager.persist( customer ); + } ); } @Test - public void testSessionInterceptor() { - EntityManagerFactory entityManagerFactory = entityManagerFactory(); + public void testSessionInterceptor(SessionFactoryScope scope) { + EntityManagerFactory entityManagerFactory = scope.getSessionFactory(); Serializable customerId = 1L; //tag::events-interceptors-session-scope-example[] - SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class); + SessionFactory sessionFactory = entityManagerFactory.unwrap( SessionFactory.class ); Session session = sessionFactory - .withOptions() - .interceptor(new LoggingInterceptor()) - .openSession(); + .withOptions() + .interceptor( new LoggingInterceptor() ) + .openSession(); session.getTransaction().begin(); - Customer customer = session.get(Customer.class, customerId); - customer.setName("Mr. John Doe"); + Customer customer = session.get( Customer.class, customerId ); + customer.setName( "Mr. John Doe" ); //Entity Customer#1 changed from [John Doe, 0] to [Mr. John Doe, 0] session.getTransaction().commit(); @@ -92,8 +90,8 @@ public void testSessionFactoryInterceptor() { Session session = sessionFactory.openSession(); session.getTransaction().begin(); - Customer customer = session.get(Customer.class, customerId); - customer.setName("Mr. John Doe"); + Customer customer = session.get( Customer.class, customerId ); + customer.setName( "Mr. John Doe" ); //Entity Customer#1 changed from [John Doe, 0] to [Mr. John Doe, 0] session.getTransaction().commit(); session.close(); @@ -133,19 +131,19 @@ public void setName(String name) { public static class LoggingInterceptor implements Interceptor { @Override public boolean onFlushDirty( - Object entity, - Object id, - Object[] currentState, - Object[] previousState, - String[] propertyNames, - Type[] types) { - LOGGER.debugv("Entity {0}#{1} changed from {2} to {3}", + Object entity, + Object id, + Object[] currentState, + Object[] previousState, + String[] propertyNames, + Type[] types) { + LOGGER.debugv( "Entity {0}#{1} changed from {2} to {3}", entity.getClass().getSimpleName(), id, - Arrays.toString(previousState), - Arrays.toString(currentState) - ); - return Interceptor.super.onFlushDirty(entity, id, currentState, + Arrays.toString( previousState ), + Arrays.toString( currentState ) + ); + return Interceptor.super.onFlushDirty( entity, id, currentState, previousState, propertyNames, types ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/events/LegacyPostCommitListenerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/events/LegacyPostCommitListenerTest.java index de3c0961cbaa..0737ec332e8b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/events/LegacyPostCommitListenerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/events/LegacyPostCommitListenerTest.java @@ -5,12 +5,6 @@ package org.hibernate.orm.test.events; import org.hibernate.IrrelevantEntity; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.boot.Metadata; -import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; -import org.hibernate.boot.spi.BootstrapContext; -import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.event.service.spi.EventListenerRegistry; import org.hibernate.event.spi.EventType; import org.hibernate.event.spi.PostDeleteEvent; @@ -19,193 +13,162 @@ import org.hibernate.event.spi.PostInsertEventListener; import org.hibernate.event.spi.PostUpdateEvent; import org.hibernate.event.spi.PostUpdateEventListener; -import org.hibernate.integrator.spi.Integrator; import org.hibernate.persister.entity.EntityPersister; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Assert; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test to ensure that the existing post commit behavior when using plain PostXEventListeners fire on both success and failure. * * @author ShawnClowater */ -public class LegacyPostCommitListenerTest extends BaseCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + IrrelevantEntity.class + } +) +@SessionFactory +public class LegacyPostCommitListenerTest { private final PostInsertEventListener postCommitInsertEventListener = new LegacyPostCommitInsertEventListener(); private final PostDeleteEventListener postCommitDeleteEventListener = new LegacyPostCommitDeleteEventListener(); private final PostUpdateEventListener postCommitUpdateEventListener = new LegacyPostCommitUpdateEventListener(); - @Override - protected void prepareTest() throws Exception { - ( (LegacyPostCommitInsertEventListener) postCommitInsertEventListener ).fired = 0; - ( (LegacyPostCommitDeleteEventListener) postCommitDeleteEventListener ).fired = 0; - ( (LegacyPostCommitUpdateEventListener) postCommitUpdateEventListener ).fired = 0; + @BeforeEach + void prepareTest() { + ((LegacyPostCommitInsertEventListener) postCommitInsertEventListener).fired = 0; + ((LegacyPostCommitDeleteEventListener) postCommitDeleteEventListener).fired = 0; + ((LegacyPostCommitUpdateEventListener) postCommitUpdateEventListener).fired = 0; } - @Override - protected void prepareBootstrapRegistryBuilder(BootstrapServiceRegistryBuilder builder) { - super.prepareBootstrapRegistryBuilder( builder ); - builder.applyIntegrator( - new Integrator() { - @Override - public void integrate( - Metadata metadata, - BootstrapContext bootstrapContext, - SessionFactoryImplementor sessionFactory) { - integrate( sessionFactory ); - } - - private void integrate(SessionFactoryImplementor sessionFactory) { - final EventListenerRegistry listenerRegistry = sessionFactory.getEventListenerRegistry(); - listenerRegistry.getEventListenerGroup( EventType.POST_COMMIT_DELETE ) - .appendListener( postCommitDeleteEventListener ); - listenerRegistry.getEventListenerGroup( EventType.POST_COMMIT_UPDATE ) - .appendListener( postCommitUpdateEventListener ); - listenerRegistry.getEventListenerGroup( EventType.POST_COMMIT_INSERT ) - .appendListener( postCommitInsertEventListener ); - } - } - ); + @BeforeAll + protected void prepareBootstrapRegistryBuilder(SessionFactoryScope scope) { + final EventListenerRegistry listenerRegistry = scope.getSessionFactory().getEventListenerRegistry(); + listenerRegistry.getEventListenerGroup( EventType.POST_COMMIT_DELETE ) + .appendListener( postCommitDeleteEventListener ); + listenerRegistry.getEventListenerGroup( EventType.POST_COMMIT_UPDATE ) + .appendListener( postCommitUpdateEventListener ); + listenerRegistry.getEventListenerGroup( EventType.POST_COMMIT_INSERT ) + .appendListener( postCommitInsertEventListener ); } @Test @JiraKey("HHH-1582") - public void testPostCommitInsertListenerSuccess() { - Session session = openSession(); - Transaction transaction = session.beginTransaction(); - - IrrelevantEntity irrelevantEntity = new IrrelevantEntity(); - irrelevantEntity.setName( "Irrelevant" ); + public void testPostCommitInsertListenerSuccess(SessionFactoryScope scope) { + scope.inTransaction( session -> { + IrrelevantEntity irrelevantEntity = new IrrelevantEntity(); + irrelevantEntity.setName( "Irrelevant" ); - session.persist( irrelevantEntity ); - session.flush(); - transaction.commit(); - session.close(); + session.persist( irrelevantEntity ); + session.flush(); + } ); - Assert.assertEquals( 1, ( (LegacyPostCommitInsertEventListener) postCommitInsertEventListener ).fired ); + assertEquals( 1, ((LegacyPostCommitInsertEventListener) postCommitInsertEventListener).fired ); } @Test @JiraKey("HHH-1582") - public void testPostCommitInsertListenerRollback() { - Session session = openSession(); - Transaction transaction = session.beginTransaction(); + public void testPostCommitInsertListenerRollback(SessionFactoryScope scope) { + scope.inTransaction( session -> { + IrrelevantEntity irrelevantEntity = new IrrelevantEntity(); + irrelevantEntity.setName( "Irrelevant" ); - IrrelevantEntity irrelevantEntity = new IrrelevantEntity(); - irrelevantEntity.setName( "Irrelevant" ); - - session.persist( irrelevantEntity ); - session.flush(); - transaction.rollback(); - session.close(); + session.persist( irrelevantEntity ); + session.flush(); + session.getTransaction().setRollbackOnly(); + } ); //the legacy implementation fires the listener on failure as well - Assert.assertEquals( 1, ( (LegacyPostCommitInsertEventListener) postCommitInsertEventListener ).fired ); + assertEquals( 1, ((LegacyPostCommitInsertEventListener) postCommitInsertEventListener).fired ); } @Test @JiraKey("HHH-1582") - public void testPostCommitUpdateListenerSuccess() { - Session session = openSession(); - Transaction transaction = session.beginTransaction(); - + public void testPostCommitUpdateListenerSuccess(SessionFactoryScope scope) { IrrelevantEntity irrelevantEntity = new IrrelevantEntity(); - irrelevantEntity.setName( "Irrelevant" ); - - session.persist( irrelevantEntity ); - session.flush(); - transaction.commit(); + scope.inTransaction( session -> { + irrelevantEntity.setName( "Irrelevant" ); - session = openSession(); - transaction = session.beginTransaction(); - irrelevantEntity.setName( "Irrelevant 2" ); - session.merge( irrelevantEntity ); - session.flush(); - transaction.commit(); + session.persist( irrelevantEntity ); + session.flush(); + } ); - session.close(); + scope.inTransaction( session -> { + irrelevantEntity.setName( "Irrelevant 2" ); + session.merge( irrelevantEntity ); + session.flush(); + } ); - Assert.assertEquals( 1, ( (LegacyPostCommitUpdateEventListener) postCommitUpdateEventListener ).fired ); + assertEquals( 1, ((LegacyPostCommitUpdateEventListener) postCommitUpdateEventListener).fired ); } @Test @JiraKey("HHH-1582") - public void testPostCommitUpdateListenerRollback() { - Session session = openSession(); - Transaction transaction = session.beginTransaction(); - + public void testPostCommitUpdateListenerRollback(SessionFactoryScope scope) { IrrelevantEntity irrelevantEntity = new IrrelevantEntity(); - irrelevantEntity.setName( "Irrelevant" ); - - session.persist( irrelevantEntity ); - session.flush(); - transaction.commit(); - session.close(); + scope.inTransaction( session -> { + irrelevantEntity.setName( "Irrelevant" ); - session = openSession(); - transaction = session.beginTransaction(); - irrelevantEntity.setName( "Irrelevant 2" ); - session.merge( irrelevantEntity ); - session.flush(); - transaction.rollback(); + session.persist( irrelevantEntity ); + session.flush(); + } ); - session.close(); + scope.inTransaction( session -> { + irrelevantEntity.setName( "Irrelevant 2" ); + session.merge( irrelevantEntity ); + session.flush(); + session.getTransaction().setRollbackOnly(); + } ); //the legacy implementation fires the listener on failure as well - Assert.assertEquals( 1, ( (LegacyPostCommitUpdateEventListener) postCommitUpdateEventListener ).fired ); + assertEquals( 1, ((LegacyPostCommitUpdateEventListener) postCommitUpdateEventListener).fired ); } @Test @JiraKey("HHH-1582") - public void testPostCommitDeleteListenerSuccess() { - Session session = openSession(); - Transaction transaction = session.beginTransaction(); - + public void testPostCommitDeleteListenerSuccess(SessionFactoryScope scope) { IrrelevantEntity irrelevantEntity = new IrrelevantEntity(); - irrelevantEntity.setName( "Irrelevant" ); - - session.persist( irrelevantEntity ); - session.flush(); - transaction.commit(); - session.close(); + scope.inTransaction( session -> { + irrelevantEntity.setName( "Irrelevant" ); - session = openSession(); - transaction = session.beginTransaction(); - session.remove( irrelevantEntity ); - session.flush(); - transaction.commit(); + session.persist( irrelevantEntity ); + session.flush(); + } ); - session.close(); + scope.inTransaction( session -> { + session.remove( irrelevantEntity ); + session.flush(); + } ); - Assert.assertEquals( 1, ( (LegacyPostCommitDeleteEventListener) postCommitDeleteEventListener ).fired ); + assertEquals( 1, ((LegacyPostCommitDeleteEventListener) postCommitDeleteEventListener).fired ); } @Test @JiraKey("HHH-1582") - public void testPostCommitDeleteListenerRollback() { - Session session = openSession(); - Transaction transaction = session.beginTransaction(); - + public void testPostCommitDeleteListenerRollback(SessionFactoryScope scope) { IrrelevantEntity irrelevantEntity = new IrrelevantEntity(); - irrelevantEntity.setName( "Irrelevant" ); - - session.persist( irrelevantEntity ); - session.flush(); - transaction.commit(); - session.close(); + scope.inTransaction( session -> { + irrelevantEntity.setName( "Irrelevant" ); - session = openSession(); - transaction = session.beginTransaction(); - session.remove( irrelevantEntity ); - session.flush(); - transaction.rollback(); + session.persist( irrelevantEntity ); + session.flush(); + } ); - session.close(); + scope.inTransaction( session -> { + session.remove( irrelevantEntity ); + session.flush(); + session.getTransaction().setRollbackOnly(); + } ); //the legacy implementation fires the listener on failure as well - Assert.assertEquals( 1, ( (LegacyPostCommitDeleteEventListener) postCommitDeleteEventListener ).fired ); + assertEquals( 1, ((LegacyPostCommitDeleteEventListener) postCommitDeleteEventListener).fired ); } private static class LegacyPostCommitDeleteEventListener implements PostDeleteEventListener { @@ -249,9 +212,4 @@ public boolean requiresPostCommitHandling(EntityPersister persister) { return true; } } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { IrrelevantEntity.class }; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/events/ListenerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/events/ListenerTest.java index 9d0dc7193338..8b330585e4fd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/events/ListenerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/events/ListenerTest.java @@ -11,6 +11,7 @@ import java.time.ZoneOffset; import java.time.temporal.ChronoUnit; import java.util.Date; + import jakarta.persistence.Entity; import jakarta.persistence.EntityListeners; import jakarta.persistence.EntityManagerFactory; @@ -26,57 +27,70 @@ import org.hibernate.event.spi.EventType; import org.hibernate.event.spi.LoadEvent; import org.hibernate.event.spi.LoadEventListener; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.*; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertTrue; /** * @author Vlad Mihalcea */ -public class ListenerTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Customer.class - }; +@DomainModel( + annotatedClasses = { + ListenerTest.Person.class, + ListenerTest.Customer.class + } +) +@SessionFactory +public class ListenerTest { + + @AfterEach + public void afterEach(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } - @Test(expected = SecurityException.class) - public void testLoadListener() { + @BeforeEach + public void testLoadListener(SessionFactoryScope scope) { Serializable customerId = 1L; - - doInJPA( this::entityManagerFactory, entityManager -> { - //tag::events-interceptors-load-listener-example-part1[] - EntityManagerFactory entityManagerFactory = entityManagerFactory(); - entityManagerFactory.unwrap( SessionFactoryImplementor.class ).getEventListenerRegistry() - .prependListeners( EventType.LOAD, new SecuredLoadEntityListener() ); - - Customer customer = entityManager.find( Customer.class, customerId ); - //end::events-interceptors-load-listener-example-part1[] - } ); + assertThatThrownBy( () -> + scope.inTransaction( entityManager -> { + //tag::events-interceptors-load-listener-example-part1[] + EntityManagerFactory entityManagerFactory = /* ... */ + //end::events-interceptors-load-listener-example-part1[] + entityManager.getEntityManagerFactory(); + //tag::events-interceptors-load-listener-example-part1[] + entityManagerFactory.unwrap( SessionFactoryImplementor.class ).getEventListenerRegistry() + .prependListeners( EventType.LOAD, new SecuredLoadEntityListener() ); + + Customer customer = entityManager.find( Customer.class, customerId ); + //end::events-interceptors-load-listener-example-part1[] + } ) ).isInstanceOf( SecurityException.class ); } @Test - public void testJPACallback() { + public void testJPACallback(SessionFactoryScope scope) { Long personId = 1L; - doInJPA( this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Person person = new Person(); person.id = personId; person.name = "John Doe"; - person.dateOfBirth = Timestamp.valueOf(LocalDateTime.of( 2000, 1, 1, 0, 0, 0 )); + person.dateOfBirth = Timestamp.valueOf( LocalDateTime.of( 2000, 1, 1, 0, 0, 0 ) ); entityManager.persist( person ); } ); - doInJPA( this::entityManagerFactory, entityManager -> { - Person person = entityManager.find( Person.class, personId ); - assertTrue(person.age > 0); - } ); + assertThatThrownBy( () -> + scope.inTransaction( entityManager -> { + Person person = entityManager.find( Person.class, personId ); + assertTrue( person.age > 0 ); + } ) ).isInstanceOf( SecurityException.class ); } @Entity(name = "Customer") @@ -110,7 +124,7 @@ public void setName(String name) { //tag::events-jpa-callbacks-example[] @Entity(name = "Person") - @EntityListeners( LastUpdateListener.class ) + @EntityListeners(LastUpdateListener.class) public static class Person { @Id @@ -136,8 +150,8 @@ public void setLastUpdate(Date lastUpdate) { @PostLoad public void calculateAge() { age = ChronoUnit.YEARS.between( LocalDateTime.ofInstant( - Instant.ofEpochMilli( dateOfBirth.getTime()), ZoneOffset.UTC), - LocalDateTime.now() + Instant.ofEpochMilli( dateOfBirth.getTime() ), ZoneOffset.UTC ), + LocalDateTime.now() ); } } @@ -146,7 +160,7 @@ public static class LastUpdateListener { @PreUpdate @PrePersist - public void setLastUpdate( Person p ) { + public void setLastUpdate(Person p) { p.setLastUpdate( new Date() ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/events/PostCommitListenerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/events/PostCommitListenerTest.java index 80c0e528a706..2015812fdc67 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/events/PostCommitListenerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/events/PostCommitListenerTest.java @@ -5,12 +5,6 @@ package org.hibernate.orm.test.events; import org.hibernate.IrrelevantEntity; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.boot.Metadata; -import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; -import org.hibernate.boot.spi.BootstrapContext; -import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.event.service.spi.EventListenerRegistry; import org.hibernate.event.spi.EventType; import org.hibernate.event.spi.PostCommitDeleteEventListener; @@ -22,199 +16,170 @@ import org.hibernate.event.spi.PostInsertEventListener; import org.hibernate.event.spi.PostUpdateEvent; import org.hibernate.event.spi.PostUpdateEventListener; -import org.hibernate.integrator.spi.Integrator; import org.hibernate.persister.entity.EntityPersister; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Assert; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test to ensure that the existing post commit behavior when using plain PostXEventListeners fire on both success and failure. * * @author ShawnClowater */ -public class PostCommitListenerTest extends BaseCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + IrrelevantEntity.class + } +) +@SessionFactory +public class PostCommitListenerTest { private final PostInsertEventListener postCommitInsertEventListener = new TestPostCommitInsertEventListener(); private final PostDeleteEventListener postCommitDeleteEventListener = new TestPostCommitDeleteEventListener(); private final PostUpdateEventListener postCommitUpdateEventListener = new TestPostCommitUpdateEventListener(); - @Override - protected void prepareTest() throws Exception { + @BeforeEach + void prepareTest() throws Exception { ((TestPostCommitInsertEventListener) postCommitInsertEventListener).success = 0; ((TestPostCommitInsertEventListener) postCommitInsertEventListener).failed = 0; ((TestPostCommitDeleteEventListener) postCommitDeleteEventListener).success = 0; ((TestPostCommitDeleteEventListener) postCommitDeleteEventListener).failed = 0; - ((TestPostCommitUpdateEventListener) postCommitUpdateEventListener).sucess = 0; + ((TestPostCommitUpdateEventListener) postCommitUpdateEventListener).success = 0; ((TestPostCommitUpdateEventListener) postCommitUpdateEventListener).failed = 0; } - @Override - protected void prepareBootstrapRegistryBuilder(BootstrapServiceRegistryBuilder builder) { - super.prepareBootstrapRegistryBuilder( builder ); - builder.applyIntegrator( - new Integrator() { - @Override - public void integrate( - Metadata metadata, - BootstrapContext bootstrapContext, - SessionFactoryImplementor sessionFactory) { - integrate( sessionFactory ); - } - - private void integrate(SessionFactoryImplementor sessionFactory) { - final EventListenerRegistry listenerRegistry = sessionFactory.getEventListenerRegistry(); - listenerRegistry.getEventListenerGroup( EventType.POST_COMMIT_DELETE ) - .appendListener( postCommitDeleteEventListener ); - listenerRegistry.getEventListenerGroup( EventType.POST_COMMIT_UPDATE ) - .appendListener( postCommitUpdateEventListener ); - listenerRegistry.getEventListenerGroup( EventType.POST_COMMIT_INSERT ) - .appendListener( postCommitInsertEventListener ); - } - } - ); + @BeforeAll + void prepareBootstrapRegistryBuilder(SessionFactoryScope scope) { + final EventListenerRegistry listenerRegistry = scope.getSessionFactory().getEventListenerRegistry(); + listenerRegistry.getEventListenerGroup( EventType.POST_COMMIT_DELETE ) + .appendListener( postCommitDeleteEventListener ); + listenerRegistry.getEventListenerGroup( EventType.POST_COMMIT_UPDATE ) + .appendListener( postCommitUpdateEventListener ); + listenerRegistry.getEventListenerGroup( EventType.POST_COMMIT_INSERT ) + .appendListener( postCommitInsertEventListener ); } @Test - @JiraKey( "HHH-1582") - public void testPostCommitInsertListenerSuccess() { - Session session = openSession(); - Transaction transaction = session.beginTransaction(); - - IrrelevantEntity irrelevantEntity = new IrrelevantEntity(); - irrelevantEntity.setName( "Irrelevant" ); - - session.persist( irrelevantEntity ); - session.flush(); - transaction.commit(); - session.close(); - - Assert.assertEquals( 1, ((TestPostCommitInsertEventListener) postCommitInsertEventListener).success ); - Assert.assertEquals( 0, ((TestPostCommitInsertEventListener) postCommitInsertEventListener).failed ); + @JiraKey("HHH-1582") + public void testPostCommitInsertListenerSuccess(SessionFactoryScope scope) { + scope.inTransaction( session -> { + IrrelevantEntity irrelevantEntity = new IrrelevantEntity(); + irrelevantEntity.setName( "Irrelevant" ); + + session.persist( irrelevantEntity ); + session.flush(); + } ); + + assertEquals( 1, ((TestPostCommitInsertEventListener) postCommitInsertEventListener).success ); + assertEquals( 0, ((TestPostCommitInsertEventListener) postCommitInsertEventListener).failed ); } @Test - @JiraKey( "HHH-1582") - public void testPostCommitInsertListenerRollback() { - Session session = openSession(); - Transaction transaction = session.beginTransaction(); - - IrrelevantEntity irrelevantEntity = new IrrelevantEntity(); - irrelevantEntity.setName( "Irrelevant" ); - - session.persist( irrelevantEntity ); - session.flush(); - transaction.rollback(); - session.close(); - - Assert.assertEquals( 0, ((TestPostCommitInsertEventListener) postCommitInsertEventListener).success ); - Assert.assertEquals( 1, ((TestPostCommitInsertEventListener) postCommitInsertEventListener).failed ); + @JiraKey("HHH-1582") + public void testPostCommitInsertListenerRollback(SessionFactoryScope scope) { + scope.inTransaction( session -> { + IrrelevantEntity irrelevantEntity = new IrrelevantEntity(); + irrelevantEntity.setName( "Irrelevant" ); + + session.persist( irrelevantEntity ); + session.flush(); + session.getTransaction().setRollbackOnly(); + } ); + + assertEquals( 0, ((TestPostCommitInsertEventListener) postCommitInsertEventListener).success ); + assertEquals( 1, ((TestPostCommitInsertEventListener) postCommitInsertEventListener).failed ); } @Test - @JiraKey( "HHH-1582") - public void testPostCommitUpdateListenerSuccess() { - Session session = openSession(); - Transaction transaction = session.beginTransaction(); - + @JiraKey("HHH-1582") + public void testPostCommitUpdateListenerSuccess(SessionFactoryScope scope) { IrrelevantEntity irrelevantEntity = new IrrelevantEntity(); - irrelevantEntity.setName( "Irrelevant" ); - - session.persist( irrelevantEntity ); - session.flush(); - transaction.commit(); + scope.inTransaction( session -> { + irrelevantEntity.setName( "Irrelevant" ); - session = openSession(); - transaction = session.beginTransaction(); - irrelevantEntity.setName( "Irrelevant 2" ); - session.merge( irrelevantEntity ); - session.flush(); - transaction.commit(); + session.persist( irrelevantEntity ); + session.flush(); + } ); - session.close(); + scope.inTransaction( session -> { + irrelevantEntity.setName( "Irrelevant 2" ); + session.merge( irrelevantEntity ); + session.flush(); + } ); - Assert.assertEquals( 1, ((TestPostCommitUpdateEventListener) postCommitUpdateEventListener).sucess ); - Assert.assertEquals( 0, ((TestPostCommitUpdateEventListener) postCommitUpdateEventListener).failed ); + assertEquals( 1, ((TestPostCommitUpdateEventListener) postCommitUpdateEventListener).success ); + assertEquals( 0, ((TestPostCommitUpdateEventListener) postCommitUpdateEventListener).failed ); } @Test - @JiraKey( "HHH-1582") - public void testPostCommitUpdateListenerRollback() { - Session session = openSession(); - Transaction transaction = session.beginTransaction(); - - IrrelevantEntity irrelevantEntity = new IrrelevantEntity(); - irrelevantEntity.setName( "Irrelevant" ); - - session.persist( irrelevantEntity ); - session.flush(); - transaction.commit(); - session.close(); - - session = openSession(); - transaction = session.beginTransaction(); - irrelevantEntity.setName( "Irrelevant 2" ); - session.merge( irrelevantEntity ); - session.flush(); - transaction.rollback(); - - session.close(); - - Assert.assertEquals( 0, ((TestPostCommitUpdateEventListener) postCommitUpdateEventListener).sucess ); - Assert.assertEquals( 1, ((TestPostCommitUpdateEventListener) postCommitUpdateEventListener).failed ); + @JiraKey("HHH-1582") + public void testPostCommitUpdateListenerRollback(SessionFactoryScope scope) { + IrrelevantEntity irrelevantEntity = scope.fromTransaction( session -> { + IrrelevantEntity e = new IrrelevantEntity(); + e.setName( "Irrelevant" ); + + session.persist( e ); + session.flush(); + return e; + } ); + + scope.inTransaction( session -> { + irrelevantEntity.setName( "Irrelevant 2" ); + session.merge( irrelevantEntity ); + session.flush(); + session.getTransaction().setRollbackOnly(); + } ); + + assertEquals( 0, ((TestPostCommitUpdateEventListener) postCommitUpdateEventListener).success ); + assertEquals( 1, ((TestPostCommitUpdateEventListener) postCommitUpdateEventListener).failed ); } @Test - @JiraKey( "HHH-1582") - public void testPostCommitDeleteListenerSuccess() { - Session session = openSession(); - Transaction transaction = session.beginTransaction(); - - IrrelevantEntity irrelevantEntity = new IrrelevantEntity(); - irrelevantEntity.setName( "Irrelevant" ); - - session.persist( irrelevantEntity ); - session.flush(); - transaction.commit(); - session.close(); - - session = openSession(); - transaction = session.beginTransaction(); - session.remove( irrelevantEntity ); - session.flush(); - transaction.commit(); - - session.close(); - - Assert.assertEquals( 1, ((TestPostCommitDeleteEventListener) postCommitDeleteEventListener).success ); - Assert.assertEquals( 0, ((TestPostCommitDeleteEventListener) postCommitDeleteEventListener).failed ); + @JiraKey("HHH-1582") + public void testPostCommitDeleteListenerSuccess(SessionFactoryScope scope) { + IrrelevantEntity irrelevantEntity = scope.fromTransaction( session -> { + IrrelevantEntity e = new IrrelevantEntity(); + e.setName( "Irrelevant" ); + + session.persist( e ); + session.flush(); + return e; + } ); + + scope.inTransaction( session -> { + session.remove( irrelevantEntity ); + session.flush(); + } ); + + assertEquals( 1, ((TestPostCommitDeleteEventListener) postCommitDeleteEventListener).success ); + assertEquals( 0, ((TestPostCommitDeleteEventListener) postCommitDeleteEventListener).failed ); } @Test - @JiraKey( "HHH-1582") - public void testPostCommitDeleteListenerRollback() { - Session session = openSession(); - Transaction transaction = session.beginTransaction(); - + @JiraKey("HHH-1582") + public void testPostCommitDeleteListenerRollback(SessionFactoryScope scope) { IrrelevantEntity irrelevantEntity = new IrrelevantEntity(); - irrelevantEntity.setName( "Irrelevant" ); + scope.inTransaction( session -> { + irrelevantEntity.setName( "Irrelevant" ); - session.persist( irrelevantEntity ); - session.flush(); - transaction.commit(); - session.close(); + session.persist( irrelevantEntity ); + session.flush(); + } ); - session = openSession(); - transaction = session.beginTransaction(); - session.remove( irrelevantEntity ); - session.flush(); - transaction.rollback(); + scope.inTransaction( session -> { + session.remove( irrelevantEntity ); + session.flush(); + session.getTransaction().setRollbackOnly(); + } ); - session.close(); - - Assert.assertEquals( 0, ((TestPostCommitDeleteEventListener) postCommitDeleteEventListener).success ); - Assert.assertEquals( 1, ((TestPostCommitDeleteEventListener) postCommitDeleteEventListener).failed ); + assertEquals( 0, ((TestPostCommitDeleteEventListener) postCommitDeleteEventListener).success ); + assertEquals( 1, ((TestPostCommitDeleteEventListener) postCommitDeleteEventListener).failed ); } private static class TestPostCommitDeleteEventListener implements PostCommitDeleteEventListener { @@ -238,12 +203,12 @@ public boolean requiresPostCommitHandling(EntityPersister persister) { } private static class TestPostCommitUpdateEventListener implements PostCommitUpdateEventListener { - int sucess; + int success; int failed; @Override public void onPostUpdate(PostUpdateEvent event) { - sucess++; + success++; } @Override @@ -276,9 +241,4 @@ public boolean requiresPostCommitHandling(EntityPersister persister) { return true; } } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] {IrrelevantEntity.class}; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/eviction/EvictionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/eviction/EvictionTest.java index 8564d7c8e98f..6eba91737a54 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/eviction/EvictionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/eviction/EvictionTest.java @@ -4,117 +4,98 @@ */ package org.hibernate.orm.test.eviction; -import org.hibernate.Session; - +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Steve Ebersole */ -public class EvictionTest extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { IsolatedEvictableEntity.class }; - } +@DomainModel(annotatedClasses = IsolatedEvictableEntity.class) +@SessionFactory +public class EvictionTest { @Test - @JiraKey( value = "HHH-7912" ) - public void testNormalUsage() { - Session session = openSession(); - session.beginTransaction(); - session.persist( new IsolatedEvictableEntity( 1 ) ); - session.getTransaction().commit(); - session.close(); + @JiraKey(value = "HHH-7912") + public void testNormalUsage(SessionFactoryScope scope) { + scope.inTransaction( session -> session.persist( new IsolatedEvictableEntity( 1 ) ) ); - session = openSession(); - session.beginTransaction(); - IsolatedEvictableEntity entity = (IsolatedEvictableEntity) session.get( IsolatedEvictableEntity.class, 1 ); - assertTrue( session.contains( entity ) ); - session.evict( entity ); - assertFalse( session.contains( entity ) ); - session.getTransaction().commit(); - session.close(); + var e = scope.fromTransaction( session -> { + IsolatedEvictableEntity entity = session.get( IsolatedEvictableEntity.class, 1 ); + assertTrue( session.contains( entity ) ); + session.evict( entity ); + assertFalse( session.contains( entity ) ); + return entity; + } ); - session = openSession(); - session.beginTransaction(); - session.remove( entity ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( session -> { + session.remove( e ); + } ); } @Test - @JiraKey( value = "HHH-7912" ) - public void testEvictingNull() { - Session session = openSession(); - session.beginTransaction(); - try { - session.evict( null ); - fail( "Expecting evict(null) to throw IAE" ); - } - catch (IllegalArgumentException expected) { - } - session.getTransaction().commit(); - session.close(); + @JiraKey(value = "HHH-7912") + public void testEvictingNull(SessionFactoryScope scope) { + scope.inSession( session -> { + try { + session.evict( null ); + fail( "Expecting evict(null) to throw IAE" ); + } + catch (IllegalArgumentException expected) { + } + } ); } @Test - @JiraKey( value = "HHH-7912" ) - public void testEvictingTransientEntity() { - Session session = openSession(); - session.beginTransaction(); - session.evict( new IsolatedEvictableEntity( 1 ) ); - session.getTransaction().commit(); - session.close(); + @JiraKey(value = "HHH-7912") + public void testEvictingTransientEntity(SessionFactoryScope scope) { + scope.inSession( session -> { + session.evict( new IsolatedEvictableEntity( 1 ) ); + } ); } @Test - @JiraKey( value = "HHH-7912" ) - public void testEvictingDetachedEntity() { - Session session = openSession(); - session.beginTransaction(); - session.persist( new IsolatedEvictableEntity( 1 ) ); - session.getTransaction().commit(); - session.close(); + @JiraKey(value = "HHH-7912") + public void testEvictingDetachedEntity(SessionFactoryScope scope) { + scope.inTransaction( session -> { + session.persist( new IsolatedEvictableEntity( 1 ) ); + } ); - session = openSession(); - session.beginTransaction(); - IsolatedEvictableEntity entity = (IsolatedEvictableEntity) session.get( IsolatedEvictableEntity.class, 1 ); - assertTrue( session.contains( entity ) ); - // detach the entity - session.evict( entity ); - assertFalse( session.contains( entity ) ); - // evict it again the entity - session.evict( entity ); - assertFalse( session.contains( entity ) ); - session.getTransaction().commit(); - session.close(); + var e = scope.fromTransaction( session -> { + IsolatedEvictableEntity entity = (IsolatedEvictableEntity) session.get( IsolatedEvictableEntity.class, 1 ); + assertTrue( session.contains( entity ) ); + // detach the entity + session.evict( entity ); + assertFalse( session.contains( entity ) ); + // evict it again the entity + session.evict( entity ); + assertFalse( session.contains( entity ) ); + return entity; + } ); - session = openSession(); - session.beginTransaction(); - session.remove( entity ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( session -> { + session.remove( e ); + }); } @Test - @JiraKey( value = "HHH-7912" ) - public void testEvictingNonEntity() { - Session session = openSession(); - session.beginTransaction(); - try { - session.evict( new EvictionTest() ); - fail( "Expecting evict(non-entity) to throw IAE" ); - } - catch (IllegalArgumentException expected) { - } - session.getTransaction().commit(); - session.close(); + @JiraKey(value = "HHH-7912") + public void testEvictingNonEntity(SessionFactoryScope scope) { + scope.inSession( session -> { + try { + session.evict( new EvictionTest() ); + fail( "Expecting evict(non-entity) to throw IAE" ); + } + catch (IllegalArgumentException expected) { + } + } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/exception/SQLExceptionConversionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/exception/SQLExceptionConversionTest.java index 2eb63b0736de..7b47e24db020 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/exception/SQLExceptionConversionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/exception/SQLExceptionConversionTest.java @@ -18,140 +18,134 @@ import org.hibernate.exception.SQLGrammarException; import org.hibernate.testing.SkipForDialect; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; -import static org.junit.Assert.fail; /** * Implementation of SQLExceptionConversionTest. * * @author Steve Ebersole */ -public class SQLExceptionConversionTest extends BaseCoreFunctionalTestCase { - - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } - - @Override - public String[] getMappings() { - return new String[] {"exception/User.hbm.xml", "exception/Group.hbm.xml"}; - } +@DomainModel(xmlMappings = { + "org/hibernate/orm/test/exception/User.hbm.xml", + "org/hibernate/orm/test/exception/Group.hbm.xml" +}) +@SessionFactory +public class SQLExceptionConversionTest { @Test @SkipForDialect(value = HANADialect.class, comment = "Hana do not support FK violation checking") @SkipForDialect(value = TiDBDialect.class, comment = "TiDB do not support FK violation checking") - public void testIntegrityViolation() { - final Session session = openSession(); - session.beginTransaction(); - - session.doWork( - connection -> { - // Attempt to insert some bad values into the T_MEMBERSHIP table that should - // result in a constraint violation - PreparedStatement ps = null; - try { - final String sql = "INSERT INTO T_MEMBERSHIP (user_id, group_id) VALUES (?, ?)"; - ps = ((SessionImplementor)session).getJdbcCoordinator() - .getStatementPreparer() - .prepareStatement( sql ); - ps.setLong(1, 52134241); // Non-existent user_id - ps.setLong(2, 5342); // Non-existent group_id - ((SessionImplementor)session).getJdbcCoordinator().getResultSetReturn().executeUpdate( ps, sql ); - - fail("INSERT should have failed"); - } - catch (ConstraintViolationException ignore) { - // expected outcome + public void testIntegrityViolation(SessionFactoryScope scope) { + scope.inTransaction( session -> { + + session.doWork( + connection -> { + // Attempt to insert some bad values into the T_MEMBERSHIP table that should + // result in a constraint violation + PreparedStatement ps = null; + try { + final String sql = "INSERT INTO T_MEMBERSHIP (user_id, group_id) VALUES (?, ?)"; + ps = ((SessionImplementor) session).getJdbcCoordinator() + .getStatementPreparer() + .prepareStatement( sql ); + ps.setLong( 1, 52134241 ); // Non-existent user_id + ps.setLong( 2, 5342 ); // Non-existent group_id + ((SessionImplementor) session).getJdbcCoordinator().getResultSetReturn() + .executeUpdate( ps, sql ); + + fail( "INSERT should have failed" ); + } + catch (ConstraintViolationException ignore) { + // expected outcome + } + finally { + releaseStatement( session, ps ); + } } - finally { - releaseStatement( session, ps ); - } - } - ); - - session.getTransaction().rollback(); - session.close(); + ); + } ); } @Test - public void testBadGrammar() { - final Session session = openSession(); - session.beginTransaction(); - - session.doWork( - connection -> { - // prepare/execute a query against a non-existent table - PreparedStatement ps = null; - try { - final String sql = "SELECT user_id, user_name FROM tbl_no_there"; - ps = ((SessionImplementor)session).getJdbcCoordinator().getStatementPreparer().prepareStatement( sql ); - ((SessionImplementor)session).getJdbcCoordinator().getResultSetReturn().extract( ps, sql ); - - fail("SQL compilation should have failed"); - } - catch (SQLGrammarException ignored) { - // expected outcome + public void testBadGrammar(SessionFactoryScope scope) { + scope.inTransaction( session -> { + + session.doWork( + connection -> { + // prepare/execute a query against a non-existent table + PreparedStatement ps = null; + try { + final String sql = "SELECT user_id, user_name FROM tbl_no_there"; + ps = ((SessionImplementor) session).getJdbcCoordinator().getStatementPreparer() + .prepareStatement( sql ); + ((SessionImplementor) session).getJdbcCoordinator().getResultSetReturn().extract( ps, sql ); + + fail( "SQL compilation should have failed" ); + } + catch (SQLGrammarException ignored) { + // expected outcome + } + finally { + releaseStatement( session, ps ); + } } - finally { - releaseStatement( session, ps ); - } - } - ); + ); - session.getTransaction().rollback(); - session.close(); + } ); } @Test @JiraKey(value = "HHH-7357") - public void testNotNullConstraint() { - final Session session = openSession(); - session.beginTransaction(); - - final User user = new User(); - user.setUsername( "Lukasz" ); - session.persist( user ); - session.flush(); - - session.doWork( - connection -> { - final JdbcCoordinator jdbcCoordinator = ( (SessionImplementor) session ).getJdbcCoordinator(); - final StatementPreparer statementPreparer = jdbcCoordinator.getStatementPreparer(); - final ResultSetReturn resultSetReturn = jdbcCoordinator.getResultSetReturn(); - PreparedStatement ps = null; - try { - final String sql = "UPDATE T_USER SET user_name = ? WHERE user_id = ?"; - ps = statementPreparer.prepareStatement( sql ); - // Attempt to update username to NULL (NOT NULL constraint defined). - ps.setNull( 1, Types.VARCHAR ); - ps.setLong( 2, user.getId() ); - resultSetReturn.executeUpdate( ps, sql ); - - fail( "UPDATE should have failed because of not NULL constraint." ); - } - catch ( ConstraintViolationException ignore ) { - // expected outcome - } - finally { - releaseStatement( session, ps ); + public void testNotNullConstraint(SessionFactoryScope scope) { + scope.inTransaction( session -> { + + final User user = new User(); + user.setUsername( "Lukasz" ); + session.persist( user ); + session.flush(); + + session.doWork( + connection -> { + final JdbcCoordinator jdbcCoordinator = ((SessionImplementor) session).getJdbcCoordinator(); + final StatementPreparer statementPreparer = jdbcCoordinator.getStatementPreparer(); + final ResultSetReturn resultSetReturn = jdbcCoordinator.getResultSetReturn(); + PreparedStatement ps = null; + try { + final String sql = "UPDATE T_USER SET user_name = ? WHERE user_id = ?"; + ps = statementPreparer.prepareStatement( sql ); + // Attempt to update username to NULL (NOT NULL constraint defined). + ps.setNull( 1, Types.VARCHAR ); + ps.setLong( 2, user.getId() ); + resultSetReturn.executeUpdate( ps, sql ); + + fail( "UPDATE should have failed because of not NULL constraint." ); + } + catch (ConstraintViolationException ignore) { + // expected outcome + } + finally { + releaseStatement( session, ps ); + } } - } - ); + ); - session.getTransaction().rollback(); - session.close(); + } ); } private void releaseStatement(Session session, PreparedStatement ps) { if ( ps != null ) { try { - ((SessionImplementor) session).getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( ps ); + ((SessionImplementor) session).getJdbcCoordinator().getLogicalConnection().getResourceRegistry() + .release( ps ); } - catch ( Throwable ignore ) { + catch (Throwable ignore) { // ignore... } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/extendshbm/ExtendsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/extendshbm/ExtendsTest.java index e51e72665b1c..d4bb452a8b47 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/extendshbm/ExtendsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/extendshbm/ExtendsTest.java @@ -10,26 +10,25 @@ import org.hibernate.boot.registry.internal.StandardServiceRegistryImpl; import org.hibernate.testing.ServiceRegistryBuilder; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.AssertionsKt.assertNotNull; /** * @author Gavin King */ -public class ExtendsTest extends BaseUnitTestCase { +public class ExtendsTest { private StandardServiceRegistryImpl serviceRegistry; - @Before + @BeforeEach public void setUp() { serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry(); } - @After + @AfterEach public void tearDown() { ServiceRegistryBuilder.destroy( serviceRegistry ); } diff --git a/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/SessionFactory.java b/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/SessionFactory.java index 1be61c90b95c..fb8362803dd0 100644 --- a/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/SessionFactory.java +++ b/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/SessionFactory.java @@ -9,8 +9,10 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import java.util.function.Consumer; import org.hibernate.Interceptor; +import org.hibernate.boot.SessionFactoryBuilder; import org.hibernate.resource.jdbc.spi.StatementInspector; import org.hibernate.testing.jdbc.SQLStatementInspector; @@ -56,4 +58,13 @@ boolean useCollectingStatementInspector() default false; boolean applyCollectionsInDefaultFetchGroup() default true; + + Class> sessionFactoryConfigurer() default NoOpConfigurer.class; + + class NoOpConfigurer implements Consumer { + + @Override + public void accept(SessionFactoryBuilder sessionFactoryBuilder) { + } + } } diff --git a/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/SessionFactoryExtension.java b/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/SessionFactoryExtension.java index d985538590c5..e3ce5d98acc5 100644 --- a/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/SessionFactoryExtension.java +++ b/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/SessionFactoryExtension.java @@ -134,7 +134,7 @@ private static SessionFactoryScopeImpl createSessionFactoryScope( } if ( ! sessionFactoryConfig.interceptorClass().equals( Interceptor.class ) ) { - sessionFactoryBuilder.applyInterceptor( sessionFactoryConfig.interceptorClass().newInstance() ); + sessionFactoryBuilder.applyInterceptor( sessionFactoryConfig.interceptorClass().getDeclaredConstructor().newInstance() ); } final Class explicitInspectorClass = sessionFactoryConfig.statementInspectorClass(); @@ -146,6 +146,9 @@ else if ( ! explicitInspectorClass.equals( StatementInspector.class ) ) { } sessionFactoryBuilder.applyCollectionsInDefaultFetchGroup( sessionFactoryConfig.applyCollectionsInDefaultFetchGroup() ); + sessionFactoryConfig.sessionFactoryConfigurer().getDeclaredConstructor().newInstance() + .accept( sessionFactoryBuilder ); + final SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) sessionFactoryBuilder.build(); if ( sessionFactoryConfig.exportSchema() ) {