diff --git a/hibernate-community-dialects/src/test/java/org/hibernate/community/dialect/DerbyCustomSQLTest.java b/hibernate-community-dialects/src/test/java/org/hibernate/community/dialect/DerbyCustomSQLTest.java index f42f36526beb..6596f495a5cd 100644 --- a/hibernate-community-dialects/src/test/java/org/hibernate/community/dialect/DerbyCustomSQLTest.java +++ b/hibernate-community-dialects/src/test/java/org/hibernate/community/dialect/DerbyCustomSQLTest.java @@ -5,7 +5,7 @@ package org.hibernate.community.dialect; import org.hibernate.orm.test.sql.hand.custom.CustomStoredProcTestSupport; - +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.RequiresDialect; @@ -13,8 +13,8 @@ * @author Andrea Boriero */ @RequiresDialect(DerbyDialect.class) +@DomainModel( + xmlMappings = "org/hibernate/orm/test/derby/Mappings.hbm.xml" +) public class DerbyCustomSQLTest extends CustomStoredProcTestSupport { - public String[] getMappings() { - return new String[] {"derby/Mappings.hbm.xml"}; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/Customer.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/Customer.java index 0a3e61d914da..7142be2832c9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/Customer.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/Customer.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations; + import java.io.Serializable; import java.util.Collection; import java.util.SortedSet; @@ -31,7 +32,7 @@ public class Customer implements Serializable { Long id; String name; SortedSet tickets; - Collection discountTickets; + Collection discountTickets; Passport passport; public Customer() { @@ -69,11 +70,11 @@ public void setTickets(SortedSet tickets) { @OneToMany(targetEntity = Discount.class, cascade = CascadeType.ALL, mappedBy = "owner") @Cascade({ALL}) - public Collection getDiscountTickets() { + public Collection getDiscountTickets() { return discountTickets; } - public void setDiscountTickets(Collection collection) { + public void setDiscountTickets(Collection collection) { discountTickets = collection; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/Discount.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/Discount.java index 576c0f5f440c..ad7698a2c2ff 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/Discount.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/Discount.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations; + import java.io.Serializable; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/Passport.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/Passport.java index d38a7c7a70ef..92eafdf7554b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/Passport.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/Passport.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations; + import java.io.Serializable; import jakarta.persistence.Column; import jakarta.persistence.Entity; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/Ticket.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/Ticket.java index 5f28b73a2fa2..49a8578484eb 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/Ticket.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/Ticket.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations; + import java.io.Serializable; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -43,13 +44,9 @@ public void setNumber(String string) { public boolean equals(Object o) { if ( this == o ) return true; - if ( !( o instanceof Ticket ) ) return false; - - final Ticket ticket = (Ticket) o; - - if ( !number.equals( ticket.number ) ) return false; + if ( !(o instanceof Ticket ticket) ) return false; - return true; + return number.equals( ticket.number ); } public int hashCode() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/configuration/ConfigurationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/configuration/ConfigurationTest.java index 68605f8714d8..067fd08cb158 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/configuration/ConfigurationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/configuration/ConfigurationTest.java @@ -7,23 +7,25 @@ import org.hibernate.boot.registry.BootstrapServiceRegistry; import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; import org.hibernate.cfg.Configuration; +import org.hibernate.testing.orm.junit.BaseUnitTest; +import org.junit.jupiter.api.Test; -import org.junit.Assert; -import org.junit.Test; +import static org.assertj.core.api.Fail.fail; /** * @author Emmanuel Bernard */ +@BaseUnitTest public class ConfigurationTest { @Test - public void testMixPackageAndResourceOrdering() throws Exception { + public void testMixPackageAndResourceOrdering() { try (BootstrapServiceRegistry serviceRegistry = new BootstrapServiceRegistryBuilder().build()) { Configuration config = new Configuration( serviceRegistry ); config.addResource( "org/hibernate/orm/test/annotations/configuration/orm.xml" ); config.addPackage( "org.hibernate.orm/test.annotations.configuration" ); } catch( Exception e ) { - Assert.fail( "Processing package first when ORM.xml is used should not fail" ); + fail( "Processing package first when ORM.xml is used should not fail" ); } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/DerivedIdentitySimpleParentEmbeddedIdDepTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/DerivedIdentitySimpleParentEmbeddedIdDepTest.java index c5d07b87a0f8..d2cd38f39f8c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/DerivedIdentitySimpleParentEmbeddedIdDepTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/DerivedIdentitySimpleParentEmbeddedIdDepTest.java @@ -4,75 +4,83 @@ */ package org.hibernate.orm.test.annotations.derivedidentities.e1.b; -import org.hibernate.Session; - -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; +import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.orm.test.util.SchemaUtil; -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 static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; /** * @author Emmanuel Bernard */ -public class DerivedIdentitySimpleParentEmbeddedIdDepTest extends BaseNonConfigCoreFunctionalTestCase { - @Test - public void testManyToOne() throws Exception { - assertTrue( SchemaUtil.isColumnPresent( "Dependent", "emp_empId", metadata() ) ); - assertTrue( ! SchemaUtil.isColumnPresent( "Dependent", "empPK", metadata() ) ); - - Employee e = new Employee(); - e.empId = 1; - e.empName = "Emmanuel"; - Session s = openSession( ); - s.getTransaction().begin(); +@SessionFactory +@DomainModel( + annotatedClasses = { + Dependent.class, + Employee.class, + ExclusiveDependent.class + } +) +public class DerivedIdentitySimpleParentEmbeddedIdDepTest { - Dependent d = new Dependent(); - d.emp = e; - d.id = new DependentId(); - d.id.name = "Doggy"; - s.persist( d ); - s.persist( e ); - s.flush(); - s.clear(); - d = (Dependent) s.get( Dependent.class, d.id ); - assertEquals( d.id.empPK, d.emp.empId ); - s.getTransaction().rollback(); - s.close(); + @AfterEach + public void tearDown(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Test - public void testOneToOne() throws Exception { - assertTrue( SchemaUtil.isColumnPresent( "ExclusiveDependent", "FK", metadata() ) ); - assertTrue( ! SchemaUtil.isColumnPresent( "ExclusiveDependent", "empPK", metadata() ) ); + public void testManyToOne(SessionFactoryScope scope) { + MetadataImplementor metadata = scope.getMetadataImplementor(); + assertThat( SchemaUtil.isColumnPresent( "Dependent", "emp_empId", metadata ) ).isTrue(); + assertThat( !SchemaUtil.isColumnPresent( "Dependent", "empPK", metadata ) ).isTrue(); - Employee e = new Employee(); - e.empId = 1; - e.empName = "Emmanuel"; - Session s = openSession( ); - s.getTransaction().begin(); - s.persist( e ); - ExclusiveDependent d = new ExclusiveDependent(); - d.emp = e; - d.id = new DependentId(); - d.id.name = "Doggy"; - //d.id.empPK = e.empId; //FIXME not needed when foreign is enabled - s.persist( d ); - s.flush(); - s.clear(); - d = (ExclusiveDependent) s.get( ExclusiveDependent.class, d.id ); - assertEquals( d.id.empPK, d.emp.empId ); - s.getTransaction().rollback(); - s.close(); + scope.inTransaction( + session -> { + Employee e = new Employee(); + e.empId = 1; + e.empName = "Emmanuel"; + Dependent d = new Dependent(); + d.emp = e; + d.id = new DependentId(); + d.id.name = "Doggy"; + session.persist( d ); + session.persist( e ); + session.flush(); + session.clear(); + d = session.find( Dependent.class, d.id ); + assertThat( d.emp.empId ).isEqualTo( d.id.empPK ); + } + ); } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Dependent.class, - Employee.class, - ExclusiveDependent.class - }; + @Test + public void testOneToOne(SessionFactoryScope scope) { + MetadataImplementor metadata = scope.getMetadataImplementor(); + assertThat( SchemaUtil.isColumnPresent( "ExclusiveDependent", "FK", metadata ) ).isTrue(); + assertThat( !SchemaUtil.isColumnPresent( "ExclusiveDependent", "empPK", metadata ) ).isTrue(); + + scope.inTransaction( + session -> { + Employee e = new Employee(); + e.empId = 1; + e.empName = "Emmanuel"; + session.persist( e ); + ExclusiveDependent d = new ExclusiveDependent(); + d.emp = e; + d.id = new DependentId(); + d.id.name = "Doggy"; + //d.id.empPK = e.empId; //FIXME not needed when foreign is enabled + session.persist( d ); + session.flush(); + session.clear(); + d = session.find( ExclusiveDependent.class, d.id ); + assertThat( d.emp.empId ).isEqualTo( d.id.empPK ); + } + ); } + } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/IdMapManyToOneSpecjTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/IdMapManyToOneSpecjTest.java index d5fbd24216e5..6f0deed8eece 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/IdMapManyToOneSpecjTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/IdMapManyToOneSpecjTest.java @@ -4,121 +4,128 @@ */ package org.hibernate.orm.test.annotations.derivedidentities.e1.b.specjmapid; +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 java.math.BigDecimal; import java.util.List; -import org.hibernate.Session; -import org.hibernate.Transaction; - -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import static org.junit.Assert.assertEquals; /** * A test. * * @author Stale W. Pedersen */ -public class IdMapManyToOneSpecjTest extends BaseNonConfigCoreFunctionalTestCase { - - @Test - public void testComplexIdClass() { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - - Customer c1 = new Customer( - "foo", "bar", "contact1", "100", new BigDecimal( 1000 ), new BigDecimal( 1000 ), new BigDecimal( 1000 ) - ); - - s.persist( c1 ); - s.flush(); - s.clear(); - - Item boat = new Item(); - boat.setId( "1" ); - boat.setName( "cruiser" ); - boat.setPrice( new BigDecimal( 500 ) ); - boat.setDescription( "a boat" ); - boat.setCategory( 42 ); - - s.persist( boat ); - - - Item house = new Item(); - house.setId( "2" ); - house.setName( "blada" ); - house.setPrice( new BigDecimal( 5000 ) ); - house.setDescription( "a house" ); - house.setCategory( 74 ); - - s.persist( house ); - s.flush(); - s.clear(); - - c1.addInventory( boat, 10, new BigDecimal( 5000 ) ); - - c1.addInventory( house, 100, new BigDecimal( 50000 ) ); - s.merge( c1 ); - tx.commit(); - - - tx = s.beginTransaction(); - Customer c12 = ( Customer ) s.createQuery( "select c from Customer c" ).uniqueResult(); - - List inventory = c12.getInventories(); - - assertEquals( 2, inventory.size() ); - assertEquals( 10, inventory.get( 0 ).getQuantity() ); - assertEquals( "2", inventory.get(1).getVehicle().getId()); - - - Item house2 = new Item(); - house2.setId( "3" ); - house2.setName( "blada" ); - house2.setPrice( new BigDecimal( 5000 ) ); - house2.setDescription( "a house" ); - house2.setCategory( 74 ); - - s.persist( house2 ); - s.flush(); - s.clear(); - - c12.addInventory( house2, 200, new BigDecimal( 500000 ) ); - s.merge( c12 ); - - s.flush(); - s.clear(); - - Customer c13 = ( Customer ) s.createQuery( "select c from Customer c where c.id = " + c12.getId() ) - .uniqueResult(); - assertEquals( 3, c13.getInventories().size() ); - - - - Customer customer2 = new Customer( - "foo2", "bar2", "contact12", "1002", new BigDecimal( 10002 ), new BigDecimal( 10002 ), new BigDecimal( 1000 )); - customer2.setId(2); - s.persist(customer2); - - customer2.addInventory(boat, 10, new BigDecimal(400)); - customer2.addInventory(house2, 3, new BigDecimal(4000)); - s.merge(customer2); - - Customer c23 = ( Customer ) s.createQuery( "select c from Customer c where c.id = 2" ).uniqueResult(); - assertEquals( 2, c23.getInventories().size() ); - - tx.rollback(); - s.close(); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { +@SessionFactory +@DomainModel( + annotatedClasses = { Customer.class, CustomerInventory.class, CustomerInventoryPK.class, Item.class + } +) +public class IdMapManyToOneSpecjTest { - }; + @Test + public void testComplexIdClass(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Customer c1 = new Customer( + "foo", + "bar", + "contact1", + "100", + new BigDecimal( 1000 ), + new BigDecimal( 1000 ), + new BigDecimal( 1000 ) + ); + + session.persist( c1 ); + session.flush(); + session.clear(); + + Item boat = new Item(); + boat.setId( "1" ); + boat.setName( "cruiser" ); + boat.setPrice( new BigDecimal( 500 ) ); + boat.setDescription( "a boat" ); + boat.setCategory( 42 ); + + session.persist( boat ); + + Item house = new Item(); + house.setId( "2" ); + house.setName( "blada" ); + house.setPrice( new BigDecimal( 5000 ) ); + house.setDescription( "a house" ); + house.setCategory( 74 ); + + session.persist( house ); + session.flush(); + session.clear(); + + c1.addInventory( boat, 10, new BigDecimal( 5000 ) ); + + c1.addInventory( house, 100, new BigDecimal( 50000 ) ); + session.merge( c1 ); + session.getTransaction().commit(); + + session.beginTransaction(); + Customer c12 = session.createSelectionQuery( "select c from Customer c", Customer.class ) + .uniqueResult(); + + List inventory = c12.getInventories(); + + assertThat( inventory.size() ).isEqualTo( 2 ); + assertThat( inventory.get( 0 ).getQuantity() ).isEqualTo( 10 ); + assertThat( inventory.get( 1 ).getVehicle().getId() ).isEqualTo( "2" ); + + Item house2 = new Item(); + house2.setId( "3" ); + house2.setName( "blada" ); + house2.setPrice( new BigDecimal( 5000 ) ); + house2.setDescription( "a house" ); + house2.setCategory( 74 ); + + session.persist( house2 ); + session.flush(); + session.clear(); + + c12.addInventory( house2, 200, new BigDecimal( 500000 ) ); + session.merge( c12 ); + + session.flush(); + session.clear(); + + Customer c13 = session + .createSelectionQuery( "select c from Customer c where c.id = " + c12.getId(), Customer.class ) + .uniqueResult(); + assertThat( c13.getInventories().size() ).isEqualTo( 3 ); + + Customer customer2 = new Customer( + "foo2", + "bar2", + "contact12", + "1002", + new BigDecimal( 10002 ), + new BigDecimal( 10002 ), + new BigDecimal( 1000 ) + ); + customer2.setId( 2 ); + session.persist( customer2 ); + + customer2.addInventory( boat, 10, new BigDecimal( 400 ) ); + customer2.addInventory( house2, 3, new BigDecimal( 4000 ) ); + session.merge( customer2 ); + + Customer c23 = session.createQuery( "select c from Customer c where c.id = 2", Customer.class ) + .uniqueResult(); + assertThat( c23.getInventories().size() ).isEqualTo( 2 ); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/lazy/CompositeKeyDeleteTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/lazy/CompositeKeyDeleteTest.java index 82e3f41c1b9e..7950554ccbae 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/lazy/CompositeKeyDeleteTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/lazy/CompositeKeyDeleteTest.java @@ -4,100 +4,91 @@ */ package org.hibernate.orm.test.annotations.derivedidentities.e1.b.specjmapid.lazy; -import java.math.BigDecimal; -import java.util.List; - -import junit.framework.Assert; - -import org.hibernate.Session; -import org.hibernate.Transaction; import org.hibernate.orm.test.annotations.derivedidentities.e1.b.specjmapid.Item; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; - -public class CompositeKeyDeleteTest extends BaseCoreFunctionalTestCase { - -@Override -protected String getBaseForMappings() { - return ""; -} - -@Override -public String[] getMappings() { - return new String[] { "org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/lazy/order_orm.xml" }; -} -/** - * This test checks to make sure the non null column is not updated with a - * null value when a CustomerInventory is removed. - */ -@Test -public void testRemove() { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - - CustomerTwo c1 = new CustomerTwo( - "foo", "bar", "contact1", "100", new BigDecimal( 1000 ), new BigDecimal( 1000 ), new BigDecimal( 1000 ) - ); - - s.persist( c1 ); - s.flush(); - s.clear(); - - Item boat = new Item(); - boat.setId( "1" ); - boat.setName( "cruiser" ); - boat.setPrice( new BigDecimal( 500 ) ); - boat.setDescription( "a boat" ); - boat.setCategory( 42 ); - - s.persist( boat ); +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 java.math.BigDecimal; +import java.util.List; - Item house = new Item(); - house.setId( "2" ); - house.setName( "blada" ); - house.setPrice( new BigDecimal( 5000 ) ); - house.setDescription( "a house" ); - house.setCategory( 74 ); - - s.persist( house ); - s.flush(); - s.clear(); - - c1.addInventory( boat, 10, new BigDecimal( 5000 ) ); - - c1.addInventory( house, 100, new BigDecimal( 50000 ) ); - s.merge( c1 ); - Integer id = c1.getId(); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - - CustomerTwo c12 = ( CustomerTwo) s.createQuery( "select c from CustomerTwo c" ).uniqueResult(); - Assert.assertNotNull(c12); - List list = c12.getInventories(); - Assert.assertNotNull(list); - Assert.assertEquals(2, list.size()); - CustomerInventoryTwo ci = list.get(1); - list.remove(ci); - s.remove(ci); - s.flush(); - - tx.commit();//fail - s.close(); - -} - -@Override -protected Class[] getAnnotatedClasses() { - return new Class[] { - CustomerTwo.class, - CustomerInventoryTwo.class, - CustomerInventoryTwoPK.class, - Item.class - - }; -} +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + +@SessionFactory +@DomainModel( + xmlMappings = "org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/lazy/order_orm.xml", + annotatedClasses = { + CustomerTwo.class, + CustomerInventoryTwo.class, + CustomerInventoryTwoPK.class, + Item.class + } +) +public class CompositeKeyDeleteTest { + + /** + * This test checks to make sure the non null column is not updated with a + * null value when a CustomerInventory is removed. + */ + @Test + public void testRemove(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + CustomerTwo c1 = new CustomerTwo( + "foo", + "bar", + "contact1", + "100", + new BigDecimal( 1000 ), + new BigDecimal( 1000 ), + new BigDecimal( 1000 ) + ); + + session.persist( c1 ); + session.flush(); + session.clear(); + + Item boat = new Item(); + boat.setId( "1" ); + boat.setName( "cruiser" ); + boat.setPrice( new BigDecimal( 500 ) ); + boat.setDescription( "a boat" ); + boat.setCategory( 42 ); + + session.persist( boat ); + + Item house = new Item(); + house.setId( "2" ); + house.setName( "blada" ); + house.setPrice( new BigDecimal( 5000 ) ); + house.setDescription( "a house" ); + house.setCategory( 74 ); + + session.persist( house ); + session.flush(); + session.clear(); + + c1.addInventory( boat, 10, new BigDecimal( 5000 ) ); + + c1.addInventory( house, 100, new BigDecimal( 50000 ) ); + session.merge( c1 ); + } + ); + + scope.inTransaction( + session -> { + CustomerTwo c12 = session.createQuery( "select c from CustomerTwo c", CustomerTwo.class ) + .uniqueResult(); + assertThat( c12 ).isNotNull(); + List list = c12.getInventories(); + assertThat( list ).isNotNull(); + assertThat( list.size() ).isEqualTo( 2 ); + CustomerInventoryTwo ci = list.get( 1 ); + list.remove( ci ); + session.remove( ci ); + session.flush(); + } + ); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/c/DerivedIdentitySimpleParentEmbeddedDepTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/c/DerivedIdentitySimpleParentEmbeddedDepTest.java index ddd0c553e863..c85d8ef6e71e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/c/DerivedIdentitySimpleParentEmbeddedDepTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/c/DerivedIdentitySimpleParentEmbeddedDepTest.java @@ -5,38 +5,49 @@ package org.hibernate.orm.test.annotations.derivedidentities.e1.c; import org.hibernate.Session; - -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; +import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.orm.test.util.SchemaUtil; -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.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; /** * @author Emmanuel Bernard */ -public class DerivedIdentitySimpleParentEmbeddedDepTest extends BaseNonConfigCoreFunctionalTestCase { +@SessionFactory +@DomainModel( + annotatedClasses = { + Dependent.class, + Employee.class + } +) +public class DerivedIdentitySimpleParentEmbeddedDepTest { + @Test - public void testManyToOne() throws Exception { - assertTrue( SchemaUtil.isColumnPresent( "Dependent", "emp_empId", metadata() ) ); - assertTrue( ! SchemaUtil.isColumnPresent( "Dependent", "empPK", metadata() ) ); + public void testManyToOne(SessionFactoryScope scope) { + MetadataImplementor metadata = scope.getMetadataImplementor(); + + assertThat( SchemaUtil.isColumnPresent( "Dependent", "emp_empId", metadata ) ).isTrue(); + assertThat( !SchemaUtil.isColumnPresent( "Dependent", "empPK", metadata ) ).isTrue(); Employee e = new Employee(); e.empId = 1; e.empName = "Emmanuel"; - Session s = openSession( ); - s.getTransaction().begin(); - s.persist( e ); - Dependent d = new Dependent(); - d.emp = e; - d.name = "Doggy"; - s.persist( d ); - s.flush(); - s.clear(); - d = getDerivedClassById( e, d.name, s ); - assertEquals( e.empId, d.emp.empId ); - s.getTransaction().rollback(); - s.close(); + scope.inTransaction( + session -> { + session.persist( e ); + Dependent d = new Dependent(); + d.emp = e; + d.name = "Doggy"; + session.persist( d ); + session.flush(); + session.clear(); + d = getDerivedClassById( e, d.name, session ); + assertThat( d.emp.empId ).isEqualTo( e.empId ); + } + ); } private Dependent getDerivedClassById(Employee e, String name, Session s) { @@ -47,12 +58,4 @@ private Dependent getDerivedClassById(Employee e, String name, Session s) { .setParameter( "name", name ) .uniqueResult(); } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Dependent.class, - Employee.class - }; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e4/b/DerivedIdentitySimpleParentSimpleDepMapsIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e4/b/DerivedIdentitySimpleParentSimpleDepMapsIdTest.java index 8a1240d9ec29..be5de215e6a9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e4/b/DerivedIdentitySimpleParentSimpleDepMapsIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e4/b/DerivedIdentitySimpleParentSimpleDepMapsIdTest.java @@ -4,121 +4,120 @@ */ package org.hibernate.orm.test.annotations.derivedidentities.e4.b; -import java.util.Date; - -import org.hibernate.Session; - -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; +import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.orm.test.util.SchemaUtil; -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.Date; -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 static org.assertj.core.api.AssertionsForClassTypes.assertThat; /** * @author Emmanuel Bernard */ -public class DerivedIdentitySimpleParentSimpleDepMapsIdTest extends BaseNonConfigCoreFunctionalTestCase { +@SessionFactory +@DomainModel( + annotatedClasses = { + MedicalHistory.class, + Person.class, + FinancialHistory.class + } +) +public class DerivedIdentitySimpleParentSimpleDepMapsIdTest { + + @AfterEach + public void tearDown(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); + } + @Test - public void testOneToOneExplicitJoinColumn() throws Exception { - assertTrue( SchemaUtil.isColumnPresent( "MedicalHistory", "FK", metadata() ) ); - assertTrue( ! SchemaUtil.isColumnPresent( "MedicalHistory", "id", metadata() ) ); + public void testOneToOneExplicitJoinColumn(SessionFactoryScope scope) { + MetadataImplementor metadata = scope.getMetadataImplementor(); + + assertThat( SchemaUtil.isColumnPresent( "MedicalHistory", "FK", metadata ) ).isTrue(); + assertThat( !SchemaUtil.isColumnPresent( "MedicalHistory", "id", metadata ) ).isTrue(); Person e = new Person(); e.ssn = "aaa"; - Session s = openSession( ); - s.getTransaction().begin(); - s.persist( e ); - MedicalHistory d = new MedicalHistory(); - d.patient = e; - //d.id = "aaa"; //FIXME not needed when foreign is enabled - s.persist( d ); - s.flush(); - s.clear(); - d = (MedicalHistory) s.get( MedicalHistory.class, d.id ); - assertEquals( d.id, d.patient.ssn ); - d.lastupdate = new Date(); - s.flush(); - s.clear(); - d = (MedicalHistory) s.get( MedicalHistory.class, d.id ); - assertNotNull( d.lastupdate ); - s.getTransaction().rollback(); - s.close(); + scope.inTransaction( + session -> { + session.persist( e ); + MedicalHistory d = new MedicalHistory(); + d.patient = e; + //d.id = "aaa"; //FIXME not needed when foreign is enabled + session.persist( d ); + session.flush(); + session.clear(); + d = session.find( MedicalHistory.class, d.id ); + assertThat( d.patient.ssn ).isEqualTo( d.id ); + d.lastupdate = new Date(); + session.flush(); + session.clear(); + d = session.find( MedicalHistory.class, d.id ); + assertThat( d.lastupdate ).isNotNull(); + } + ); } @Test - public void testManyToOneExplicitJoinColumn() throws Exception { - assertTrue( SchemaUtil.isColumnPresent( "FinancialHistory", "FK", metadata() ) ); - assertTrue( ! SchemaUtil.isColumnPresent( "FinancialHistory", "id", metadata() ) ); + public void testManyToOneExplicitJoinColumn(SessionFactoryScope scope) { + MetadataImplementor metadata = scope.getMetadataImplementor(); + + assertThat( SchemaUtil.isColumnPresent( "FinancialHistory", "FK", metadata ) ).isTrue(); + assertThat( !SchemaUtil.isColumnPresent( "FinancialHistory", "id", metadata ) ).isTrue(); Person e = new Person(); e.ssn = "aaa"; - Session s = openSession( ); - s.getTransaction().begin(); - s.persist( e ); - FinancialHistory d = new FinancialHistory(); - d.patient = e; - //d.id = "aaa"; //FIXME not needed when foreign is enabled - s.persist( d ); - s.flush(); - s.clear(); - d = (FinancialHistory) s.get( FinancialHistory.class, d.id ); - assertEquals( d.id, d.patient.ssn ); - d.lastupdate = new Date(); - s.flush(); - s.clear(); - d = (FinancialHistory) s.get( FinancialHistory.class, d.id ); - assertNotNull( d.lastupdate ); - s.getTransaction().rollback(); - s.close(); + scope.inTransaction( + session -> { + session.persist( e ); + FinancialHistory d = new FinancialHistory(); + d.patient = e; + //d.id = "aaa"; //FIXME not needed when foreign is enabled + session.persist( d ); + session.flush(); + session.clear(); + d = session.find( FinancialHistory.class, d.id ); + assertThat( d.patient.ssn ).isEqualTo( d.id ); + d.lastupdate = new Date(); + session.flush(); + session.clear(); + d = session.find( FinancialHistory.class, d.id ); + assertThat( d.lastupdate ).isNotNull(); + } + ); } @Test - public void testExplicitlyAssignedDependentIdAttributeValue() { + public void testExplicitlyAssignedDependentIdAttributeValue(SessionFactoryScope scope) { // even though the id is by definition generated (using the "foreign" strategy), JPA // still does allow manually setting the generated id attribute value which providers // are expected to promptly disregard :? - Session s = openSession(); - s.beginTransaction(); Person person = new Person( "123456789" ); MedicalHistory medicalHistory = new MedicalHistory( "987654321", person ); - s.persist( person ); - s.persist( medicalHistory ); - s.getTransaction().commit(); - s.close(); - + scope.inTransaction( + session -> { + session.persist( person ); + session.persist( medicalHistory ); + } + ); // again, even though we specified an id value of "987654321" prior to persist, // Hibernate should have replaced that with the "123456789" from the associated // person - assertEquals( person.ssn, medicalHistory.patient.ssn ); - assertEquals( person, medicalHistory.patient ); - assertEquals( person.ssn, medicalHistory.id ); - - s = openSession(); - s.beginTransaction(); - // Should return null... - MedicalHistory separateMedicalHistory = (MedicalHistory) s.get( MedicalHistory.class, "987654321" ); - assertNull( separateMedicalHistory ); - // Now we should find it... - separateMedicalHistory = (MedicalHistory) s.get( MedicalHistory.class, "123456789" ); - assertNotNull( separateMedicalHistory ); - s.getTransaction().commit(); - s.close(); + assertThat( medicalHistory.patient.ssn ).isEqualTo( person.ssn ); + assertThat( medicalHistory.patient ).isEqualTo( person ); + assertThat( medicalHistory.id ).isEqualTo( person.ssn ); - s = openSession(); - s.beginTransaction(); - s.remove( medicalHistory ); - s.remove( person ); - s.getTransaction().commit(); - s.close(); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - MedicalHistory.class, - Person.class, - FinancialHistory.class - }; + scope.inTransaction( + session -> { + MedicalHistory separateMedicalHistory = session.find( MedicalHistory.class, "987654321" ); + assertThat( separateMedicalHistory ).isNull(); + // Now we should find it... + separateMedicalHistory = session.find( MedicalHistory.class, "123456789" ); + assertThat( separateMedicalHistory ).isNotNull(); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e5/c/ForeignGeneratorViaMapsIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e5/c/ForeignGeneratorViaMapsIdTest.java index 8f3bb783e8ca..fad36eae8e3b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e5/c/ForeignGeneratorViaMapsIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e5/c/ForeignGeneratorViaMapsIdTest.java @@ -4,45 +4,47 @@ */ package org.hibernate.orm.test.annotations.derivedidentities.e5.c; -import org.hibernate.Session; - -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; +import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.orm.test.util.SchemaUtil; -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.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; /** * @author Emmanuel Bernard */ -public class ForeignGeneratorViaMapsIdTest extends BaseNonConfigCoreFunctionalTestCase { +@SessionFactory +@DomainModel( + annotatedClasses = { + MedicalHistory.class, + Person.class + } +) +public class ForeignGeneratorViaMapsIdTest { + @Test - public void testForeignGenerator() throws Exception { - assertTrue( SchemaUtil.isColumnPresent( "MedicalHistory", "patient_id", metadata() ) ); + public void testForeignGenerator(SessionFactoryScope scope) { + MetadataImplementor metadata = scope.getMetadataImplementor(); - Person e = new Person(); - Session s = openSession( ); - s.getTransaction().begin(); - s.persist( e ); - MedicalHistory d = new MedicalHistory(); - d.patient = e; - s.persist( d ); - s.flush(); - s.clear(); - d = s.get( MedicalHistory.class, e.id); - assertEquals( e.id, d.id ); - s.remove( d ); - s.remove( d.patient ); - s.getTransaction().rollback(); - s.close(); - } + assertThat( SchemaUtil.isColumnPresent( "MedicalHistory", "patient_id", metadata ) ).isTrue(); - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - MedicalHistory.class, - Person.class - }; + Person e = new Person(); + scope.inTransaction( + session -> { + session.persist( e ); + MedicalHistory d = new MedicalHistory(); + d.patient = e; + session.persist( d ); + session.flush(); + session.clear(); + d = session.find( MedicalHistory.class, e.id ); + assertThat( d.id ).isEqualTo( e.id ); + session.remove( d ); + session.remove( d.patient ); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/duplicatedgenerator/DuplicateTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/duplicatedgenerator/DuplicateTest.java index c386a2babaf4..b3cd0286ddcd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/duplicatedgenerator/DuplicateTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/duplicatedgenerator/DuplicateTest.java @@ -12,13 +12,17 @@ import org.hibernate.service.ServiceRegistry; import org.hibernate.testing.ServiceRegistryBuilder; -import org.junit.Assert; -import org.junit.Test; +import org.hibernate.testing.orm.junit.BaseUnitTest; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Fail.fail; /** * @author Emmanuel Bernard */ +@BaseUnitTest public class DuplicateTest { + @Test public void testDuplicateEntityName() { Configuration cfg = new Configuration(); @@ -33,7 +37,7 @@ public void testDuplicateEntityName() { cfg.addResource( "org/hibernate/orm/test/annotations/duplicatedgenerator/orm.xml" ); serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry( cfg.getProperties() ); sf = cfg.buildSessionFactory( serviceRegistry ); - Assert.fail( "Should not be able to map the same entity name twice" ); + fail( "Should not be able to map the same entity name twice" ); } catch (DuplicateMappingException ae) { //success diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/BasicHibernateAnnotationsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/BasicHibernateAnnotationsTest.java index 46f2e6c0f9a6..eefa756232c8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/BasicHibernateAnnotationsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/BasicHibernateAnnotationsTest.java @@ -4,142 +4,152 @@ */ package org.hibernate.orm.test.annotations.entity; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Currency; -import java.util.Date; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Set; - +import jakarta.persistence.OptimisticLockException; import jakarta.persistence.RollbackException; import org.hibernate.Hibernate; -import org.hibernate.Session; -import org.hibernate.Transaction; import org.hibernate.community.dialect.DerbyDialect; import org.hibernate.dialect.CockroachDialect; import org.hibernate.dialect.OracleDialect; import org.hibernate.dialect.PostgreSQLDialect; import org.hibernate.dialect.SybaseDialect; -import org.hibernate.query.Query; +import org.hibernate.engine.spi.SessionFactoryImplementor; +import org.hibernate.testing.orm.junit.DialectFeatureChecks; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.RequiresDialectFeature; +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 org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; -import org.hibernate.testing.SkipForDialect; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; - -import jakarta.persistence.OptimisticLockException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Currency; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Fail.fail; /** * @author Emmanuel Bernard */ -public class BasicHibernateAnnotationsTest extends BaseCoreFunctionalTestCase { - @Override - protected boolean isCleanupTestDataRequired() { - return true; +@SessionFactory +@DomainModel( + annotatedClasses = { + Forest.class, + Tree.class, + Ransom.class, + ZipCode.class, + Flight.class, + Name.class, + FormalLastName.class, + ContactDetails.class, + Topic.class, + Narrative.class, + Drill.class, + PowerDrill.class, + SoccerTeam.class, + Player.class, + Doctor.class, + PhoneNumberConverter.class + }, + annotatedPackageNames = "org.hibernate.orm.test.annotations.entity" +) +public class BasicHibernateAnnotationsTest { + + @AfterEach + public void tearDown(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } + @Test - @RequiresDialectFeature( DialectChecks.SupportsExpectedLobUsagePattern.class ) - public void testEntity() throws Exception { + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsExpectedLobUsagePattern.class) + public void testEntity(SessionFactoryScope scope) throws Exception { Forest forest = new Forest(); forest.setName( "Fontainebleau" ); - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - s.persist( forest ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - forest = (Forest) s.get( Forest.class, forest.getId() ); - assertNotNull( forest ); - forest.setName( "Fontainebleau" ); - //should not execute SQL update - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - forest = (Forest) s.get( Forest.class, forest.getId() ); - assertNotNull( forest ); - forest.setLength( 23 ); - //should execute dynamic SQL update - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - s.remove( s.get( Forest.class, forest.getId() ) ); - tx.commit(); - s.close(); + scope.inTransaction( + session -> session.persist( forest ) + ); + + scope.inTransaction( + session -> { + Forest f = session.find( Forest.class, forest.getId() ); + assertThat( f ).isNotNull(); + f.setName( "Fontainebleau" ); + //should not execute SQL update + } + ); + + scope.inTransaction( + session -> { + Forest f = session.find( Forest.class, forest.getId() ); + assertThat( f ).isNotNull(); + f.setLength( 23 ); + //should execute dynamic SQL update + } + ); + + scope.inTransaction( + session -> session.remove( session.find( Forest.class, forest.getId() ) ) + ); } @Test - @RequiresDialectFeature( DialectChecks.SupportsExpectedLobUsagePattern.class ) - public void testVersioning() throws Exception { + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsExpectedLobUsagePattern.class) + public void testVersioning(SessionFactoryScope scope) { Forest forest = new Forest(); forest.setName( "Fontainebleau" ); forest.setLength( 33 ); - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - s.persist( forest ); - tx.commit(); - s.close(); - - Session parallelSession = openSession(); - Transaction parallelTx = parallelSession.beginTransaction(); - s = openSession(); - tx = s.beginTransaction(); - - forest = (Forest) parallelSession.get( Forest.class, forest.getId() ); - Forest reloadedForest = (Forest) s.get( Forest.class, forest.getId() ); - reloadedForest.setLength( 11 ); - assertNotSame( forest, reloadedForest ); - tx.commit(); - s.close(); - - forest.setLength( 22 ); - try { - parallelTx.commit(); - fail( "All optimistic locking should have make it fail" ); - } - catch (Exception e) { - if (getDialect() instanceof CockroachDialect) { - // CockroachDB always runs in SERIALIZABLE isolation, and throws a RollbackException - assertTrue( e instanceof RollbackException ); - } else { - assertTrue( e instanceof OptimisticLockException ); - } - parallelTx.rollback(); - } - finally { - parallelSession.close(); - } - - s = openSession(); - tx = s.beginTransaction(); - s.remove( s.get( Forest.class, forest.getId() ) ); - tx.commit(); - s.close(); + + scope.inTransaction( + session -> session.persist( forest ) + ); + + scope.inSession( + parallelSession -> { + try { + parallelSession.getTransaction().begin(); + Forest forestFromParallelSession = scope.fromTransaction( + s -> { + Forest f = parallelSession.find( Forest.class, forest.getId() ); + Forest reloadedForest = s.find( Forest.class, forest.getId() ); + reloadedForest.setLength( 11 ); + assertThat( reloadedForest ).isNotSameAs( f ); + return f; + } + ); + forestFromParallelSession.setLength( 22 ); + parallelSession.getTransaction().commit(); + fail( "All optimistic locking should have make it fail" ); + } + catch (Exception e) { + if ( scope.getSessionFactory().getJdbcServices().getDialect() instanceof CockroachDialect ) { + // CockroachDB always runs in SERIALIZABLE isolation, and throws a RollbackException + assertThat( e ).isInstanceOf( RollbackException.class ); + } + else { + assertThat( e ).isInstanceOf( OptimisticLockException.class ); + } + + if ( parallelSession.getTransaction().isActive() ) { + parallelSession.getTransaction().rollback(); + } + } + } + ); + + scope.inTransaction( + session -> session.remove( session.find( Forest.class, forest.getId() ) ) + ); } @Test - @RequiresDialectFeature(DialectChecks.SupportsExpectedLobUsagePattern.class) - public void testWhereClause() throws Exception { + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsExpectedLobUsagePattern.class) + public void testWhereClause(SessionFactoryScope scope) { List doctors = new ArrayList<>(); Doctor goodDoctor = new Doctor(); @@ -168,284 +178,275 @@ public void testWhereClause() throws Exception { team.setName( "New team" ); team.getPhysiologists().addAll( doctors ); - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - - for ( Doctor doctor : doctors ) { - s.persist( doctor ); - } - - s.persist( team ); - - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); + scope.inTransaction( + session -> { + for ( Doctor doctor : doctors ) { + session.persist( doctor ); + } - Query query = s.createQuery( "from " + Doctor.class.getName(), Doctor.class ); - List list = query.getResultList(); + session.persist( team ); + } + ); - assertEquals( 2, list.size() ); + scope.inTransaction( + session -> { + List list = session.createSelectionQuery( "from " + Doctor.class.getName(), Doctor.class ) + .getResultList(); - assertEquals( list.get( 0 ).getName(), goodDoctor.getName() ); - assertEquals( list.get( 1 ).getName(), docExperiencedUnlicensed.getName() ); + assertThat( list.size() ).isEqualTo( 2 ); - SoccerTeam loadedTeam = s.get( SoccerTeam.class, team.getId() ); + assertThat( list.get( 0 ).getName() ).isEqualTo( goodDoctor.getName() ); + assertThat( list.get( 1 ).getName() ).isEqualTo( docExperiencedUnlicensed.getName() ); - assertEquals( 1, loadedTeam.getPhysiologists().size() ); - assertEquals( goodDoctor.getName(), loadedTeam.getPhysiologists().get( 0 ).getName() ); + SoccerTeam loadedTeam = session.find( SoccerTeam.class, team.getId() ); - tx.commit(); - s.close(); + assertThat( loadedTeam.getPhysiologists().size() ).isEqualTo( 1 ); + assertThat( loadedTeam.getPhysiologists().get( 0 ).getName() ).isEqualTo( goodDoctor.getName() ); + } + ); } @Test - @RequiresDialectFeature( DialectChecks.SupportsExpectedLobUsagePattern.class ) - public void testType() throws Exception { + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsExpectedLobUsagePattern.class) + public void testType(SessionFactoryScope scope) { Forest f = new Forest(); f.setName( "Broceliande" ); String description = "C'est une enorme foret enchantee ou vivais Merlin et toute la clique"; f.setLongDescription( description ); - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - s.persist( f ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - f = s.get( Forest.class, f.getId() ); - assertNotNull( f ); - assertEquals( description, f.getLongDescription() ); - s.remove( f ); - tx.commit(); - s.close(); + scope.inTransaction( + session -> session.persist( f ) + ); + scope.inTransaction( + session -> { + Forest forest = session.find( Forest.class, f.getId() ); + assertThat( forest ).isNotNull(); + assertThat( forest.getLongDescription() ).isEqualTo( description ); + session.remove( forest ); + } + ); } @Test - public void testLoading() throws Exception { - final Forest created = fromTransaction( (session) -> { + public void testLoading(SessionFactoryScope scope) { + final Forest created = scope.fromTransaction( (session) -> { Forest f = new Forest(); session.persist( f ); return f; } ); // getReference - inTransaction( (session) -> { + scope.inTransaction( (session) -> { final Forest reference = session.getReference( Forest.class, created.getId() ); - assertFalse( Hibernate.isInitialized( reference ) ); + assertThat( Hibernate.isInitialized( reference ) ).isFalse(); } ); // find - inTransaction( (session) -> { + scope.inTransaction( (session) -> { final Forest reference = session.find( Forest.class, created.getId() ); - assertTrue( Hibernate.isInitialized( reference ) ); + assertThat( Hibernate.isInitialized( reference ) ).isTrue(); } ); } @Test - public void testCache() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); + public void testCache(SessionFactoryScope scope) { ZipCode zc = new ZipCode(); - zc.code = "92400"; - s.persist( zc ); - tx.commit(); - s.close(); - sessionFactory().getStatistics().clear(); - sessionFactory().getStatistics().setStatisticsEnabled( true ); - sessionFactory().getCache().evictEntityData( ZipCode.class ); - s = openSession(); - tx = s.beginTransaction(); - s.get( ZipCode.class, zc.code ); - assertEquals( 1, sessionFactory().getStatistics().getSecondLevelCachePutCount() ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - s.get( ZipCode.class, zc.code ); - assertEquals( 1, sessionFactory().getStatistics().getSecondLevelCacheHitCount() ); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + zc.code = "92400"; + session.persist( zc ); + } + ); + SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); + sessionFactory.getStatistics().clear(); + sessionFactory.getStatistics().setStatisticsEnabled( true ); + sessionFactory.getCache().evictEntityData( ZipCode.class ); + + scope.inTransaction( + session -> { + session.find( ZipCode.class, zc.code ); + assertThat( sessionFactory.getStatistics().getSecondLevelCachePutCount() ).isEqualTo( 1 ); + } + ); + + scope.inTransaction( + session -> { + session.find( ZipCode.class, zc.code ); + assertThat( sessionFactory.getStatistics().getSecondLevelCacheHitCount() ).isEqualTo( 1 ); + } + ); } @Test - public void testFilterOnCollection() { - - Session s = openSession(); - Transaction tx = s.beginTransaction(); - - Topic topic = new Topic(); - Narrative n1 = new Narrative(); - n1.setState("published"); - topic.addNarrative(n1); - - Narrative n2 = new Narrative(); - n2.setState("draft"); - topic.addNarrative(n2); - - s.persist(topic); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - topic = (Topic) s.getReference( Topic.class, topic.getId() ); - - s.enableFilter("byState").setParameter("state", "published"); - topic = (Topic) s.getReference( Topic.class, topic.getId() ); - assertNotNull(topic); - assertTrue(topic.getNarratives().size() == 1); - assertEquals("published", topic.getNarratives().iterator().next().getState()); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - s.createQuery( "delete from " + Narrative.class.getSimpleName() ).executeUpdate(); - tx.commit(); - s.close(); + public void testFilterOnCollection(SessionFactoryScope scope) { + Topic t = new Topic(); + scope.inTransaction( + session -> { + Narrative n1 = new Narrative(); + n1.setState( "published" ); + t.addNarrative( n1 ); + + Narrative n2 = new Narrative(); + n2.setState( "draft" ); + t.addNarrative( n2 ); + + session.persist( t ); + } + ); + + scope.inTransaction( + session -> { + Topic topic = session.getReference( Topic.class, t.getId() ); + + session.enableFilter( "byState" ).setParameter( "state", "published" ); + topic = session.getReference( Topic.class, topic.getId() ); + assertThat( topic ).isNotNull(); + assertThat( topic.getNarratives().size() ).isEqualTo( 1 ); + assertThat( topic.getNarratives().iterator().next().getState() ).isEqualTo( "published" ); + } + ); + + scope.inTransaction( + session -> session.createMutationQuery( "delete from " + Narrative.class.getSimpleName() ) + .executeUpdate() + ); } @Test - public void testCascadedDeleteOfChildEntitiesBug2() { + public void testCascadedDeleteOfChildEntitiesBug2(SessionFactoryScope scope) { // Relationship is one SoccerTeam to many Players. // Create a SoccerTeam (parent) and three Players (child). // Verify that the count of Players is correct. // Clear the SoccerTeam reference Players. // The orphanRemoval should remove the Players automatically. // @OneToMany(mappedBy="name", orphanRemoval=true) - Session s = openSession(); - Transaction tx = s.beginTransaction(); + SoccerTeam t = new SoccerTeam(); + scope.inTransaction( + session -> { + Player player1 = new Player(); + player1.setName( "Shalrie Joseph" ); + t.addPlayer( player1 ); + + Player player2 = new Player(); + player2.setName( "Taylor Twellman" ); + t.addPlayer( player2 ); + + Player player3 = new Player(); + player3.setName( "Steve Ralston" ); + t.addPlayer( player3 ); + session.persist( t ); + } + ); - SoccerTeam team = new SoccerTeam(); - int teamid = team.getId(); - Player player1 = new Player(); - player1.setName("Shalrie Joseph"); - team.addPlayer(player1); - - Player player2 = new Player(); - player2.setName("Taylor Twellman"); - team.addPlayer(player2); - - Player player3 = new Player(); - player3.setName("Steve Ralston"); - team.addPlayer(player3); - s.persist(team); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - team = (SoccerTeam)s.merge(team); - int count = ( (Long) s.createQuery( "select count(*) from Player" ).list().get( 0 ) ).intValue(); - assertEquals("expected count of 3 but got = " + count, count, 3); - - // clear references to players, this should orphan the players which should - // in turn trigger orphanRemoval logic. - team.getPlayers().clear(); + scope.inTransaction( + session -> { + SoccerTeam team = session.merge( t ); + Long count = session.createSelectionQuery( "select count(*) from Player", Long.class ).list() + .get( 0 ); + assertThat( count ).isEqualTo( 3 ); + + // clear references to players, this should orphan the players which should + // in turn trigger orphanRemoval logic. + team.getPlayers().clear(); // count = ( (Long) s.createQuery( "select count(*) from Player" ).iterate().next() ).intValue(); // assertEquals("expected count of 0 but got = " + count, count, 0); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - count = ( (Long) s.createQuery( "select count(*) from Player" ).list().get( 0 ) ).intValue(); - assertEquals("expected count of 0 but got = " + count, count, 0); - tx.commit(); - s.close(); + } + ); + + + scope.inTransaction( + session -> { + Long count = session.createSelectionQuery( "select count(*) from Player", Long.class ).list() + .get( 0 ); + assertThat( count ).isEqualTo( 0 ); + } + ); } @Test - public void testCascadedDeleteOfChildOneToOne() { + public void testCascadedDeleteOfChildOneToOne(SessionFactoryScope scope) { // create two single player teams (for one versus one match of soccer) // and associate teams with players via the special OneVOne methods. // Clear the Team reference to players, which should orphan the teams. // Orphaning the team should delete the team. - Session s = openSession(); - Transaction tx = s.beginTransaction(); + scope.inTransaction( + session -> { + SoccerTeam team = new SoccerTeam(); + team.setName( "Shalrie's team" ); + Player player1 = new Player(); + player1.setName( "Shalrie Joseph" ); + team.setOneVonePlayer( player1 ); + player1.setOneVoneTeam( team ); + + session.persist( team ); + SoccerTeam team2 = new SoccerTeam(); + team2.setName( "Taylor's team" ); + Player player2 = new Player(); + player2.setName( "Taylor Twellman" ); + team2.setOneVonePlayer( player2 ); + player2.setOneVoneTeam( team2 ); + session.persist( team2 ); + + session.getTransaction().commit(); + session.getTransaction().begin(); + session.clear(); + team2 = session.getReference( team2.getClass(), team2.getId() ); + team = session.getReference( team.getClass(), team.getId() ); + Long count = session.createSelectionQuery( "select count(*) from Player", Long.class ).list() + .get( 0 ); + assertThat( count ).isEqualTo( 2 ); + + // clear references to players, this should orphan the players which should + // in turn trigger orphanRemoval logic. + team.setOneVonePlayer( null ); + team2.setOneVonePlayer( null ); + } + ); - SoccerTeam team = new SoccerTeam(); - team.setName("Shalrie's team"); - Player player1 = new Player(); - player1.setName("Shalrie Joseph"); - team.setOneVonePlayer(player1); - player1.setOneVoneTeam(team); - - s.persist(team); - - SoccerTeam team2 = new SoccerTeam(); - team2.setName("Taylor's team"); - Player player2 = new Player(); - player2.setName("Taylor Twellman"); - team2.setOneVonePlayer(player2); - player2.setOneVoneTeam(team2); - s.persist(team2); - tx.commit(); - - tx = s.beginTransaction(); - s.clear(); - team2 = (SoccerTeam)s.getReference(team2.getClass(), team2.getId()); - team = (SoccerTeam)s.getReference(team.getClass(), team.getId()); - int count = ( (Long) s.createQuery( "select count(*) from Player" ).list().get( 0 ) ).intValue(); - assertEquals("expected count of 2 but got = " + count, count, 2); - - // clear references to players, this should orphan the players which should - // in turn trigger orphanRemoval logic. - team.setOneVonePlayer(null); - team2.setOneVonePlayer(null); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - count = ( (Long) s.createQuery( "select count(*) from Player" ).list().get( 0 ) ).intValue(); - assertEquals("expected count of 0 but got = " + count, count, 0); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + Long count = session.createSelectionQuery( "select count(*) from Player", Long.class ).list() + .get( 0 ); + assertThat( count ).isEqualTo( 0 ); + } + ); } @Test - public void testFilter() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - s.createQuery( "delete Forest" ).executeUpdate(); - Forest f1 = new Forest(); - f1.setLength( 2 ); - s.persist( f1 ); - Forest f2 = new Forest(); - f2.setLength( 20 ); - s.persist( f2 ); - Forest f3 = new Forest(); - f3.setLength( 200 ); - s.persist( f3 ); - tx.commit(); - s.close(); - s = openSession(); - tx = s.beginTransaction(); - s.enableFilter( "betweenLength" ).setParameter( "minLength", 5 ).setParameter( "maxLength", 50 ); - long count = ( (Long) s.createQuery( "select count(*) from Forest" ).list().get( 0 ) ).intValue(); - assertEquals( 1, count ); - s.disableFilter( "betweenLength" ); - s.enableFilter( "minLength" ).setParameter( "minLength", 5 ); - count = ( (Long) s.createQuery( "select count(*) from Forest" ).list().get( 0 ) ).longValue(); - assertEquals( 2l, count ); - s.disableFilter( "minLength" ); - tx.rollback(); - s.close(); + public void testFilter(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.createMutationQuery( "delete Forest" ).executeUpdate(); + Forest f1 = new Forest(); + f1.setLength( 2 ); + session.persist( f1 ); + Forest f2 = new Forest(); + f2.setLength( 20 ); + session.persist( f2 ); + Forest f3 = new Forest(); + f3.setLength( 200 ); + session.persist( f3 ); + } + ); + + scope.inTransaction( + session -> { + session.enableFilter( "betweenLength" ).setParameter( "minLength", 5 ) + .setParameter( "maxLength", 50 ); + long count = session.createSelectionQuery( "select count(*) from Forest", Long.class ).list() + .get( 0 ); + assertThat( count ).isEqualTo( 1 ); + session.disableFilter( "betweenLength" ); + session.enableFilter( "minLength" ).setParameter( "minLength", 5 ); + count = session.createSelectionQuery( "select count(*) from Forest", Long.class ).list().get( 0 ); + assertThat( count ).isEqualTo( 2 ); + + session.disableFilter( "minLength" ); + } + ); + + } /** @@ -453,236 +454,196 @@ public void testFilter() throws Exception { * defined on a parent MappedSuperclass(s) */ @Test - public void testInheritFiltersFromMappedSuperclass() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - s.createQuery( "delete Drill" ).executeUpdate(); - Drill d1 = new PowerDrill(); - d1.setName("HomeDrill1"); - d1.setCategory("HomeImprovment"); - s.persist( d1 ); - Drill d2 = new PowerDrill(); - d2.setName("HomeDrill2"); - d2.setCategory("HomeImprovement"); - s.persist(d2); - Drill d3 = new PowerDrill(); - d3.setName("HighPowerDrill"); - d3.setCategory("Industrial"); - s.persist( d3 ); - tx.commit(); - s.close(); - s = openSession(); - tx = s.beginTransaction(); - - //We test every filter with 2 queries, the first on the base class of the - //inheritance hierarchy (Drill), and the second on a subclass (PowerDrill) - s.enableFilter( "byName" ).setParameter( "name", "HomeDrill1"); - long count = ( (Long) s.createQuery( "select count(*) from Drill" ).list().get( 0 ) ).intValue(); - assertEquals( 1, count ); - count = ( (Long) s.createQuery( "select count(*) from PowerDrill" ).list().get( 0 ) ).intValue(); - assertEquals( 1, count ); - s.disableFilter( "byName" ); - - s.enableFilter( "byCategory" ).setParameter( "category", "Industrial" ); - count = ( (Long) s.createQuery( "select count(*) from Drill" ).list().get( 0 ) ).longValue(); - assertEquals( 1, count ); - count = ( (Long) s.createQuery( "select count(*) from PowerDrill" ).list().get( 0 ) ).longValue(); - assertEquals( 1, count ); - s.disableFilter( "byCategory" ); - - tx.rollback(); - s.close(); + public void testInheritFiltersFromMappedSuperclass(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.createMutationQuery( "delete Drill" ).executeUpdate(); + Drill d1 = new PowerDrill(); + d1.setName( "HomeDrill1" ); + d1.setCategory( "HomeImprovment" ); + session.persist( d1 ); + Drill d2 = new PowerDrill(); + d2.setName( "HomeDrill2" ); + d2.setCategory( "HomeImprovement" ); + session.persist( d2 ); + Drill d3 = new PowerDrill(); + d3.setName( "HighPowerDrill" ); + d3.setCategory( "Industrial" ); + session.persist( d3 ); + } + ); + + scope.inTransaction( + session -> { + //We test every filter with 2 queries, the first on the base class of the + //inheritance hierarchy (Drill), and the second on a subclass (PowerDrill) + session.enableFilter( "byName" ).setParameter( "name", "HomeDrill1" ); + long count = session.createSelectionQuery( "select count(*) from Drill", Long.class ).list() + .get( 0 ); + assertThat( count ).isEqualTo( 1 ); + count = session.createSelectionQuery( "select count(*) from PowerDrill", Long.class ).list() + .get( 0 ); + assertThat( count ).isEqualTo( 1 ); + session.disableFilter( "byName" ); + + session.enableFilter( "byCategory" ).setParameter( "category", "Industrial" ); + count = session.createSelectionQuery( "select count(*) from Drill", Long.class ).list().get( 0 ); + assertThat( count ).isEqualTo( 1 ); + count = session.createSelectionQuery( "select count(*) from PowerDrill", Long.class ).list() + .get( 0 ); + assertThat( count ).isEqualTo( 1 ); + session.disableFilter( "byCategory" ); + } + ); } @Test - @RequiresDialectFeature( DialectChecks.SupportsExpectedLobUsagePattern.class ) - public void testParameterizedType() { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsExpectedLobUsagePattern.class) + public void testParameterizedType(SessionFactoryScope scope) { Forest f = new Forest(); - f.setSmallText( "ThisIsASmallText" ); - f.setBigText( "ThisIsABigText" ); - s.persist( f ); - tx.commit(); - s.close(); - s = openSession(); - tx = s.beginTransaction(); - Forest f2 = s.get( Forest.class, f.getId() ); - assertEquals( f.getSmallText().toLowerCase(Locale.ROOT), f2.getSmallText() ); - assertEquals( f.getBigText().toUpperCase(Locale.ROOT), f2.getBigText() ); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + f.setSmallText( "ThisIsASmallText" ); + f.setBigText( "ThisIsABigText" ); + session.persist( f ); + } + ); + + scope.inTransaction( + session -> { + Forest f2 = session.find( Forest.class, f.getId() ); + assertThat( f2.getSmallText() ).isEqualTo( f.getSmallText().toLowerCase( Locale.ROOT ) ); + assertThat( f2.getBigText() ).isEqualTo( f.getBigText().toUpperCase( Locale.ROOT ) ); + } + ); } @Test - @RequiresDialectFeature( DialectChecks.SupportsExpectedLobUsagePattern.class ) + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsExpectedLobUsagePattern.class) @SkipForDialect( - value = SybaseDialect.class, - comment = "Sybase does not support LOB comparisons, and data cleanup plus OptimisticLockType.ALL on Forest triggers LOB comparison" + dialectClass = SybaseDialect.class, + reason = "Sybase does not support LOB comparisons, and data cleanup plus OptimisticLockType.ALL on Forest triggers LOB comparison" ) @SkipForDialect( - value = PostgreSQLDialect.class, - comment = "PGSQL does not support LOB comparisons, and data cleanup plus OptimisticLockType.ALL on Forest triggers LOB comparison" + dialectClass = PostgreSQLDialect.class, + reason = "PGSQL does not support LOB comparisons, and data cleanup plus OptimisticLockType.ALL on Forest triggers LOB comparison" ) @SkipForDialect( - value = DerbyDialect.class, - comment = "Derby does not support LOB comparisons, and data cleanup plus OptimisticLockType.ALL on Forest triggers LOB comparison" + dialectClass = DerbyDialect.class, + reason = "Derby does not support LOB comparisons, and data cleanup plus OptimisticLockType.ALL on Forest triggers LOB comparison" ) @SkipForDialect( - value = OracleDialect.class, - comment = "Oracle does not support LOB comparisons, and data cleanup plus OptimisticLockType.ALL on Forest triggers LOB comparison" + dialectClass = OracleDialect.class, + reason = "Oracle does not support LOB comparisons, and data cleanup plus OptimisticLockType.ALL on Forest triggers LOB comparison" ) - public void testSerialized() { - Forest forest = new Forest(); - forest.setName( "Shire" ); - Country country = new Country(); - country.setName( "Middle Earth" ); - forest.setCountry( country ); - Set near = new HashSet<>(); - country = new Country(); - country.setName("Mordor"); - near.add(country); - country = new Country(); - country.setName("Gondor"); - near.add(country); - country = new Country(); - country.setName("Eriador"); - near.add(country); - forest.setNear(near); - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - s.persist( forest ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - forest = s.get( Forest.class, forest.getId() ); - assertNotNull( forest ); - country = forest.getCountry(); - assertNotNull( country ); - assertEquals( country.getName(), forest.getCountry().getName() ); - near = forest.getNear(); - assertTrue("correct number of nearby countries", near.size() == 3); - for (Iterator iter = near.iterator(); iter.hasNext();) { - country = (Country)iter.next(); - String name = country.getName(); - assertTrue("found expected nearby country " + name, - (name.equals("Mordor") || name.equals("Gondor") || name.equals("Eriador"))); - } - tx.commit(); - s.close(); - } + public void testSerialized(SessionFactoryScope scope) { + Forest f = new Forest(); + f.setName( "Shire" ); + Country c = new Country(); + c.setName( "Middle Earth" ); + f.setCountry( c ); + Set nearCountries = new HashSet<>(); + c = new Country(); + c.setName( "Mordor" ); + nearCountries.add( c ); + c = new Country(); + c.setName( "Gondor" ); + nearCountries.add( c ); + c = new Country(); + c.setName( "Eriador" ); + nearCountries.add( c ); + f.setNear( nearCountries ); + scope.inTransaction( + session -> session.persist( f ) + ); - @Test - public void testCompositeType() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - Ransom r = new Ransom(); - r.setKidnapperName( "Se7en" ); - r.setDate( new Date() ); - MonetaryAmount amount = new MonetaryAmount( - new BigDecimal( 100000 ), - Currency.getInstance( "EUR" ) - ); - r.setAmount( amount ); - s.persist( r ); - tx.commit(); - s.clear(); - tx = s.beginTransaction(); - r = (Ransom) s.get( Ransom.class, r.getId() ); - assertNotNull( r ); - assertNotNull( r.getAmount() ); - assertTrue( 0 == new BigDecimal( 100000 ).compareTo( r.getAmount().getAmount() ) ); - assertEquals( Currency.getInstance( "EUR" ), r.getAmount().getCurrency() ); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + Forest forest = session.find( Forest.class, f.getId() ); + assertThat( forest ).isNotNull(); + Country country = forest.getCountry(); + assertThat( country ).isNotNull(); + assertThat( country.getName() ).isEqualTo( forest.getCountry().getName() ); + Set near = forest.getNear(); + assertThat( near.size() ).isEqualTo( 3 ); + for ( Country n : near ) { + String name = n.getName(); + assertThat( (name.equals( "Mordor" ) || name.equals( "Gondor" ) || name.equals( "Eriador" )) ) + .isTrue(); + } + } + ); } @Test - public void testFormula() throws Exception { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Flight airFrance = new Flight(); - airFrance.setId( new Long( 747 ) ); - airFrance.setMaxAltitude( 10000 ); - s.persist( airFrance ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - airFrance = s.get( Flight.class, airFrance.getId() ); - assertNotNull( airFrance ); - assertEquals( 10000000, airFrance.getMaxAltitudeInMilimeter() ); - s.remove( airFrance ); - tx.commit(); - s.close(); + public void testCompositeType(SessionFactoryScope scope) { + Ransom ransom = new Ransom(); + scope.inTransaction( + session -> { + ransom.setKidnapperName( "Se7en" ); + ransom.setDate( new Date() ); + MonetaryAmount amount = new MonetaryAmount( + new BigDecimal( 100000 ), + Currency.getInstance( "EUR" ) + ); + ransom.setAmount( amount ); + session.persist( ransom ); + } + ); + + scope.inTransaction( + session -> { + Ransom r = session.find( Ransom.class, ransom.getId() ); + assertThat( r ).isNotNull(); + assertThat( r.getAmount() ).isNotNull(); + assertThat( r.getAmount().getAmount() ).isEqualByComparingTo( new BigDecimal( 100000 ) ); + assertThat( r.getAmount().getCurrency() ).isEqualTo( Currency.getInstance( "EUR" ) ); + } + ); } @Test - public void testTypeDefNameAndDefaultForTypeAttributes() { - ContactDetails contactDetails = new ContactDetails(); - contactDetails.setLocalPhoneNumber(new PhoneNumber("999999")); - contactDetails.setOverseasPhoneNumber( - new OverseasPhoneNumber("041", "111111")); - - Session s = openSession(); - Transaction tx = s.beginTransaction(); - s.persist(contactDetails); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - contactDetails = - s.get( ContactDetails.class, contactDetails.getId() ); - assertNotNull( contactDetails ); - assertEquals( "999999", contactDetails.getLocalPhoneNumber().getNumber() ); - assertEquals( "041111111", contactDetails.getOverseasPhoneNumber().getNumber() ); - s.remove(contactDetails); - tx.commit(); - s.close(); + public void testFormula(SessionFactoryScope scope) { + Flight flight = new Flight(); + scope.inTransaction( + session -> { + flight.setId( 747L ); + flight.setMaxAltitude( 10000 ); + session.persist( flight ); + } + ); + scope.inTransaction( + session -> { + Flight airFrance = session.find( Flight.class, flight.getId() ); + assertThat( airFrance ).isNotNull(); + assertThat( airFrance.getMaxAltitudeInMilimeter() ).isEqualTo( 10000000 ); + session.remove( airFrance ); + } + ); } + @Test + public void testTypeDefNameAndDefaultForTypeAttributes(SessionFactoryScope scope) { + ContactDetails details = new ContactDetails(); + details.setLocalPhoneNumber( new PhoneNumber( "999999" ) ); + details.setOverseasPhoneNumber( + new OverseasPhoneNumber( "041", "111111" ) ); + + scope.inTransaction( + session -> session.persist( details ) + ); - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - Forest.class, - Tree.class, - Ransom.class, - ZipCode.class, - Flight.class, - Name.class, - FormalLastName.class, - ContactDetails.class, - Topic.class, - Narrative.class, - Drill.class, - PowerDrill.class, - SoccerTeam.class, - Player.class, - Doctor.class, - PhoneNumberConverter.class - }; - } - - @Override - protected String[] getAnnotatedPackages() { - return new String[]{ - "org.hibernate.orm.test.annotations.entity" - }; + scope.inTransaction( + session -> { + ContactDetails contactDetails = + session.find( ContactDetails.class, details.getId() ); + assertThat( contactDetails ).isNotNull(); + assertThat( contactDetails.getLocalPhoneNumber().getNumber() ).isEqualTo( "999999" ); + assertThat( contactDetails.getOverseasPhoneNumber().getNumber() ).isEqualTo( "041111111" ); + session.remove( contactDetails ); + } + ); } - } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/Forest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/Forest.java index 3f33dc4eb38a..61fd40f0ab44 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/Forest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/Forest.java @@ -51,7 +51,7 @@ public class Forest { private String smallText; private String bigText; private Country country; - private Set near; + private Set near; @OptimisticLock(excluded=true) @JdbcTypeCode( Types.LONGVARCHAR ) @@ -123,7 +123,7 @@ public Set getNear() { return near; } - public void setNear(Setnear) { + public void setNear(Set near) { this.near = near; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/HibernateAnnotationMappingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/HibernateAnnotationMappingTest.java index 2a1768f7310a..cd5e0c960dc9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/HibernateAnnotationMappingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/HibernateAnnotationMappingTest.java @@ -4,37 +4,43 @@ */ package org.hibernate.orm.test.annotations.entity; -import static org.junit.Assert.fail; - -import java.util.ConcurrentModificationException; - import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; +import org.hibernate.testing.orm.junit.BaseUnitTest; 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; + +import java.util.ConcurrentModificationException; + +import static org.assertj.core.api.Fail.fail; /** * @author Guenther Demetz */ -public class HibernateAnnotationMappingTest extends BaseUnitTestCase { +@BaseUnitTest +public class HibernateAnnotationMappingTest { @Test - @JiraKey( value = "HHH-7446" ) - public void testUniqueConstraintAnnotationOnNaturalIds() throws Exception { + @JiraKey(value = "HHH-7446") + public void testUniqueConstraintAnnotationOnNaturalIds() { Configuration configuration = new Configuration(); ServiceRegistryUtil.applySettings( configuration.getStandardServiceRegistryBuilder() ); configuration.setProperty( Environment.HBM2DDL_AUTO, "create-drop" ); - configuration.addAnnotatedClass( Month.class); + configuration.addAnnotatedClass( Month.class ); SessionFactory sf = null; try { sf = configuration.buildSessionFactory(); - sf.close(); + } catch (ConcurrentModificationException e) { - fail(e.toString()); + fail( e.toString() ); + } + finally { + if ( sf != null ) { + sf.close(); + } } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/Java5FeaturesTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/Java5FeaturesTest.java index 40e689bcc8be..b10c7073e9ec 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/Java5FeaturesTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/Java5FeaturesTest.java @@ -4,129 +4,130 @@ */ package org.hibernate.orm.test.annotations.entity; -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 org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; /** * @author Emmanuel Bernard */ -public class Java5FeaturesTest extends BaseCoreFunctionalTestCase { - @Test - public void testInterface() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - Race r = new Race(); - r.setId( new Integer( 1 ) ); - r.setLength( new Long( 3 ) ); - s.persist( r ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - r = (Race) s.get( Race.class, r.getId() ); - assertEquals( new Long( 3 ), r.getLength() ); - tx.commit(); - s.close(); +@DomainModel( + annotatedClasses = { + Race.class, + Bid.class, + CommunityBid.class + } +) +@SessionFactory +public class Java5FeaturesTest { + @AfterEach + public void afterEach(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Test - public void testEnums() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - CommunityBid communityBid = new CommunityBid(); - communityBid.setId( new Integer( 2 ) ); - communityBid.setCommunityNote( Starred.OK ); - Bid bid = new Bid(); - bid.setId( new Integer( 1 ) ); - bid.setDescription( "My best one" ); - bid.setNote( Starred.OK ); - bid.setEditorsNote( Starred.GOOD ); - s.persist( bid ); - s.persist( communityBid ); - tx.commit(); - s.close(); + public void testInterface(SessionFactoryScope scope) { + Race r = new Race(); + scope.inTransaction( + session -> { + r.setId( 1 ); + r.setLength( 3L ); + session.persist( r ); + } + ); - s = openSession(); - tx = s.beginTransaction(); - //bid = (Bid) s.get( Bid.class, bid.getId() ); - bid = (Bid)s.createQuery( "select b from Bid b where b.note = " + - Starred.class.getName() + ".OK and b.editorsNote = " + - Starred.class.getName() + ".GOOD and b.id = :id") - .setParameter( "id", bid.getId() ).uniqueResult(); - //testing constant value - assertEquals( Starred.OK, bid.getNote() ); - assertEquals( Starred.GOOD, bid.getEditorsNote() ); - bid = (Bid)s.createQuery( "select b from Bid b where b.note = :note" + - " and b.editorsNote = :editorNote " + - " and b.id = :id") - .setParameter( "id", bid.getId() ) - .setParameter( "note", Starred.OK ) - .setParameter( "editorNote", Starred.GOOD ) - .uniqueResult(); - //testing constant value - assertEquals( Starred.OK, bid.getNote() ); - assertEquals( Starred.GOOD, bid.getEditorsNote() ); - bid.setNote( null ); - tx.commit(); - s.clear(); - tx = s.beginTransaction(); - bid = (Bid) s.get( Bid.class, bid.getId() ); - communityBid = (CommunityBid) s.get( CommunityBid.class, communityBid.getId() ); - assertNull( bid.getNote() ); - assertEquals( Starred.OK, communityBid.getCommunityNote() ); - s.remove( bid ); - s.clear(); - communityBid = (CommunityBid) s.createNativeQuery( "select {b.*} from Bid b where b.id = ?" ) - .addEntity( "b", CommunityBid.class ) - .setParameter( 1, communityBid.getId() ).uniqueResult(); - assertEquals( Starred.OK, communityBid.getCommunityNote() ); - s.remove( communityBid ); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + Race race = session.find( Race.class, r.getId() ); + assertThat( race.getLength() ).isEqualTo( 3 ); + } + ); } - public void testAutoboxing() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - Bid bid = new Bid(); - bid.setId( new Integer( 2 ) ); - bid.setDescription( "My best one" ); - bid.setNote( Starred.OK ); - bid.setEditorsNote( Starred.GOOD ); - bid.setApproved( null ); - s.persist( bid ); - tx.commit(); - s.close(); + @Test + public void testEnums(SessionFactoryScope scope) { + Bid b = new Bid(); + CommunityBid cb = new CommunityBid(); + scope.inTransaction( + session -> { + cb.setId( 2 ); + cb.setCommunityNote( Starred.OK ); + b.setId( 1 ); + b.setDescription( "My best one" ); + b.setNote( Starred.OK ); + b.setEditorsNote( Starred.GOOD ); + session.persist( b ); + session.persist( cb ); + } + ); + + scope.inTransaction( + session -> { + //bid = (Bid) s.get( Bid.class, bid.getId() ); + Bid bid = session.createQuery( "select b from Bid b where b.note = " + + Starred.class.getName() + ".OK and b.editorsNote = " + + Starred.class.getName() + ".GOOD and b.id = :id", Bid.class ) + .setParameter( "id", b.getId() ).uniqueResult(); + //testing constant value + assertThat( bid.getNote() ).isEqualTo( Starred.OK ); + assertThat( bid.getEditorsNote() ).isEqualTo( Starred.GOOD ); + bid = session.createQuery( "select b from Bid b where b.note = :note" + + " and b.editorsNote = :editorNote " + + " and b.id = :id", Bid.class ) + .setParameter( "id", bid.getId() ) + .setParameter( "note", Starred.OK ) + .setParameter( "editorNote", Starred.GOOD ) + .uniqueResult(); + //testing constant value + assertThat( bid.getNote() ).isEqualTo( Starred.OK ); + assertThat( bid.getEditorsNote() ).isEqualTo( Starred.GOOD ); + bid.setNote( null ); + } + ); - s = openSession(); - tx = s.beginTransaction(); - bid = (Bid) s.get( Bid.class, bid.getId() ); - assertEquals( null, bid.getApproved() ); - s.remove( bid ); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + Bid bid = session.find( Bid.class, b.getId() ); + CommunityBid communityBid = session.find( CommunityBid.class, cb.getId() ); + assertThat( bid.getNote() ).isNull(); + assertThat( communityBid.getCommunityNote() ).isEqualTo( Starred.OK ); + session.remove( bid ); + session.clear(); + communityBid = session.createNativeQuery( "select {b.*} from Bid b where b.id = ?", + CommunityBid.class ) + .addEntity( "b", CommunityBid.class ) + .setParameter( 1, communityBid.getId() ).uniqueResult(); + assertThat( communityBid.getCommunityNote() ).isEqualTo( Starred.OK ); + session.remove( communityBid ); + } + ); } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - Race.class, - Bid.class, - CommunityBid.class - }; + @Test + public void testAutoboxing(SessionFactoryScope scope) { + Bid b = new Bid(); + scope.inTransaction( + session -> { + b.setId( 2 ); + b.setDescription( "My best one" ); + b.setNote( Starred.OK ); + b.setEditorsNote( Starred.GOOD ); + b.setApproved( null ); + session.persist( b ); + } + ); + + scope.inTransaction( + session -> { + Bid bid = session.find( Bid.class, b.getId() ); + assertThat( bid.getApproved() ).isNull(); + session.remove( bid ); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/PropertyDefaultMappingsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/PropertyDefaultMappingsTest.java index 8c7e0053a28e..029a7a3e0ec2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/PropertyDefaultMappingsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/PropertyDefaultMappingsTest.java @@ -4,67 +4,69 @@ */ package org.hibernate.orm.test.annotations.entity; -import org.junit.Test; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +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 static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; /** * @author Emmanuel Bernard */ -public class PropertyDefaultMappingsTest extends BaseCoreFunctionalTestCase { - @Test - public void testSerializableObject() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - Country c = new Country(); - c.setName( "France" ); - Address a = new Address(); - a.setCity( "Paris" ); - a.setCountry( c ); - s.persist( a ); - tx.commit(); - s.close(); +@DomainModel( + annotatedClasses = {Address.class, + WashingMachine.class - s = openSession(); - tx = s.beginTransaction(); - Address reloadedAddress = (Address) s.get( Address.class, a.getId() ); - assertNotNull( reloadedAddress ); - assertNotNull( reloadedAddress.getCountry() ); - assertEquals( a.getCountry().getName(), reloadedAddress.getCountry().getName() ); - tx.rollback(); - s.close(); + } +) +@SessionFactory +public class PropertyDefaultMappingsTest { + @AfterEach + public void afterEach(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } + @Test - public void testTransientField() throws Exception { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - WashingMachine wm = new WashingMachine(); - wm.setActive( true ); - s.persist( wm ); - tx.commit(); - s.clear(); - tx = s.beginTransaction(); - wm = s.get( WashingMachine.class, wm.getId() ); - assertFalse( "transient should not be persistent", wm.isActive() ); - s.remove( wm ); - tx.commit(); - s.close(); + public void testSerializableObject(SessionFactoryScope scope) { + Address a = new Address(); + scope.inTransaction( + session -> { + Country c = new Country(); + c.setName( "France" ); + a.setCity( "Paris" ); + a.setCountry( c ); + session.persist( a ); + } + ); + + scope.inTransaction( + session -> { + Address reloadedAddress = session.find( Address.class, a.getId() ); + assertThat( reloadedAddress ).isNotNull(); + assertThat( reloadedAddress.getCountry() ).isNotNull(); + assertThat( reloadedAddress.getCountry().getName() ).isEqualTo( a.getCountry().getName() ); + } + ); } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - Address.class, - WashingMachine.class - }; + @Test + public void testTransientField(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + WashingMachine wm = new WashingMachine(); + wm.setActive( true ); + session.persist( wm ); + session.getTransaction().commit(); + session.clear(); + session.beginTransaction(); + wm = session.find( WashingMachine.class, wm.getId() ); + assertThat( wm.isActive() ).isFalse(); + session.remove( wm ); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/SoccerTeam.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/SoccerTeam.java index e4d4821f5f30..6d0355c69ce5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/SoccerTeam.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/SoccerTeam.java @@ -26,12 +26,12 @@ public class SoccerTeam { @OneToMany @SQLRestriction("activeLicense = true") - private List physiologists = new ArrayList(); + private List physiologists = new ArrayList<>(); @OneToMany(mappedBy="team", orphanRemoval=true, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH}) - private Set players = new HashSet(); + private Set players = new HashSet<>(); @OneToOne(mappedBy="oneVoneTeam", orphanRemoval=true, diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/Topic.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/Topic.java index 457ff17a00c4..6b5768adf01f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/Topic.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/Topic.java @@ -27,10 +27,12 @@ public class Topic { @Id @GeneratedValue private int id; + private String name; + @OneToMany(mappedBy="topic", cascade=CascadeType.ALL) @Filter(name="byState", condition=":state = state") - private Set narratives = new HashSet(); + private Set narratives = new HashSet<>(); public int getId() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/enumerated/mapkey/MapKeyEnumeratedTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/enumerated/mapkey/MapKeyEnumeratedTest.java index 9e113a35200c..b47f0c58a04b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/enumerated/mapkey/MapKeyEnumeratedTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/enumerated/mapkey/MapKeyEnumeratedTest.java @@ -4,41 +4,41 @@ */ package org.hibernate.orm.test.annotations.enumerated.mapkey; -import org.hibernate.Session; - -import org.junit.Test; - -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +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; /** * @author Steve Ebersole */ -public class MapKeyEnumeratedTest extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { User.class, SocialNetworkProfile.class }; - } +@DomainModel( + annotatedClasses = { + User.class, + SocialNetworkProfile.class + } +) +@SessionFactory +public class MapKeyEnumeratedTest { @Test - public void testMapKeyEnumerated() { - Session s = openSession(); - s.beginTransaction(); - User user = new User("User1", SocialNetwork.STUB_NETWORK_NAME, "facebookId"); - s.persist( user ); - s.getTransaction().commit(); - s.close(); + public void testMapKeyEnumerated(SessionFactoryScope scope) { + User u = new User( "User1", SocialNetwork.STUB_NETWORK_NAME, "facebookId" ); + scope.inTransaction( + session -> session.persist( u ) + + ); - s = openSession(); - s.beginTransaction(); - user = s.get( User.class, user.getId() ); - s.getTransaction().commit(); - s.close(); + scope.inTransaction( + session -> + session.find( User.class, u.getId() ) + ); - s = openSession(); - s.beginTransaction(); - user = s.get( User.class, user.getId() ); - s.remove( user ); - s.getTransaction().commit(); - s.close(); + scope.inTransaction( + session -> { + User user = session.find( User.class, u.getId() ); + session.remove( user ); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/enumerated/ormXml/OrmXmlEnumTypeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/enumerated/ormXml/OrmXmlEnumTypeTest.java index 5371d3efbc95..ba91ff66a85f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/enumerated/ormXml/OrmXmlEnumTypeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/enumerated/ormXml/OrmXmlEnumTypeTest.java @@ -7,25 +7,26 @@ import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.type.Type; -import org.hibernate.type.descriptor.jdbc.spi.JdbcTypeRegistry; - import org.hibernate.testing.ServiceRegistryBuilder; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.junit4.ExtraAssertions; +import org.hibernate.testing.orm.junit.BaseUnitTest; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.type.Type; +import org.hibernate.type.descriptor.jdbc.spi.JdbcTypeRegistry; import org.hibernate.type.internal.BasicTypeImpl; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static java.sql.Types.VARCHAR; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.hibernate.type.SqlTypes.ENUM; -import static org.junit.Assert.assertEquals; /** * @author Steve Ebersole */ -@JiraKey( value = "HHH-7645" ) -public class OrmXmlEnumTypeTest extends BaseUnitTestCase { +@JiraKey(value = "HHH-7645") +@BaseUnitTest +public class OrmXmlEnumTypeTest { + @Test public void testOrmXmlDefinedEnumType() { StandardServiceRegistry ssr = ServiceRegistryBuilder.buildServiceRegistry(); @@ -44,10 +45,10 @@ public void testOrmXmlDefinedEnumType() { .getTypeConfiguration() .getJdbcTypeRegistry(); BasicTypeImpl enumMapping = ExtraAssertions.assertTyping( BasicTypeImpl.class, bindingPropertyType ); - assertEquals( - jdbcTypeRegistry.getDescriptor( jdbcTypeRegistry.hasRegisteredDescriptor( ENUM ) ? ENUM : VARCHAR ), + assertThat( jdbcTypeRegistry.getDescriptor( enumMapping.getJdbcType().getDefaultSqlTypeCode() ) - ); + ).isEqualTo( jdbcTypeRegistry.getDescriptor( + jdbcTypeRegistry.hasRegisteredDescriptor( ENUM ) ? ENUM : VARCHAR ) ); } finally { ServiceRegistryBuilder.destroy( ssr ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fetch/FetchingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fetch/FetchingTest.java index bedd47a1f91b..3c22156cefcd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fetch/FetchingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fetch/FetchingTest.java @@ -4,127 +4,110 @@ */ package org.hibernate.orm.test.annotations.fetch; -import java.util.Date; - import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; - -import org.junit.Test; - import org.hibernate.Hibernate; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +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 static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import java.util.Date; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; /** * @author Emmanuel Bernard */ -public class FetchingTest extends BaseCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + Person.class, + Stay.class, + Branch.class, + Leaf.class + } +) +@SessionFactory +public class FetchingTest { + + @AfterEach + public void cleanup(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); + } + @Test - public void testLazy() { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - Person p = new Person( "Gavin", "King", "JBoss Inc" ); - Stay stay = new Stay( p, new Date(), new Date(), "A380", "Blah", "Blah" ); - p.addStay( stay ); - s.persist( p ); - tx.commit(); - s.clear(); - tx = s.beginTransaction(); - p = (Person) s.createQuery( "from Person p where p.firstName = :name" ) - .setParameter( "name", "Gavin" ).uniqueResult(); - assertFalse( Hibernate.isInitialized( p.getStays() ) ); - s.remove( p ); - tx.commit(); - s.close(); + public void testLazy(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Person p = new Person( "Gavin", "King", "JBoss Inc" ); + Stay stay = new Stay( p, new Date(), new Date(), "A380", "Blah", "Blah" ); + p.addStay( stay ); + session.persist( p ); + session.getTransaction().commit(); + session.clear(); + session.beginTransaction(); + p = session.createQuery( "from Person p where p.firstName = :name", Person.class ) + .setParameter( "name", "Gavin" ).uniqueResult(); + assertThat( Hibernate.isInitialized( p.getStays() ) ).isFalse(); + session.remove( p ); + } + ); } @Test - public void testHibernateFetchingLazy() { - try(Session s = openSession()) { - Transaction tx = s.beginTransaction(); - try { - Person p = new Person( "Gavin", "King", "JBoss Inc" ); - Stay stay = new Stay( null, new Date(), new Date(), "A380", "Blah", "Blah" ); - Stay stay2 = new Stay( null, new Date(), new Date(), "A320", "Blah", "Blah" ); - Stay stay3 = new Stay( null, new Date(), new Date(), "A340", "Blah", "Blah" ); - stay.setOldPerson( p ); - stay2.setVeryOldPerson( p ); - stay3.setVeryOldPerson( p ); - p.addOldStay( stay ); - p.addVeryOldStay( stay2 ); - p.addVeryOldStay( stay3 ); - s.persist( p ); - tx.commit(); - s.clear(); - tx = s.beginTransaction(); - p = (Person) s.createQuery( "from Person p where p.firstName = :name" ) - .setParameter( "name", "Gavin" ).uniqueResult(); - assertFalse( Hibernate.isInitialized( p.getOldStays() ) ); - assertEquals( 1, p.getOldStays().size() ); - assertTrue( Hibernate.isInitialized( p.getOldStays() ) ); - s.clear(); - stay = (Stay) s.get( Stay.class, stay.getId() ); - assertTrue( !Hibernate.isInitialized( stay.getOldPerson() ) ); - s.clear(); - stay3 = (Stay) s.get( Stay.class, stay3.getId() ); - assertTrue( - "FetchMode.JOIN should overrides lazy options", - Hibernate.isInitialized( stay3.getVeryOldPerson() ) - ); - s.remove( stay3.getVeryOldPerson() ); - tx.commit(); - }finally { - if ( tx.isActive() ) { - tx.rollback(); + public void testHibernateFetchingLazy(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Person p = new Person( "Gavin", "King", "JBoss Inc" ); + Stay stay = new Stay( null, new Date(), new Date(), "A380", "Blah", "Blah" ); + Stay stay2 = new Stay( null, new Date(), new Date(), "A320", "Blah", "Blah" ); + Stay stay3 = new Stay( null, new Date(), new Date(), "A340", "Blah", "Blah" ); + stay.setOldPerson( p ); + stay2.setVeryOldPerson( p ); + stay3.setVeryOldPerson( p ); + p.addOldStay( stay ); + p.addVeryOldStay( stay2 ); + p.addVeryOldStay( stay3 ); + session.persist( p ); + session.getTransaction().commit(); + session.clear(); + session.beginTransaction(); + p = session.createQuery( "from Person p where p.firstName = :name", Person.class ) + .setParameter( "name", "Gavin" ).uniqueResult(); + assertThat( Hibernate.isInitialized( p.getOldStays() ) ).isFalse(); + assertThat( p.getOldStays().size() ).isEqualTo( 1 ); + assertThat( Hibernate.isInitialized( p.getOldStays() ) ).isTrue(); + session.clear(); + stay = session.find( Stay.class, stay.getId() ); + assertThat( !Hibernate.isInitialized( stay.getOldPerson() ) ).isTrue(); + session.clear(); + stay3 = session.find( Stay.class, stay3.getId() ); + assertThat( Hibernate.isInitialized( stay3.getVeryOldPerson() ) ).isTrue(); + session.remove( stay3.getVeryOldPerson() ); } - } - } + ); } @Test - public void testOneToManyFetchEager() { + public void testOneToManyFetchEager(SessionFactoryScope scope) { Branch b = new Branch(); - Session s = openSession( ); - try { - s.getTransaction().begin(); - s.persist( b ); - s.flush(); - Leaf l = new Leaf(); - l.setBranch( b ); - s.persist( l ); - s.flush(); - - s.clear(); + scope.inTransaction( + session -> { + session.persist( b ); + session.flush(); + Leaf l = new Leaf(); + l.setBranch( b ); + session.persist( l ); + session.flush(); - CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); - CriteriaQuery criteria = criteriaBuilder.createQuery( Branch.class ); - criteria.from( Branch.class ); - s.createQuery( criteria ).list(); -// s.createCriteria( Branch.class ).list(); + session.clear(); - } - finally { - if ( s.getTransaction().isActive() ) { - s.getTransaction().rollback(); - } - s.close(); - } - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - Person.class, - Stay.class, - Branch.class, - Leaf.class - }; + CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); + CriteriaQuery criteria = criteriaBuilder.createQuery( Branch.class ); + criteria.from( Branch.class ); + session.createQuery( criteria ).list(); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fetchprofile/Customer.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fetchprofile/Customer.java index c561be51bc21..c3656d6dbd20 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fetchprofile/Customer.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fetchprofile/Customer.java @@ -38,7 +38,7 @@ public class Customer { private long customerNumber; @OneToMany - private Set orders = new HashSet(); + private Set orders = new HashSet<>(); @ManyToOne(fetch = FetchType.LAZY) private Order lastOrder; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fetchprofile/MappedByFetchProfileFunctionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fetchprofile/MappedByFetchProfileFunctionTest.java index 57a018bbee7a..26cfdf53ac48 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fetchprofile/MappedByFetchProfileFunctionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fetchprofile/MappedByFetchProfileFunctionTest.java @@ -5,52 +5,48 @@ package org.hibernate.orm.test.annotations.fetchprofile; import org.hibernate.Hibernate; -import org.hibernate.Session; -import org.hibernate.Transaction; import org.hibernate.orm.test.annotations.fetchprofile.mappedby.Address; - +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 static org.junit.Assert.assertTrue; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; -@JiraKey( value = "HHH-14071" ) -public class MappedByFetchProfileFunctionTest extends BaseCoreFunctionalTestCase { +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; - @Test - public void testFetchWithOneToOneMappedBy() { - final Session session = openSession(); - session.enableFetchProfile( "address-with-customer" ); - final Transaction transaction = session.beginTransaction(); - - Address address = new Address(); - address.setStreet("Test Road 1"); - Customer6 customer = new Customer6(); - customer.setName("Tester"); - customer.setAddress(address); - - session.persist(address); - session.persist(customer); - - session.flush(); - session.clear(); - - address = session.get(Address.class, address.getId()); - assertTrue(Hibernate.isInitialized(address.getCustomer())); - session.remove(address.getCustomer()); - session.remove(address); - - transaction.commit(); - session.close(); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { +@JiraKey(value = "HHH-14071") +@DomainModel( + annotatedClasses = { Customer6.class, Address.class - }; + } +) +@SessionFactory +public class MappedByFetchProfileFunctionTest { + + @Test + public void testFetchWithOneToOneMappedBy(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.enableFetchProfile( "address-with-customer" ); + Address address = new Address(); + address.setStreet( "Test Road 1" ); + Customer6 customer = new Customer6(); + customer.setName( "Tester" ); + customer.setAddress( address ); + + session.persist( address ); + session.persist( customer ); + + session.flush(); + session.clear(); + + address = session.get( Address.class, address.getId() ); + assertThat( Hibernate.isInitialized( address.getCustomer() ) ).isTrue(); + session.remove( address.getCustomer() ); + session.remove( address ); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fetchprofile/MappedByFetchProfileUnitTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fetchprofile/MappedByFetchProfileUnitTest.java index 368532e9016e..6f82eb335e96 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fetchprofile/MappedByFetchProfileUnitTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fetchprofile/MappedByFetchProfileUnitTest.java @@ -9,29 +9,31 @@ import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.orm.test.annotations.fetchprofile.mappedby.Address; import org.hibernate.service.ServiceRegistry; - import org.hibernate.testing.ServiceRegistryBuilder; +import org.hibernate.testing.orm.junit.BaseUnitTest; import org.hibernate.testing.orm.junit.JiraKey; -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.assertTrue; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -@JiraKey( value = "HHH-14071" ) -public class MappedByFetchProfileUnitTest extends BaseUnitTestCase { +@JiraKey(value = "HHH-14071") +@BaseUnitTest +public class MappedByFetchProfileUnitTest { private ServiceRegistry serviceRegistry; - @Before + @BeforeEach public void setUp() { serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry( Environment.getProperties() ); } - @After + @AfterEach public void tearDown() { - if (serviceRegistry != null) ServiceRegistryBuilder.destroy(serviceRegistry); + if ( serviceRegistry != null ) { + ServiceRegistryBuilder.destroy( serviceRegistry ); + } } @Test @@ -39,18 +41,15 @@ public void testFetchProfileConfigured() { Configuration config = new Configuration(); config.addAnnotatedClass( Customer6.class ); config.addAnnotatedClass( Address.class ); - try (SessionFactoryImplementor sessionImpl = ( SessionFactoryImplementor ) config.buildSessionFactory( - serviceRegistry - )) { + try (SessionFactoryImplementor sessionImpl = (SessionFactoryImplementor) config + .buildSessionFactory( serviceRegistry )) { - assertTrue( - "fetch profile not parsed properly", - sessionImpl.containsFetchProfileDefinition( "address-with-customer" ) - ); - assertTrue( - "fetch profile not parsed properly", - sessionImpl.containsFetchProfileDefinition( "customer-with-address" ) - ); + assertThat( sessionImpl.containsFetchProfileDefinition( "address-with-customer" ) ) + .describedAs( "fetch profile not parsed properly" ) + .isTrue(); + assertThat( sessionImpl.containsFetchProfileDefinition( "customer-with-address" ) ) + .describedAs( "fetch profile not parsed properly" ) + .isTrue(); } } @@ -60,18 +59,15 @@ public void testPackageConfiguredFetchProfile() { config.addAnnotatedClass( Customer6.class ); config.addAnnotatedClass( Address.class ); config.addPackage( Address.class.getPackage().getName() ); - try (SessionFactoryImplementor sessionImpl = ( SessionFactoryImplementor ) config.buildSessionFactory( - serviceRegistry - )) { + try (SessionFactoryImplementor sessionImpl = (SessionFactoryImplementor) config + .buildSessionFactory( serviceRegistry )) { - assertTrue( - "fetch profile not parsed properly", - sessionImpl.containsFetchProfileDefinition( "mappedBy-package-profile-1" ) - ); - assertTrue( - "fetch profile not parsed properly", - sessionImpl.containsFetchProfileDefinition( "mappedBy-package-profile-2" ) - ); + assertThat( sessionImpl.containsFetchProfileDefinition( "mappedBy-package-profile-1" ) ) + .describedAs( "fetch profile not parsed properly" ) + .isTrue(); + assertThat( sessionImpl.containsFetchProfileDefinition( "mappedBy-package-profile-2" ) ) + .describedAs( "fetch profile not parsed properly" ) + .isTrue(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fetchprofile/MoreFetchProfileTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fetchprofile/MoreFetchProfileTest.java index b35c4580bb8a..6fb1be955ff6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fetchprofile/MoreFetchProfileTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fetchprofile/MoreFetchProfileTest.java @@ -4,79 +4,76 @@ */ package org.hibernate.orm.test.annotations.fetchprofile; -import java.util.Date; - -import org.junit.Test; - import org.hibernate.Hibernate; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +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 java.util.Date; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; /** * @author Emmanuel Bernard * @author Hardy Ferentschik */ -public class MoreFetchProfileTest extends BaseCoreFunctionalTestCase { - @Test - public void testFetchWithTwoOverrides() throws Exception { - Session s = openSession(); - s.enableFetchProfile( "customer-with-orders-and-country" ); - final Transaction transaction = s.beginTransaction(); - Country ctry = new Country(); - ctry.setName( "France" ); - Order o = new Order(); - o.setCountry( ctry ); - o.setDeliveryDate( new Date() ); - o.setOrderNumber( 1 ); - Order o2 = new Order(); - o2.setCountry( ctry ); - o2.setDeliveryDate( new Date() ); - o2.setOrderNumber( 2 ); - Customer c = new Customer(); - c.setCustomerNumber( 1 ); - c.setName( "Emmanuel" ); - c.getOrders().add( o ); - c.setLastOrder( o2 ); - - s.persist( ctry ); - s.persist( o ); - s.persist( o2 ); - s.persist( c ); - - s.flush(); +@DomainModel( + annotatedClasses = { + Order.class, + Country.class, + Customer.class, + SupportTickets.class + } +) +@SessionFactory +public class MoreFetchProfileTest { - s.clear(); + @Test + public void testFetchWithTwoOverrides(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.enableFetchProfile( "customer-with-orders-and-country" ); + Country ctry = new Country(); + ctry.setName( "France" ); + Order o = new Order(); + o.setCountry( ctry ); + o.setDeliveryDate( new Date() ); + o.setOrderNumber( 1 ); + Order o2 = new Order(); + o2.setCountry( ctry ); + o2.setDeliveryDate( new Date() ); + o2.setOrderNumber( 2 ); + Customer c = new Customer(); + c.setCustomerNumber( 1 ); + c.setName( "Emmanuel" ); + c.getOrders().add( o ); + c.setLastOrder( o2 ); - c = ( Customer ) s.get( Customer.class, c.getId() ); - assertTrue( Hibernate.isInitialized( c.getLastOrder() ) ); - assertTrue( Hibernate.isInitialized( c.getOrders() ) ); - for ( Order so : c.getOrders() ) { - assertTrue( Hibernate.isInitialized( so.getCountry() ) ); - } - final Order order = c.getOrders().iterator().next(); - c.getOrders().remove( order ); - s.remove( c ); - final Order lastOrder = c.getLastOrder(); - c.setLastOrder( null ); - s.remove( order.getCountry() ); - s.remove( lastOrder ); - s.remove( order ); + session.persist( ctry ); + session.persist( o ); + session.persist( o2 ); + session.persist( c ); - transaction.commit(); - s.close(); + session.flush(); - } + session.clear(); - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Order.class, - Country.class, - Customer.class, - SupportTickets.class - }; + c = session.find( Customer.class, c.getId() ); + assertThat( Hibernate.isInitialized( c.getLastOrder() ) ).isTrue(); + assertThat( Hibernate.isInitialized( c.getOrders() ) ).isTrue(); + for ( Order so : c.getOrders() ) { + assertThat( Hibernate.isInitialized( so.getCountry() ) ).isTrue(); + } + final Order order = c.getOrders().iterator().next(); + c.getOrders().remove( order ); + session.remove( c ); + final Order lastOrder = c.getLastOrder(); + c.setLastOrder( null ); + session.remove( order.getCountry() ); + session.remove( lastOrder ); + session.remove( order ); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/formula/JoinColumnOrFormulaTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/formula/JoinColumnOrFormulaTest.java index 02933acdf8b9..db88b2b3026f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/formula/JoinColumnOrFormulaTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/formula/JoinColumnOrFormulaTest.java @@ -4,41 +4,56 @@ */ package org.hibernate.orm.test.annotations.formula; -import java.util.HashSet; -import java.util.Set; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; - import org.hibernate.annotations.JoinColumnOrFormula; import org.hibernate.annotations.JoinFormula; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; - -import org.hibernate.testing.FailureExpected; +import org.hibernate.cfg.AvailableSettings; +import org.hibernate.cfg.Environment; +import org.hibernate.testing.jdbc.SharedDriverManagerConnectionProvider; +import org.hibernate.testing.orm.junit.BaseUnitTest; +import org.hibernate.testing.orm.junit.FailureExpected; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.hibernate.testing.util.ServiceRegistryUtil; -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 java.util.HashSet; +import java.util.Set; /** * @author Steve Ebersole */ -public class JoinColumnOrFormulaTest extends BaseUnitTestCase { +@BaseUnitTest +public class JoinColumnOrFormulaTest { private StandardServiceRegistry ssr; - @Before + @BeforeEach public void before() { - ssr = ServiceRegistryUtil.serviceRegistry(); + final StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder(); + if ( !Environment.getProperties().containsKey( AvailableSettings.CONNECTION_PROVIDER ) + && !builder.getSettings().containsKey( AvailableSettings.CONNECTION_PROVIDER ) ) { + builder.applySetting( + AvailableSettings.CONNECTION_PROVIDER, + SharedDriverManagerConnectionProvider.getInstance() + ); + builder.applySetting( + AvailableSettings.CONNECTION_PROVIDER_DISABLES_AUTOCOMMIT, + Boolean.TRUE + ); + } + + ssr = builder.build(); } - @After + @AfterEach public void after() { if ( ssr != null ) { StandardServiceRegistryBuilder.destroy( ssr ); @@ -46,8 +61,8 @@ public void after() { } @Test - @JiraKey( value = "HHH-9897" ) - @FailureExpected( jiraKey = "HHH-9897" ) + @JiraKey(value = "HHH-9897") + @FailureExpected(jiraKey = "HHH-9897") public void testUseOfJoinColumnOrFormula() { Metadata metadata = new MetadataSources( ssr ) .addAnnotatedClass( A.class ) @@ -60,23 +75,23 @@ public void testUseOfJoinColumnOrFormula() { metadata.buildSessionFactory().close(); } - @Entity( name = "A" ) - @Table( name = "A" ) + @Entity(name = "A") + @Table(name = "A") public static class A { @Id - @Column( name = "idA") + @Column(name = "idA") public Integer id; @OneToMany @JoinColumnOrFormula(formula = @JoinFormula(value = "idA", referencedColumnName = "idA")) - Set ds = new HashSet(); + Set ds = new HashSet<>(); } - @Entity( name = "D" ) - @Table( name = "D" ) + @Entity(name = "D") + @Table(name = "D") public static class D { @Id - @Column( name = "idA") + @Column(name = "idA") public Integer idA; } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/formula/JoinFormulaManyToOneLazyFetchingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/formula/JoinFormulaManyToOneLazyFetchingTest.java index e070c1b5af06..e3fdc91f142d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/formula/JoinFormulaManyToOneLazyFetchingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/formula/JoinFormulaManyToOneLazyFetchingTest.java @@ -4,8 +4,6 @@ */ package org.hibernate.orm.test.annotations.formula; -import java.io.Serializable; -import java.util.List; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.EnumType; @@ -14,36 +12,36 @@ import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; - import org.hibernate.LazyInitializationException; import org.hibernate.annotations.JoinColumnOrFormula; import org.hibernate.annotations.JoinFormula; import org.hibernate.annotations.processing.Exclude; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.io.Serializable; +import java.util.List; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.Fail.fail; @JiraKey(value = "HHH-12770") @Exclude -public class JoinFormulaManyToOneLazyFetchingTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Stock.class, - StockCode.class, - }; - } +@Jpa( + annotatedClasses = { + JoinFormulaManyToOneLazyFetchingTest.Stock.class, + JoinFormulaManyToOneLazyFetchingTest.StockCode.class, + } +) +public class JoinFormulaManyToOneLazyFetchingTest { - @Override - protected void afterEntityManagerFactoryBuilt() { - doInJPA( this::entityManagerFactory, entityManager -> { + + @BeforeAll + protected void setUp(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { StockCode code = new StockCode(); code.setId( 1L ); code.setCopeType( CodeType.TYPE_A ); @@ -62,16 +60,14 @@ protected void afterEntityManagerFactoryBuilt() { } @Test - public void testLazyLoading() { - List stocks = doInJPA( this::entityManagerFactory, entityManager -> { - return entityManager.createQuery( - "SELECT s FROM Stock s", Stock.class ) - .getResultList(); - } ); - assertEquals( 2, stocks.size() ); + public void testLazyLoading(EntityManagerFactoryScope scope) { + List stocks = scope.fromTransaction( entityManager -> + entityManager.createQuery( "SELECT s FROM Stock s", Stock.class ).getResultList() + ); + assertThat( stocks.size() ).isEqualTo( 2 ); try { - assertEquals( "ABC", stocks.get( 0 ).getCode().getRefNumber() ); + assertThat( stocks.get( 0 ).getCode().getRefNumber() ).isEqualTo( "ABC" ); fail( "Should have thrown LazyInitializationException" ); } @@ -81,18 +77,18 @@ public void testLazyLoading() { } @Test - public void testEagerLoading() { - doInJPA( this::entityManagerFactory, entityManager -> { - List stocks = entityManager.createQuery( - "SELECT s FROM Stock s", Stock.class ) + public void testEagerLoading(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + List stocks = entityManager.createQuery( + "SELECT s FROM Stock s", Stock.class ) .getResultList(); - assertEquals( 2, stocks.size() ); - assertEquals( "ABC", stocks.get( 0 ).getCode().getRefNumber() ); + assertThat( stocks.size() ).isEqualTo( 2 ); + assertThat( stocks.get( 0 ).getCode().getRefNumber() ).isEqualTo( "ABC" ); // In 5.x, for some reason, we didn't understand that a component is a FK, // hence a partial null was wrongly handled, but in 6.0 we handle this in a unified way - assertNull( stocks.get( 1 ).getCode() ); + assertThat( stocks.get( 1 ).getCode() ).isNull(); } ); } @@ -165,7 +161,7 @@ public void setRefNumber(String refNumber) { } public enum CodeType { - TYPE_A, TYPE_B; + TYPE_A, TYPE_B } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/formula/JoinFormulaManyToOneNotIgnoreLazyFetchingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/formula/JoinFormulaManyToOneNotIgnoreLazyFetchingTest.java index 8ecc8c168778..7d3e839caa9b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/formula/JoinFormulaManyToOneNotIgnoreLazyFetchingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/formula/JoinFormulaManyToOneNotIgnoreLazyFetchingTest.java @@ -4,23 +4,6 @@ */ package org.hibernate.orm.test.annotations.formula; -import java.io.Serializable; -import java.util.List; - -import org.hibernate.annotations.JoinColumnOrFormula; -import org.hibernate.annotations.JoinFormula; -import org.hibernate.annotations.NotFound; -import org.hibernate.annotations.NotFoundAction; -import org.hibernate.annotations.processing.Exclude; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.logger.LoggerInspectionRule; -import org.hibernate.testing.logger.Triggerable; -import org.junit.Rule; -import org.junit.Test; - - import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.EnumType; @@ -29,34 +12,48 @@ import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; +import org.hibernate.annotations.JoinColumnOrFormula; +import org.hibernate.annotations.JoinFormula; +import org.hibernate.annotations.NotFound; +import org.hibernate.annotations.NotFoundAction; +import org.hibernate.annotations.processing.Exclude; +import org.hibernate.testing.logger.Triggerable; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.logger.LoggerInspectionExtension; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.io.Serializable; +import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.hibernate.boot.BootLogging.BOOT_LOGGER; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; @JiraKey(value = "HHH-12770") @Exclude -public class JoinFormulaManyToOneNotIgnoreLazyFetchingTest extends BaseEntityManagerFunctionalTestCase { - - @Rule - public LoggerInspectionRule logInspection = new LoggerInspectionRule( BOOT_LOGGER ); +@Jpa( + annotatedClasses = { + JoinFormulaManyToOneNotIgnoreLazyFetchingTest.Stock.class, + JoinFormulaManyToOneNotIgnoreLazyFetchingTest.StockCode.class, + } +) +public class JoinFormulaManyToOneNotIgnoreLazyFetchingTest { - private final Triggerable triggerable = logInspection.watchForLogMessages( "HHH160133" ); + private Triggerable triggerable; + @RegisterExtension + public LoggerInspectionExtension logger = + LoggerInspectionExtension.builder().setLogger( BOOT_LOGGER ).build(); - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Stock.class, - StockCode.class, - }; - } + @BeforeAll + public void beforeAll(EntityManagerFactoryScope scope) { + triggerable = logger.watchForLogMessages( "HHH160133" ); + triggerable.reset(); - @Override - protected void afterEntityManagerFactoryBuilt() { - doInJPA( this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { StockCode code = new StockCode(); code.setId( 1L ); code.setCopeType( CodeType.TYPE_A ); @@ -75,20 +72,18 @@ protected void afterEntityManagerFactoryBuilt() { } @Test - public void testLazyLoading() { + public void testLazyLoading(EntityManagerFactoryScope scope) { assertThat( triggerable.wasTriggered() ) .describedAs( "Expecting WARN message to be logged" ) .isTrue(); - List stocks = doInJPA( this::entityManagerFactory, entityManager -> { - return entityManager.createQuery( - "SELECT s FROM Stock s", Stock.class ) - .getResultList(); - } ); - assertEquals( 2, stocks.size() ); + List stocks = scope.fromTransaction( entityManager -> + entityManager.createQuery( "SELECT s FROM Stock s", Stock.class ).getResultList() + ); + assertThat( stocks.size() ).isEqualTo( 2 ); - assertEquals( "ABC", stocks.get( 0 ).getCode().getRefNumber() ); - assertNull( stocks.get( 1 ).getCode() ); + assertThat( stocks.get( 0 ).getCode().getRefNumber() ).isEqualTo( "ABC" ); + assertThat( stocks.get( 1 ).getCode() ).isNull(); } @Entity(name = "Stock") @@ -161,7 +156,7 @@ public void setRefNumber(String refNumber) { } public enum CodeType { - TYPE_A, TYPE_B; + TYPE_A, TYPE_B } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/formula/JoinFormulaOneToOneNotIgnoreLazyFetchingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/formula/JoinFormulaOneToOneNotIgnoreLazyFetchingTest.java index 44759e871928..14f0a5cc32e8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/formula/JoinFormulaOneToOneNotIgnoreLazyFetchingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/formula/JoinFormulaOneToOneNotIgnoreLazyFetchingTest.java @@ -4,23 +4,6 @@ */ package org.hibernate.orm.test.annotations.formula; -import java.io.Serializable; -import java.util.List; - -import org.hibernate.annotations.JoinColumnOrFormula; -import org.hibernate.annotations.JoinFormula; -import org.hibernate.annotations.NotFound; -import org.hibernate.annotations.NotFoundAction; -import org.hibernate.annotations.processing.Exclude; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.logger.LoggerInspectionRule; -import org.hibernate.testing.logger.Triggerable; -import org.junit.Rule; -import org.junit.Test; - - import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.EnumType; @@ -29,34 +12,47 @@ import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.OneToOne; +import org.hibernate.annotations.JoinColumnOrFormula; +import org.hibernate.annotations.JoinFormula; +import org.hibernate.annotations.NotFound; +import org.hibernate.annotations.NotFoundAction; +import org.hibernate.annotations.processing.Exclude; +import org.hibernate.testing.logger.Triggerable; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.logger.LoggerInspectionExtension; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.io.Serializable; +import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.hibernate.boot.BootLogging.BOOT_LOGGER; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; @JiraKey(value = "HHH-12770") @Exclude -public class JoinFormulaOneToOneNotIgnoreLazyFetchingTest extends BaseEntityManagerFunctionalTestCase { - - @Rule - public LoggerInspectionRule logInspection = new LoggerInspectionRule( BOOT_LOGGER ); +@Jpa( + annotatedClasses = { + JoinFormulaOneToOneNotIgnoreLazyFetchingTest.Stock.class, + JoinFormulaOneToOneNotIgnoreLazyFetchingTest.StockCode.class, + } +) +public class JoinFormulaOneToOneNotIgnoreLazyFetchingTest { + private Triggerable triggerable; - private final Triggerable triggerable = logInspection.watchForLogMessages( "HHH160133" ); + @RegisterExtension + public LoggerInspectionExtension logger = + LoggerInspectionExtension.builder().setLogger( BOOT_LOGGER ).build(); + @BeforeAll + public void beforeAll(EntityManagerFactoryScope scope) { + triggerable = logger.watchForLogMessages( "HHH160133" ); + triggerable.reset(); - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Stock.class, - StockCode.class, - }; - } - - @Override - protected void afterEntityManagerFactoryBuilt() { - doInJPA( this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { StockCode code = new StockCode(); code.setId( 1L ); code.setCopeType( CodeType.TYPE_A ); @@ -75,20 +71,19 @@ protected void afterEntityManagerFactoryBuilt() { } @Test - public void testLazyLoading() { + public void testLazyLoading(EntityManagerFactoryScope scope) { assertThat( triggerable.wasTriggered() ) .describedAs( "Expecting WARN message to be logged" ) .isTrue(); - List stocks = doInJPA( this::entityManagerFactory, entityManager -> { - return entityManager.createQuery( - "SELECT s FROM Stock s", Stock.class ) - .getResultList(); - } ); - assertEquals( 2, stocks.size() ); + List stocks = scope.fromTransaction( entityManager -> + entityManager.createQuery( "SELECT s FROM Stock s", Stock.class ).getResultList() + ); + + assertThat( stocks.size() ).isEqualTo( 2 ); - assertEquals( "ABC", stocks.get( 0 ).getCode().getRefNumber() ); - assertNull( stocks.get( 1 ).getCode() ); + assertThat( stocks.get( 0 ).getCode().getRefNumber() ).isEqualTo( "ABC" ); + assertThat( stocks.get( 1 ).getCode() ).isNull(); } @Entity(name = "Stock") @@ -161,7 +156,7 @@ public void setRefNumber(String refNumber) { } public enum CodeType { - TYPE_A, TYPE_B; + TYPE_A, TYPE_B } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/formula/ManyToManyNotIgnoreLazyFetchingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/formula/ManyToManyNotIgnoreLazyFetchingTest.java index d7b5de3c5900..c7d40707d73d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/formula/ManyToManyNotIgnoreLazyFetchingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/formula/ManyToManyNotIgnoreLazyFetchingTest.java @@ -15,39 +15,34 @@ import org.hibernate.Hibernate; import org.hibernate.annotations.NotFound; import org.hibernate.annotations.NotFoundAction; -import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.orm.junit.JiraKeyGroup; -import org.junit.Test; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.hibernate.testing.transaction.TransactionUtil2.fromTransaction; -import static org.junit.Assert.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@JiraKeyGroup( value = { - @JiraKey( value = "HHH-12770" ), - @JiraKey( value = "HHH-15545" ) -} ) -public class ManyToManyNotIgnoreLazyFetchingTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Stock.class, - StockCode.class, - }; - } - @Override - protected void afterEntityManagerFactoryBuilt() { - doInJPA( this::entityManagerFactory, entityManager -> { +@JiraKeyGroup(value = { + @JiraKey(value = "HHH-12770"), + @JiraKey(value = "HHH-15545") +}) +@Jpa( + annotatedClasses = { + ManyToManyNotIgnoreLazyFetchingTest.Stock.class, + ManyToManyNotIgnoreLazyFetchingTest.StockCode.class, + } +) +public class ManyToManyNotIgnoreLazyFetchingTest { + + @BeforeAll + public void setUp(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { StockCode code = new StockCode(); code.setId( 1L ); code.setCopeType( CodeType.TYPE_A ); @@ -64,21 +59,23 @@ protected void afterEntityManagerFactoryBuilt() { entityManager.persist( stock2 ); entityManager.flush(); - entityManager.remove(code); + entityManager.remove( code ); stock1.getCodes().remove( code ); } ); } @Test - public void testLazyLoading() { - List stocks = fromTransaction( entityManagerFactory().unwrap( SessionFactoryImplementor.class ), session -> { - List list = session.createQuery("select s from Stock s order by id", Stock.class).getResultList(); - for (Stock s: list) { - assertFalse( Hibernate.isInitialized( s.getCodes() ) ); - Hibernate.initialize( s.getCodes() ); - } - return list; - } ); + public void testLazyLoading(EntityManagerFactoryScope scope) { + List stocks = scope.fromTransaction( + entityManager -> { + List list = entityManager.createQuery( "select s from Stock s order by id", Stock.class ) + .getResultList(); + for ( Stock s : list ) { + assertThat( Hibernate.isInitialized( s.getCodes() ) ).isFalse(); + Hibernate.initialize( s.getCodes() ); + } + return list; + } ); assertThat( stocks ).hasSize( 2 ); @@ -90,16 +87,17 @@ public void testLazyLoading() { } @Test - public void testEagerLoading() { - List stocks = fromTransaction( entityManagerFactory().unwrap( SessionFactoryImplementor.class ), - session -> session.createQuery("select s from Stock s left join fetch s.codes order by s.id", Stock.class) + public void testEagerLoading(EntityManagerFactoryScope scope) { + List stocks = scope.fromTransaction( + entityManager -> entityManager + .createQuery( "select s from Stock s left join fetch s.codes order by s.id", Stock.class ) .getResultList() ); assertThat( stocks ).hasSize( 2 ); - for (Stock s: stocks) { - assertTrue( Hibernate.isInitialized( s.getCodes() ) ); + for ( Stock s : stocks ) { + assertThat( Hibernate.isInitialized( s.getCodes() ) ).isTrue(); } final Stock firstStock = stocks.get( 0 ); @@ -179,7 +177,7 @@ public void setRefNumber(String refNumber) { } public enum CodeType { - TYPE_A, TYPE_B; + TYPE_A, TYPE_B } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/Customers.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/Customers.java index 70129de42c1d..204929c4fc09 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/Customers.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/Customers.java @@ -24,7 +24,7 @@ public class Customers implements Serializable { private int customerID; @OneToMany(mappedBy="owner", cascade= CascadeType.ALL, targetEntity=ShoppingBaskets.class) - private java.util.Set shoppingBasketses = new java.util.HashSet(); + private java.util.Set shoppingBasketses = new java.util.HashSet<>(); public void setCustomerID(int value) { this.customerID = value; @@ -38,11 +38,11 @@ public int getORMID() { return getCustomerID(); } - public void setShoppingBasketses(java.util.Set value) { + public void setShoppingBasketses(java.util.Set value) { this.shoppingBasketses = value; } - public java.util.Set getShoppingBasketses() { + public java.util.Set getShoppingBasketses() { return shoppingBasketses; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/IdManyToOneTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/IdManyToOneTest.java index 10a954ca8432..c21f9201277a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/IdManyToOneTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/IdManyToOneTest.java @@ -9,31 +9,71 @@ import jakarta.persistence.criteria.Join; import jakarta.persistence.criteria.JoinType; import jakarta.persistence.criteria.Root; - -import org.hibernate.Session; +import org.hibernate.boot.model.naming.ImplicitNamingStrategy; import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl; -import org.hibernate.cfg.Configuration; - +import org.hibernate.cfg.AvailableSettings; +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.SettingProvider; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Emmanuel Bernard */ -public class IdManyToOneTest extends BaseCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + Store.class, + Customer.class, + StoreCustomer.class, + CardKey.class, + CardField.class, + Card.class, + Project.class, + Course.class, + Student.class, + CourseStudent.class, + + //tested only through deployment + //ANN-590 testIdClassManyToOneWithReferenceColumn + Customers.class, + ShoppingBaskets.class, + ShoppingBasketsPK.class, + BasketItems.class, + BasketItemsPK.class + } +) +@ServiceRegistry( + settingProviders = @SettingProvider(settingName = AvailableSettings.IMPLICIT_NAMING_STRATEGY, + provider = IdManyToOneTest.ImplicitNameSettingProvider.class) +) +@SessionFactory +public class IdManyToOneTest { + + public static class ImplicitNameSettingProvider implements SettingProvider.Provider { + + @Override + public ImplicitNamingStrategy getSetting() { + return ImplicitNamingStrategyJpaCompliantImpl.INSTANCE; + } + } + @Test - public void testFkCreationOrdering() { + public void testFkCreationOrdering(SessionFactoryScope scope) { //no real test case, the sessionFactory building is tested - Session s = openSession(); - s.close(); + scope.inTransaction( + session -> { + } + ); } @Test - public void testIdClassManyToOne() { - inTransaction( s-> { + public void testIdClassManyToOne(SessionFactoryScope scope) { + scope.inTransaction( s -> { Store store = new Store(); Customer customer = new Customer(); s.persist( store ); @@ -43,18 +83,19 @@ public void testIdClassManyToOne() { s.flush(); s.clear(); - store = s.get(Store.class, store.id ); - assertEquals( 1, store.customers.size() ); - assertEquals( customer.id, store.customers.iterator().next().customer.id ); + store = s.find( Store.class, store.id ); + assertThat( store.customers.size() ).isEqualTo( 1 ); + assertThat( store.customers.iterator().next().customer.id ).isEqualTo( customer.id ); } ); //TODO test Customers / ShoppingBaskets / BasketItems testIdClassManyToOneWithReferenceColumn } @Test - @JiraKey( value = "HHH-7767" ) - public void testCriteriaRestrictionOnIdManyToOne() { - inTransaction( s -> { - s.createQuery( "from Course c join c.students cs join cs.student s where s.name = 'Foo'", Object[].class ).list(); + @JiraKey(value = "HHH-7767") + public void testCriteriaRestrictionOnIdManyToOne(SessionFactoryScope scope) { + scope.inTransaction( s -> { + s.createQuery( "from Course c join c.students cs join cs.student s where s.name = 'Foo'", Object[].class ) + .list(); CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); CriteriaQuery criteria = criteriaBuilder.createQuery( Course.class ); @@ -77,34 +118,4 @@ public void testCriteriaRestrictionOnIdManyToOne() { // criteria2.list(); } ); } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Store.class, - Customer.class, - StoreCustomer.class, - CardKey.class, - CardField.class, - Card.class, - Project.class, - Course.class, - Student.class, - CourseStudent.class, - - //tested only through deployment - //ANN-590 testIdClassManyToOneWithReferenceColumn - Customers.class, - ShoppingBaskets.class, - ShoppingBasketsPK.class, - BasketItems.class, - BasketItemsPK.class - }; - } - - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - configuration.setImplicitNamingStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE ); - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/ShoppingBaskets.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/ShoppingBaskets.java index 2c0e1c8cc5ee..7426fd82561f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/ShoppingBaskets.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/ShoppingBaskets.java @@ -33,7 +33,7 @@ public class ShoppingBaskets implements Serializable { private java.util.Date basketDatetime; @OneToMany(mappedBy="shoppingBaskets", cascade=CascadeType.ALL, targetEntity=BasketItems.class) - private java.util.Set items = new java.util.HashSet(); + private java.util.Set items = new java.util.HashSet<>(); public void setBasketDatetime(java.util.Date value) { this.basketDatetime = value; @@ -51,11 +51,11 @@ public Customers getOwner() { return owner; } - public void setItems(java.util.Set value) { + public void setItems(java.util.Set value) { this.items = value; } - public java.util.Set getItems() { + public java.util.Set getItems() { return items; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/StoreCustomerPK.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/StoreCustomerPK.java index c1dbf09e4b21..429c30fdd3b7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/StoreCustomerPK.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/StoreCustomerPK.java @@ -3,16 +3,20 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.idmanytoone; -import java.io.Serializable; + import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; +import java.io.Serializable; + /** * @author Emmanuel Bernard */ public class StoreCustomerPK implements Serializable { - StoreCustomerPK() {} + StoreCustomerPK() { + } + @Id @ManyToOne(optional = false) @JoinColumn(name = "idA") @@ -25,8 +29,8 @@ public class StoreCustomerPK implements Serializable { public StoreCustomerPK(Store store, Customer customer) { - this.store = store; - this.customer = customer; + this.store = store; + this.customer = customer; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/alphabetical/AlphabeticalIdManyToOneTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/alphabetical/AlphabeticalIdManyToOneTest.java index 7af025f040d8..e0eb404688d6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/alphabetical/AlphabeticalIdManyToOneTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/alphabetical/AlphabeticalIdManyToOneTest.java @@ -4,21 +4,30 @@ */ package org.hibernate.orm.test.annotations.idmanytoone.alphabetical; -import org.junit.Test; - -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +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; /** * @author Emmanuel Bernard */ -public class AlphabeticalIdManyToOneTest extends BaseCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + B.class, + C.class, + A.class + } +) +@SessionFactory +public class AlphabeticalIdManyToOneTest { + @Test - public void testAlphabeticalTest() throws Exception { + public void testAlphabeticalTest(SessionFactoryScope scope) { //test through deployment - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { B.class, C.class, A.class }; + scope.inTransaction( + session -> { + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/alphabetical/AlphabeticalManyToOneTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/alphabetical/AlphabeticalManyToOneTest.java index 437c4dba6ded..16ed4a3ab7c7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/alphabetical/AlphabeticalManyToOneTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/alphabetical/AlphabeticalManyToOneTest.java @@ -4,26 +4,32 @@ */ package org.hibernate.orm.test.annotations.idmanytoone.alphabetical; -import org.junit.Test; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +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; /** * @author Emmanuel Bernard */ -public class AlphabeticalManyToOneTest extends BaseCoreFunctionalTestCase { - @Test - public void testAlphabeticalTest() throws Exception { - //test through deployment - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { +@DomainModel( + annotatedClasses = { Acces.class, Droitacces.class, Benefserv.class, Service.class - }; + } +) +@SessionFactory +public class AlphabeticalManyToOneTest { + + @Test + public void testAlphabeticalTest(SessionFactoryScope scope) { + //test through deployment + scope.inTransaction( + session -> { + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/Caption.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/Caption.java index aee8cb550a0e..f669bdd1a27f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/Caption.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/Caption.java @@ -6,6 +6,8 @@ import org.hibernate.annotations.Immutable; +import java.util.Objects; + /** * Created by soldier on 12.04.16. */ @@ -35,7 +37,7 @@ public boolean equals(Object o) { return false; } Caption caption = (Caption) o; - return text != null ? text.equals( caption.text ) : caption.text == null; + return Objects.equals( text, caption.text ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/ImmutableEntityUpdateQueryHandlingModeExceptionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/ImmutableEntityUpdateQueryHandlingModeExceptionTest.java index 6a5bae6903cc..eae504868292 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/ImmutableEntityUpdateQueryHandlingModeExceptionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/ImmutableEntityUpdateQueryHandlingModeExceptionTest.java @@ -4,129 +4,122 @@ */ package org.hibernate.orm.test.annotations.immutable; -import java.util.Map; - import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.OneToOne; import jakarta.persistence.PersistenceException; - import org.hibernate.HibernateException; import org.hibernate.annotations.Immutable; - import org.hibernate.query.Query; +import org.hibernate.testing.orm.junit.DomainModel; 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.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.Fail.fail; /** * @author Vlad Mihalcea */ -@JiraKey( value = "HHH-12387" ) -public class ImmutableEntityUpdateQueryHandlingModeExceptionTest extends BaseNonConfigCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Country.class, State.class, Photo.class, - ImmutableEntity.class, MutableEntity.class}; - } - - @Override - protected void addSettings(Map settings) { -// settings.put( AvailableSettings.IMMUTABLE_ENTITY_UPDATE_QUERY_HANDLING_MODE, "exception" ); - } +@JiraKey(value = "HHH-12387") +@DomainModel( + annotatedClasses = { + Country.class, + State.class, + Photo.class, + ImmutableEntityUpdateQueryHandlingModeExceptionTest.ImmutableEntity.class, + ImmutableEntityUpdateQueryHandlingModeExceptionTest.MutableEntity.class + } +) +@SessionFactory +public class ImmutableEntityUpdateQueryHandlingModeExceptionTest { @Test - public void testBulkUpdate(){ - Country _country = doInHibernate( this::sessionFactory, session -> { + public void testBulkUpdate(SessionFactoryScope scope) { + Country _country = scope.fromTransaction( session -> { Country country = new Country(); - country.setName("Germany"); - session.persist(country); - + country.setName( "Germany" ); + session.persist( country ); return country; } ); try { - doInHibernate( this::sessionFactory, session -> { - session.createQuery("update Country set name = :name" ); - } ); - fail("Should throw PersistenceException"); + scope.inTransaction( session -> + session.createQuery( "update Country set name = :name" ) + ); + fail( "Should throw PersistenceException" ); } catch (PersistenceException e) { - assertTrue( e instanceof HibernateException ); - assertEquals( - "Error interpreting query [The query attempts to update an immutable entity: [Country] (set 'hibernate.query.immutable_entity_update_query_handling_mode' to suppress)] [update Country set name = :name]", - e.getMessage() - ); + assertThat( e ).isInstanceOf( HibernateException.class ); + assertThat( e.getMessage() ) + .isEqualTo( + "Error interpreting query [The query attempts to update an immutable entity: [Country] (set 'hibernate.query.immutable_entity_update_query_handling_mode' to suppress)] [update Country set name = :name]" ); } - doInHibernate( this::sessionFactory, session -> { - Country country = session.find(Country.class, _country.getId()); - assertEquals( "Germany", country.getName() ); + scope.inTransaction( session -> { + Country country = session.find( Country.class, _country.getId() ); + assertThat( country.getName() ).isEqualTo( "Germany" ); } ); } @Test - @JiraKey( value = "HHH-12927" ) - public void testUpdateMutableWithImmutableSubSelect() { - doInHibernate(this::sessionFactory, session -> { + @JiraKey(value = "HHH-12927") + public void testUpdateMutableWithImmutableSubSelect(SessionFactoryScope scope) { + scope.inTransaction( session -> { String selector = "foo"; - ImmutableEntity trouble = new ImmutableEntity(selector); - session.persist(trouble); + ImmutableEntity trouble = new ImmutableEntity( selector ); + session.persist( trouble ); - MutableEntity entity = new MutableEntity(trouble, "start"); - session.persist(entity); + MutableEntity entity = new MutableEntity( trouble, "start" ); + session.persist( entity ); // Change a mutable value via selection based on an immutable property String statement = "Update MutableEntity e set e.changeable = :changeable where e.trouble.id in " + - "(select i.id from ImmutableEntity i where i.selector = :selector)"; + "(select i.id from ImmutableEntity i where i.selector = :selector)"; - Query query = session.createQuery(statement); - query.setParameter("changeable", "end"); - query.setParameter("selector", "foo"); + Query query = session.createQuery( statement ); + query.setParameter( "changeable", "end" ); + query.setParameter( "selector", "foo" ); query.executeUpdate(); - session.refresh(entity); + session.refresh( entity ); // Assert that the value was changed. If HHH-12927 has not been fixed an exception will be thrown // before we get here. - assertEquals("end", entity.getChangeable()); - }); + assertThat( entity.getChangeable() ).isEqualTo( "end" ); + } ); } @Test - @JiraKey( value = "HHH-12927" ) - public void testUpdateImmutableWithMutableSubSelect() { - doInHibernate(this::sessionFactory, session -> { + @JiraKey(value = "HHH-12927") + public void testUpdateImmutableWithMutableSubSelect(SessionFactoryScope scope) { + scope.inTransaction( session -> { String selector = "foo"; - ImmutableEntity trouble = new ImmutableEntity(selector); - session.persist(trouble); + ImmutableEntity trouble = new ImmutableEntity( selector ); + session.persist( trouble ); - MutableEntity entity = new MutableEntity(trouble, "start"); - session.persist(entity); + MutableEntity entity = new MutableEntity( trouble, "start" ); + session.persist( entity ); // Change a mutable value via selection based on an immutable property String statement = "Update ImmutableEntity e set e.selector = :changeable where e.id in " + - "(select i.id from MutableEntity i where i.changeable = :selector)"; + "(select i.id from MutableEntity i where i.changeable = :selector)"; try { - session.createQuery(statement); + session.createQuery( statement ); - fail("Should have throw exception"); + fail( "Should have throw exception" ); } catch (Exception expected) { } - }); + } ); } @Entity(name = "MutableEntity") - public static class MutableEntity{ + public static class MutableEntity { @Id @GeneratedValue diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/ImmutableEntityUpdateQueryHandlingModeWarningTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/ImmutableEntityUpdateQueryHandlingModeWarningTest.java index a0b64e2243ac..d9ed6cd88a9a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/ImmutableEntityUpdateQueryHandlingModeWarningTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/ImmutableEntityUpdateQueryHandlingModeWarningTest.java @@ -5,65 +5,69 @@ package org.hibernate.orm.test.annotations.immutable; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.hibernate.testing.logger.LoggerInspectionRule; import org.hibernate.testing.logger.Triggerable; -import org.junit.Rule; -import org.junit.Test; - - -import java.util.Map; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.JiraKey; +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.hibernate.testing.orm.logger.LoggerInspectionExtension; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.hibernate.cfg.QuerySettings.IMMUTABLE_ENTITY_UPDATE_QUERY_HANDLING_MODE; import static org.hibernate.internal.CoreMessageLogger.CORE_LOGGER; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; /** * @author Vlad Mihalcea */ -@JiraKey( value = "HHH-12387" ) -public class ImmutableEntityUpdateQueryHandlingModeWarningTest extends BaseNonConfigCoreFunctionalTestCase { +@JiraKey(value = "HHH-12387") +@DomainModel( + annotatedClasses = { + Country.class, + State.class, + Photo.class + } +) +@SessionFactory +@ServiceRegistry( + settings = @Setting(name = IMMUTABLE_ENTITY_UPDATE_QUERY_HANDLING_MODE, value = "warning") +) +public class ImmutableEntityUpdateQueryHandlingModeWarningTest { - @Rule - public LoggerInspectionRule logInspection = new LoggerInspectionRule( CORE_LOGGER ); - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Country.class, State.class, Photo.class }; - } - - @Override - protected void addSettings(Map settings) { - settings.put( IMMUTABLE_ENTITY_UPDATE_QUERY_HANDLING_MODE, "warning" ); - } + @RegisterExtension + public LoggerInspectionExtension logInspection = + LoggerInspectionExtension.builder().setLogger( CORE_LOGGER ).build(); @Test - public void testBulkUpdate(){ - Country _country = doInHibernate( this::sessionFactory, session -> { + public void testBulkUpdate(SessionFactoryScope scope) { + Country _country = scope.fromTransaction( session -> { Country country = new Country(); - country.setName("Germany"); - session.persist(country); + country.setName( "Germany" ); + session.persist( country ); return country; } ); Triggerable triggerable = logInspection.watchForLogMessages( "HHH000487" ); triggerable.reset(); - doInHibernate( this::sessionFactory, session -> { - session.createQuery( - "update Country " + - "set name = :name" ) - .setParameter( "name", "N/A" ) - .executeUpdate(); + scope.inTransaction( session -> { + session.createMutationQuery( + "update Country " + + "set name = :name" ) + .setParameter( "name", "N/A" ) + .executeUpdate(); } ); - assertEquals( "HHH000487: The query [update Country set name = :name] updates an immutable entity: [Country]", triggerable.triggerMessage() ); + assertThat( triggerable.triggerMessage() ) + .isEqualTo( + "HHH000487: The query [update Country set name = :name] updates an immutable entity: [Country]" ); - doInHibernate( this::sessionFactory, session -> { - Country country = session.find(Country.class, _country.getId()); - assertEquals( "N/A", country.getName() ); + scope.inTransaction( session -> { + Country country = session.find( Country.class, _country.getId() ); + assertThat( country.getName() ).isEqualTo( "N/A" ); } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/ImmutableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/ImmutableTest.java index c047e1f6317d..65e509f021ae 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/ImmutableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/ImmutableTest.java @@ -4,218 +4,146 @@ */ package org.hibernate.orm.test.annotations.immutable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; import jakarta.persistence.PersistenceException; - import org.hibernate.AnnotationException; -import org.hibernate.Session; -import org.hibernate.Transaction; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.BootstrapServiceRegistry; import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; import org.hibernate.service.ServiceRegistry; - -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +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.util.ServiceRegistryUtil; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Fail.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * Tests for Immutable annotation. * * @author Hardy Ferentschik */ -public class ImmutableTest extends BaseCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + Country.class, + State.class, + Photo.class + } +) +@SessionFactory +public class ImmutableTest { + + @AfterEach + public void afterEach(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); + } @Test - public void testImmutableEntity() { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Country country = new Country(); - country.setName("Germany"); - s.persist(country); - tx.commit(); - s.close(); + public void testImmutableEntity(SessionFactoryScope scope) { + Country c = new Country(); + scope.inTransaction( + session -> { + c.setName( "Germany" ); + session.persist( c ); + } + ); // try changing the entity - s = openSession(); - tx = s.beginTransaction(); - Country germany = s.get(Country.class, country.getId()); - assertNotNull(germany); - germany.setName("France"); - assertEquals("Local name can be changed", "France", germany.getName()); - s.persist(germany); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + Country germany = session.find( Country.class, c.getId() ); + assertThat( germany ).isNotNull(); + germany.setName( "France" ); + assertThat( germany.getName() ) + .describedAs( "Local name can be changed" ) + .isEqualTo( "France" ); + + session.persist( germany ); + } + ); // retrieving the country again - it should be unmodified - s = openSession(); - tx = s.beginTransaction(); - germany = s.get(Country.class, country.getId()); - assertNotNull(germany); - assertEquals("Name should not have changed", "Germany", germany.getName()); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + Country germany = session.find( Country.class, c.getId() ); + assertThat( germany ).isNotNull(); + assertThat( germany.getName() ) + .describedAs( "Name should not have changed" ) + .isEqualTo( "Germany" ); + + } + ); } @Test - public void testImmutableCollection() { + public void testImmutableCollection(SessionFactoryScope scope) { Country country = new Country(); - country.setName("Germany"); + country.setName( "Germany" ); List states = new ArrayList<>(); State bayern = new State(); - bayern.setName("Bayern"); + bayern.setName( "Bayern" ); State hessen = new State(); - hessen.setName("Hessen"); + hessen.setName( "Hessen" ); State sachsen = new State(); - sachsen.setName("Sachsen"); - states.add(bayern); - states.add(hessen); - states.add(sachsen); - country.setStates(states); - - Session s = openSession(); - Transaction tx = s.beginTransaction(); - s.persist(country); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - Country germany = s.get(Country.class, country.getId()); - assertNotNull(germany); - assertEquals("Wrong number of states", 3, germany.getStates().size()); - - // try adding a state - State foobar = new State(); - foobar.setName("foobar"); - s.persist(foobar); - germany.getStates().add(foobar); - try { - tx.commit(); - fail(); - } - catch ( PersistenceException ex ) { - // expected - assertTrue(ex.getMessage().contains("Immutable collection was modified")); - log.debug("success"); - } - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - germany = s.get(Country.class, country.getId()); - assertNotNull(germany); - assertEquals("Wrong number of states", 3, germany.getStates().size()); - - // try deleting a state - germany.getStates().remove(0); - try { - tx.commit(); - fail(); - } catch (PersistenceException e) { - assertTrue(e.getMessage().contains("Immutable collection was modified")); - log.debug("success"); - } - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - germany = s.get(Country.class, country.getId()); - assertNotNull(germany); - assertEquals("Wrong number of states", 3, germany.getStates().size()); - tx.commit(); - s.close(); + sachsen.setName( "Sachsen" ); + states.add( bayern ); + states.add( hessen ); + states.add( sachsen ); + country.setStates( states ); + + scope.inTransaction( + session -> session.persist( country ) + ); + + PersistenceException persistenceException = assertThrows( PersistenceException.class, () -> scope.inTransaction( + session -> { + Country germany = session.find( Country.class, country.getId() ); + assertThat( germany ).isNotNull(); + assertThat( germany.getStates().size() ) + .describedAs( "Wrong number of states" ) + .isEqualTo( 3 ); + + // try adding a state + State foobar = new State(); + foobar.setName( "foobar" ); + session.persist( foobar ); + germany.getStates().add( foobar ); + } + ) ); + + assertThat( persistenceException.getMessage() ).contains( "Immutable collection was modified" ); + + persistenceException = assertThrows( PersistenceException.class, () -> scope.inTransaction( + session -> { + Country germany = session.find( Country.class, country.getId() ); + assertThat( germany ).isNotNull(); + assertThat( germany.getStates().size() ) + .describedAs( "Wrong number of states" ) + .isEqualTo( 3 ); + // try deleting a state + germany.getStates().remove( 0 ); + } + ) ); + + assertThat( persistenceException.getMessage() ).contains( "Immutable collection was modified" ); + + scope.inTransaction( + session -> { + Country germany = session.find( Country.class, country.getId() ); + assertThat( germany ).isNotNull(); + assertThat( germany.getStates().size() ) + .describedAs( "Wrong number of states" ) + .isEqualTo( 3 ); + } + ); } - @Test - public void testImmutableAttribute(){ - configuration().addAttributeConverter( ExifConverter.class); - configuration().addAttributeConverter( CaptionConverter.class); - Session s = openSession(); - Transaction tx = s.beginTransaction(); - - Photo photo = new Photo(); - photo.setName( "cat.jpg"); - photo.setMetadata( new Exif(Collections.singletonMap( "fake", "first value"))); - photo.setCaption( new Caption( "Cat.jpg caption" ) ); - s.persist(photo); - tx.commit(); - s.close(); - - // try changing the attribute - s = openSession(); - tx = s.beginTransaction(); - - Photo cat = s.get(Photo.class, photo.getId()); - assertNotNull(cat); - cat.getMetadata().getAttributes().put( "fake", "second value"); - cat.getCaption().setText( "new caption" ); - - tx.commit(); - s.close(); - - // retrieving the attribute again - it should be unmodified since object identity is the same - s = openSession(); - tx = s.beginTransaction(); - - cat = s.get(Photo.class, photo.getId()); - assertNotNull(cat); - assertEquals("Metadata should not have changed", "first value", cat.getMetadata().getAttribute( "fake")); - assertEquals("Caption should not have changed", "Cat.jpg caption", cat.getCaption().getText()); - - tx.commit(); - s.close(); - } - - @Test - public void testChangeImmutableAttribute(){ - configuration().addAttributeConverter( ExifConverter.class); - configuration().addAttributeConverter( CaptionConverter.class); - - Session s = openSession(); - Transaction tx = s.beginTransaction(); - - Photo photo = new Photo(); - photo.setName( "cat.jpg"); - photo.setMetadata( new Exif(Collections.singletonMap( "fake", "first value"))); - photo.setCaption( new Caption( "Cat.jpg caption" ) ); - s.persist(photo); - - tx.commit(); - s.close(); - - // replacing the attribute - s = openSession(); - tx = s.beginTransaction(); - - Photo cat = s.get(Photo.class, photo.getId()); - assertNotNull(cat); - cat.setMetadata( new Exif(Collections.singletonMap( "fake", "second value"))); - cat.setCaption( new Caption( "new caption" ) ); - - tx.commit(); - s.close(); - - // retrieving the attribute again - it should be modified since the holder object has changed as well - s = openSession(); - tx = s.beginTransaction(); - - cat = s.get(Photo.class, photo.getId()); - assertNotNull(cat); - - assertEquals("Metadata should have changed", "second value", cat.getMetadata().getAttribute( "fake")); - assertEquals("Caption should have changed", "new caption", cat.getCaption().getText()); - - tx.commit(); - s.close(); - } @Test public void testMisplacedImmutableAnnotation() { @@ -226,18 +154,14 @@ public void testMisplacedImmutableAnnotation() { // fail( "Expecting exception due to misplaced @Immutable annotation"); } catch (AnnotationException ignore) { - fail( "Exception with @Immutable on field"); + fail( "Exception with @Immutable on field" ); } finally { ServiceRegistry metaServiceRegistry = metadataSources.getServiceRegistry(); - if(metaServiceRegistry instanceof BootstrapServiceRegistry ) { + if ( metaServiceRegistry instanceof BootstrapServiceRegistry ) { BootstrapServiceRegistryBuilder.destroy( metaServiceRegistry ); } } } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Country.class, State.class, Photo.class }; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/ImmutableWithAttributeConverterTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/ImmutableWithAttributeConverterTest.java new file mode 100644 index 000000000000..2c86a54f1dfa --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/ImmutableWithAttributeConverterTest.java @@ -0,0 +1,127 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * Copyright Red Hat Inc. and Hibernate Authors + */ +package org.hibernate.orm.test.annotations.immutable; + +import org.hibernate.boot.MetadataBuilder; +import org.hibernate.boot.MetadataSources; +import org.hibernate.testing.orm.domain.DomainModelDescriptor; +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.Collections; + +import static org.assertj.core.api.Assertions.assertThat; + +@DomainModel( + modelDescriptorClasses = ImmutableWithAttributeConverterTest.ImmutableModel.class +) +@SessionFactory +public class ImmutableWithAttributeConverterTest { + + public static class ImmutableModel implements DomainModelDescriptor { + @Override + public Class[] getAnnotatedClasses() { + return new Class[] { + Country.class, + State.class, + Photo.class + }; + } + + + @Override + public void applyDomainModel(MetadataSources sources) { + MetadataBuilder metadataBuilder = sources.getMetadataBuilder(); + metadataBuilder.applyAttributeConverter( ExifConverter.class ); + metadataBuilder.applyAttributeConverter( CaptionConverter.class ); + } + } + + @AfterEach + public void afterEach(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); + } + + @Test + public void testImmutableAttribute(SessionFactoryScope scope) { + + Photo photo = new Photo(); + scope.inTransaction( + session -> { + photo.setName( "cat.jpg" ); + photo.setMetadata( new Exif( Collections.singletonMap( "fake", "first value" ) ) ); + photo.setCaption( new Caption( "Cat.jpg caption" ) ); + session.persist( photo ); + } + ); + + // try changing the attribute + scope.inTransaction( + session -> { + Photo cat = session.get( Photo.class, photo.getId() ); + assertThat( cat ).isNotNull(); + cat.getMetadata().getAttributes().put( "fake", "second value" ); + cat.getCaption().setText( "new caption" ); + } + ); + + // retrieving the attribute again - it should be unmodified since object identity is the same + scope.inTransaction( + session -> { + Photo cat = session.get( Photo.class, photo.getId() ); + assertThat( cat ).isNotNull(); + assertThat( cat.getMetadata().getAttribute( "fake" ) ) + .describedAs( "Metadata should not have changed" ) + .isEqualTo( "first value" ); + assertThat( cat.getCaption().getText() ) + .describedAs( "Caption should not have changed" ) + .isEqualTo( "Cat.jpg caption" ); + } + ); + } + + @Test + public void testChangeImmutableAttribute(SessionFactoryScope scope) { + + Photo photo = new Photo(); + scope.inTransaction( + session -> { + photo.setName( "cat.jpg" ); + photo.setMetadata( new Exif( Collections.singletonMap( "fake", "first value" ) ) ); + photo.setCaption( new Caption( "Cat.jpg caption" ) ); + session.persist( photo ); + } + ); + + // replacing the attribute + scope.inTransaction( + session -> { + Photo cat = session.get( Photo.class, photo.getId() ); + assertThat( cat ).isNotNull(); + cat.setMetadata( new Exif( Collections.singletonMap( "fake", "second value" ) ) ); + cat.setCaption( new Caption( "new caption" ) ); + } + ); + + // retrieving the attribute again - it should be modified since the holder object has changed as well + scope.inTransaction( + session -> { + Photo cat = session.get( Photo.class, photo.getId() ); + assertThat( cat ).isNotNull(); + + assertThat( cat.getMetadata().getAttribute( "fake" ) ) + .describedAs( "Metadata should have changed" ) + .isEqualTo( "second value" ); + assertThat( cat.getCaption().getText() ) + .describedAs( "Caption should have changed" ) + .isEqualTo( "new caption" ); + } + ); + } + +} diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/index/jpa/AbstractJPAIndexTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/index/jpa/AbstractJPAIndexTest.java index 8bb78892a7b3..684087a0ecd9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/index/jpa/AbstractJPAIndexTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/index/jpa/AbstractJPAIndexTest.java @@ -4,11 +4,8 @@ */ package org.hibernate.orm.test.annotations.index.jpa; -import java.util.Iterator; - -import org.hibernate.boot.MetadataBuilder; +import org.hibernate.boot.model.naming.ImplicitNamingStrategy; import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.AvailableSettings; import org.hibernate.internal.util.StringHelper; import org.hibernate.mapping.Bag; @@ -21,119 +18,138 @@ import org.hibernate.mapping.Table; import org.hibernate.mapping.UniqueKey; import org.hibernate.metamodel.CollectionClassification; +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.SettingProvider; +import org.junit.jupiter.api.Test; + +import java.util.Iterator; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * @author Strong Liu */ -public abstract class AbstractJPAIndexTest extends BaseNonConfigCoreFunctionalTestCase { - @Override - protected void configureMetadataBuilder(MetadataBuilder metadataBuilder) { - super.configureMetadataBuilder( metadataBuilder ); - metadataBuilder.applyImplicitNamingStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE ); +@SessionFactory +@ServiceRegistry( + settingProviders = { + @SettingProvider(settingName = AvailableSettings.DEFAULT_LIST_SEMANTICS, + provider = AbstractJPAIndexTest.ListSemanticProvider.class), + @SettingProvider(settingName = AvailableSettings.IMPLICIT_NAMING_STRATEGY, + provider = AbstractJPAIndexTest.ImplicitNameSettingProvider.class)} +) +public abstract class AbstractJPAIndexTest { + + public static class ImplicitNameSettingProvider implements SettingProvider.Provider { + @Override + public ImplicitNamingStrategy getSetting() { + return ImplicitNamingStrategyJpaCompliantImpl.INSTANCE; + } } - @Override - protected void configureStandardServiceRegistryBuilder(StandardServiceRegistryBuilder ssrb) { - super.configureStandardServiceRegistryBuilder( ssrb ); - ssrb.applySetting( AvailableSettings.DEFAULT_LIST_SEMANTICS, CollectionClassification.BAG ); + public static class ListSemanticProvider implements SettingProvider.Provider { + @Override + public CollectionClassification getSetting() { + return CollectionClassification.BAG; + } } @Test - public void testTableIndex() { - PersistentClass entity = metadata().getEntityBinding( Car.class.getName() ); - Iterator itr = entity.getTable().getUniqueKeys().values().iterator(); - assertTrue( itr.hasNext() ); - UniqueKey uk = (UniqueKey) itr.next(); - assertFalse( itr.hasNext() ); - assertTrue( StringHelper.isNotEmpty( uk.getName() ) ); - assertEquals( 2, uk.getColumnSpan() ); - Column column = (Column) uk.getColumns().get( 0 ); - assertEquals( "brand", column.getName() ); - column = (Column) uk.getColumns().get( 1 ); - assertEquals( "producer", column.getName() ); - assertSame( entity.getTable(), uk.getTable() ); - - - itr = entity.getTable().getIndexes().values().iterator(); - assertTrue( itr.hasNext() ); - Index index = (Index)itr.next(); - assertFalse( itr.hasNext() ); - assertEquals( "Car_idx", index.getName() ); - assertEquals( 1, index.getColumnSpan() ); + public void testTableIndex(SessionFactoryScope scope) { + PersistentClass entity = scope.getMetadataImplementor().getEntityBinding( Car.class.getName() ); + Iterator itr = entity.getTable().getUniqueKeys().values().iterator(); + assertThat( itr.hasNext() ).isTrue(); + UniqueKey uk = itr.next(); + assertThat( itr.hasNext() ).isFalse(); + assertThat( StringHelper.isNotEmpty( uk.getName() ) ).isTrue(); + assertThat( uk.getColumnSpan() ).isEqualTo( 2 ); + Column column = uk.getColumns().get( 0 ); + assertThat( column.getName() ).isEqualTo( "brand" ); + column = uk.getColumns().get( 1 ); + assertThat( column.getName() ).isEqualTo( "producer" ); + assertThat( uk.getTable() ).isSameAs( entity.getTable() ); + + + Iterator indexItr = entity.getTable().getIndexes().values().iterator(); + assertThat( indexItr.hasNext() ).isTrue(); + Index index = indexItr.next(); + assertThat( indexItr.hasNext() ).isFalse(); + assertThat( index.getName() ).isEqualTo( "Car_idx" ); + assertThat( index.getColumnSpan() ).isEqualTo( 1 ); column = index.getColumns().iterator().next(); - assertEquals( "since", column.getName() ); - assertSame( entity.getTable(), index.getTable() ); + assertThat( column.getName() ).isEqualTo( "since" ); + assertThat( index.getTable() ).isSameAs( entity.getTable() ); } @Test - public void testSecondaryTableIndex(){ - PersistentClass entity = metadata().getEntityBinding( Car.class.getName() ); + public void testSecondaryTableIndex(SessionFactoryScope scope) { + PersistentClass entity = scope.getMetadataImplementor().getEntityBinding( Car.class.getName() ); Join join = entity.getJoins().get( 0 ); Iterator itr = join.getTable().getIndexes().values().iterator(); - assertTrue( itr.hasNext() ); + assertThat( itr.hasNext() ).isTrue(); Index index = itr.next(); - assertFalse( itr.hasNext() ); - assertTrue( "index name is not generated", StringHelper.isNotEmpty( index.getName() ) ); - assertEquals( 2, index.getColumnSpan() ); + assertThat( itr.hasNext() ).isFalse(); + assertThat( StringHelper.isNotEmpty( index.getName() ) ) + .describedAs( "index name is not generated" ) + .isTrue(); + assertThat( index.getColumnSpan() ).isEqualTo( 2 ); Iterator columnIterator = index.getColumns().iterator(); Column column = columnIterator.next(); - assertEquals( "dealer_name", column.getName() ); + assertThat( column.getName() ).isEqualTo( "dealer_name" ); column = columnIterator.next(); - assertEquals( "rate", column.getName() ); - assertSame( join.getTable(), index.getTable() ); + assertThat( column.getName() ).isEqualTo( "rate" ); + assertThat( index.getTable() ).isSameAs( join.getTable() ); } @Test - public void testCollectionTableIndex(){ - PersistentClass entity = metadata().getEntityBinding( Car.class.getName() ); + public void testCollectionTableIndex(SessionFactoryScope scope) { + PersistentClass entity = scope.getMetadataImplementor().getEntityBinding( Car.class.getName() ); Property property = entity.getProperty( "otherDealers" ); - Set set = (Set)property.getValue(); + Set set = (Set) property.getValue(); Table collectionTable = set.getCollectionTable(); Iterator itr = collectionTable.getIndexes().values().iterator(); - assertTrue( itr.hasNext() ); + assertThat( itr.hasNext() ).isTrue(); Index index = itr.next(); - assertFalse( itr.hasNext() ); - assertTrue( "index name is not generated", StringHelper.isNotEmpty( index.getName() ) ); - assertEquals( 1, index.getColumnSpan() ); + assertThat( itr.hasNext() ).isFalse(); + assertThat( StringHelper.isNotEmpty( index.getName() ) ) + .describedAs( "index name is not generated" ) + .isTrue(); + assertThat( index.getColumnSpan() ).isEqualTo( 1 ); Iterator columnIterator = index.getColumns().iterator(); Column column = columnIterator.next(); - assertEquals( "name", column.getName() ); - assertSame( collectionTable, index.getTable() ); + assertThat( column.getName() ).isEqualTo( "name" ); + assertThat( index.getTable() ).isSameAs( collectionTable ); } @Test - public void testJoinTableIndex(){ - PersistentClass entity = metadata().getEntityBinding( Importer.class.getName() ); + public void testJoinTableIndex(SessionFactoryScope scope) { + PersistentClass entity = scope.getMetadataImplementor().getEntityBinding( Importer.class.getName() ); Property property = entity.getProperty( "cars" ); - Bag set = (Bag)property.getValue(); + Bag set = (Bag) property.getValue(); Table collectionTable = set.getCollectionTable(); Iterator itr = collectionTable.getIndexes().values().iterator(); - assertTrue( itr.hasNext() ); + assertThat( itr.hasNext() ).isTrue(); Index index = itr.next(); - assertFalse( itr.hasNext() ); - assertTrue( "index name is not generated", StringHelper.isNotEmpty( index.getName() ) ); - assertEquals( 1, index.getColumnSpan() ); + assertThat( itr.hasNext() ).isFalse(); + assertThat( StringHelper.isNotEmpty( index.getName() ) ) + .describedAs( "index name is not generated" ) + .isTrue(); + assertThat( index.getColumnSpan() ).isEqualTo( 1 ); Iterator columnIterator = index.getColumns().iterator(); Column column = columnIterator.next(); - assertEquals( "importers_id", column.getName() ); - assertSame( collectionTable, index.getTable() ); + assertThat( column.getName() ).isEqualTo( "importers_id" ); + assertThat( index.getTable() ).isSameAs( collectionTable ); } @Test - public void testTableGeneratorIndex(){ + public void testTableGeneratorIndex() { //todo } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/index/jpa/IndexTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/index/jpa/IndexTest.java index 09ca2188f372..daea0d7f870f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/index/jpa/IndexTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/index/jpa/IndexTest.java @@ -4,16 +4,17 @@ */ package org.hibernate.orm.test.annotations.index.jpa; +import org.hibernate.testing.orm.junit.DomainModel; + /** * @author Strong Liu */ -public class IndexTest extends AbstractJPAIndexTest { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { +@DomainModel( + annotatedClasses = { Car.class, Dealer.class, Importer.class - }; - } + } +) +public class IndexTest extends AbstractJPAIndexTest { } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/index/jpa/OrmXmlIndexTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/index/jpa/OrmXmlIndexTest.java index 5a3a5e7e8e7c..e98c509e9286 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/index/jpa/OrmXmlIndexTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/index/jpa/OrmXmlIndexTest.java @@ -5,12 +5,13 @@ package org.hibernate.orm.test.annotations.index.jpa; +import org.hibernate.testing.orm.junit.DomainModel; + /** * @author Strong Liu */ +@DomainModel( + xmlMappings = "org/hibernate/orm/test/annotations/index/jpa/orm-index.xml" +) public class OrmXmlIndexTest extends AbstractJPAIndexTest { - @Override - protected String[] getXmlFiles() { - return new String[] { "org/hibernate/orm/test/annotations/index/jpa/orm-index.xml" }; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/GenerationGroup.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/GenerationGroup.java index 185b3e6e1d30..6845fcc8264d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/GenerationGroup.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/GenerationGroup.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.indexcoll; + import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/GenerationUser.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/GenerationUser.java index 629c50eac067..bbc179de8ec2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/GenerationUser.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/GenerationUser.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.indexcoll; + import java.util.HashMap; import java.util.Map; import jakarta.persistence.Entity; @@ -23,7 +24,7 @@ public class GenerationUser { @OneToMany @MapKey(name="generation") - private Map ref = new HashMap(); + private Map ref = new HashMap<>(); public int getId() { return id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/MapKeyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/MapKeyTest.java index 485cf798f11b..827128116f3d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/MapKeyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/MapKeyTest.java @@ -4,48 +4,47 @@ */ package org.hibernate.orm.test.annotations.indexcoll; -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.Test; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; - -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Emmanuel Bernard */ -public class MapKeyTest extends BaseCoreFunctionalTestCase { - @Test - public void testMapKeyOnEmbeddedId() { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Generation c = new Generation(); - c.setAge( "a" ); - c.setCulture( "b" ); - c.setSubGeneration( new Generation.SubGeneration( "description" ) ); - GenerationGroup r = new GenerationGroup(); - r.setGeneration( c ); - s.persist( r ); - GenerationUser m = new GenerationUser(); - s.persist( m ); - m.getRef().put( c, r ); - s.flush(); - s.clear(); - - m = (GenerationUser) s.get( GenerationUser.class, m.getId() ); - Generation cRead = m.getRef().keySet().iterator().next(); - assertEquals( "a",cRead.getAge() ); - assertEquals( "description", cRead.getSubGeneration().getDescription() ); - tx.rollback(); - s.close(); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { +@DomainModel( + annotatedClasses = { GenerationUser.class, GenerationGroup.class - }; + } +) +@SessionFactory +public class MapKeyTest { + + @Test + public void testMapKeyOnEmbeddedId(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Generation c = new Generation(); + c.setAge( "a" ); + c.setCulture( "b" ); + c.setSubGeneration( new Generation.SubGeneration( "description" ) ); + GenerationGroup r = new GenerationGroup(); + r.setGeneration( c ); + session.persist( r ); + GenerationUser m = new GenerationUser(); + session.persist( m ); + m.getRef().put( c, r ); + session.flush(); + session.clear(); + + m = session.find( GenerationUser.class, m.getId() ); + Generation cRead = m.getRef().keySet().iterator().next(); + assertThat( cRead.getAge() ).isEqualTo( "a" ); + assertThat( cRead.getSubGeneration().getDescription() ).isEqualTo( "description" ); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/eager/Atmosphere.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/eager/Atmosphere.java index 2f3e070de7d6..70061f21d93f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/eager/Atmosphere.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/eager/Atmosphere.java @@ -3,9 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.indexcoll.eager; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; + import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.ElementCollection; @@ -23,17 +21,20 @@ import jakarta.persistence.MapKeyJoinColumns; import jakarta.persistence.MapKeyTemporal; import jakarta.persistence.TemporalType; - import org.hibernate.orm.test.annotations.indexcoll.Gas; import org.hibernate.orm.test.annotations.indexcoll.GasKey; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + /** * @author Emmanuel Bernard */ @Entity public class Atmosphere { - public static enum Level { + public enum Level { LOW, HIGH } @@ -43,45 +44,45 @@ public static enum Level { public Integer id; @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) - @MapKeyColumn(name="gas_name") - public Map gases = new HashMap(); + @MapKeyColumn(name = "gas_name") + public Map gases = new HashMap<>(); @MapKeyTemporal(TemporalType.DATE) @ElementCollection(fetch = FetchType.EAGER) - @MapKeyColumn(nullable=false) - public Map colorPerDate = new HashMap(); + @MapKeyColumn(nullable = false) + public Map colorPerDate = new HashMap<>(); @ElementCollection(fetch = FetchType.EAGER) @MapKeyEnumerated(EnumType.STRING) - @MapKeyColumn(nullable=false) - public Map colorPerLevel = new HashMap(); + @MapKeyColumn(nullable = false) + public Map colorPerLevel = new HashMap<>(); @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) - @MapKeyJoinColumn(name="gas_id" ) + @MapKeyJoinColumn(name = "gas_id") @JoinTable(name = "Gas_per_key") public Map gasesPerKey = new HashMap(); @ElementCollection(fetch = FetchType.EAGER) - @Column(name="composition_rate") - @MapKeyJoinColumns( { @MapKeyJoinColumn(name="gas_id" ) } ) //use @MapKeyJoinColumns explicitly for tests + @Column(name = "composition_rate") + @MapKeyJoinColumns({@MapKeyJoinColumn(name = "gas_id")}) //use @MapKeyJoinColumns explicitly for tests @JoinTable(name = "Composition", joinColumns = @JoinColumn(name = "atmosphere_id")) - public Map composition = new HashMap(); + public Map composition = new HashMap<>(); //use default JPA 2 column name for map key @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @MapKeyColumn - @JoinTable(name="Atm_Gas_Def") - public Map gasesDef = new HashMap(); + @JoinTable(name = "Atm_Gas_Def") + public Map gasesDef = new HashMap<>(); //use default HAN legacy column name for map key @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @MapKeyColumn - @JoinTable(name="Atm_Gas_DefLeg") - public Map gasesDefLeg = new HashMap(); + @JoinTable(name = "Atm_Gas_DefLeg") + public Map gasesDefLeg = new HashMap<>(); @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @MapKeyJoinColumn @JoinTable(name = "Gas_p_key_def") - public Map gasesPerKeyDef = new HashMap(); + public Map gasesPerKeyDef = new HashMap<>(); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/eager/EagerIndexedCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/eager/EagerIndexedCollectionTest.java index 0b8b11377626..0f381f28f84d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/eager/EagerIndexedCollectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/eager/EagerIndexedCollectionTest.java @@ -4,148 +4,158 @@ */ package org.hibernate.orm.test.annotations.indexcoll.eager; -import java.util.Date; -import java.util.Iterator; - import org.hibernate.Hibernate; -import org.hibernate.Session; -import org.hibernate.Transaction; import org.hibernate.mapping.Collection; import org.hibernate.mapping.Column; - -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; import org.hibernate.orm.test.annotations.indexcoll.Gas; import org.hibernate.orm.test.annotations.indexcoll.GasKey; -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.Date; +import java.util.Iterator; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; /** * Test index collections * * @author Emmanuel Bernard */ -public class EagerIndexedCollectionTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + Atmosphere.class, + Gas.class, + GasKey.class + } +) +@SessionFactory +public class EagerIndexedCollectionTest { + + @AfterEach + public void afterEach(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); + } + @Test - public void testJPA2DefaultMapColumns() throws Exception { - isDefaultKeyColumnPresent( Atmosphere.class.getName(), "gasesDef", "_KEY" ); - isDefaultKeyColumnPresent( Atmosphere.class.getName(), "gasesPerKeyDef", "_KEY" ); - isDefaultKeyColumnPresent( Atmosphere.class.getName(), "gasesDefLeg", "_KEY" ); + public void testJPA2DefaultMapColumns(SessionFactoryScope scope) { + isDefaultKeyColumnPresent( Atmosphere.class.getName(), "gasesDef", "_KEY", scope ); + isDefaultKeyColumnPresent( Atmosphere.class.getName(), "gasesPerKeyDef", "_KEY", scope ); + isDefaultKeyColumnPresent( Atmosphere.class.getName(), "gasesDefLeg", "_KEY", scope ); } - private void isDefaultKeyColumnPresent(String collectionOwner, String propertyName, String suffix) { - assertTrue( "Could not find " + propertyName + suffix, - isDefaultColumnPresent(collectionOwner, propertyName, suffix) ); + private void isDefaultKeyColumnPresent(String collectionOwner, String propertyName, String suffix, SessionFactoryScope scope) { + assertThat( isDefaultColumnPresent( collectionOwner, propertyName, suffix, scope ) ) + .describedAs( "Could not find " + propertyName + suffix ) + .isTrue(); } - private boolean isDefaultColumnPresent(String collectionOwner, String propertyName, String suffix) { - final Collection collection = metadata().getCollectionBinding( collectionOwner + "." + propertyName ); + private boolean isDefaultColumnPresent(String collectionOwner, String propertyName, String suffix, SessionFactoryScope scope) { + final Collection collection = scope.getMetadataImplementor() + .getCollectionBinding( collectionOwner + "." + propertyName ); final Iterator columnIterator = collection.getCollectionTable().getColumns().iterator(); boolean hasDefault = false; while ( columnIterator.hasNext() ) { Column column = columnIterator.next(); - if ( (propertyName + suffix).equals( column.getName() ) ) hasDefault = true; + if ( (propertyName + suffix).equals( column.getName() ) ) { + hasDefault = true; + } } return hasDefault; } @Test - public void testRealMap() throws Exception { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Atmosphere atm = new Atmosphere(); - Atmosphere atm2 = new Atmosphere(); - GasKey key = new GasKey(); - key.setName( "O2" ); - Gas o2 = new Gas(); - o2.name = "oxygen"; - atm.gases.put( "100%", o2 ); - atm.gasesPerKey.put( key, o2 ); - atm2.gases.put( "100%", o2 ); - atm2.gasesPerKey.put( key, o2 ); - s.persist( key ); - s.persist( atm ); - s.persist( atm2 ); - - s.flush(); - s.clear(); - - atm = (Atmosphere) s.get( Atmosphere.class, atm.id ); - key = (GasKey) s.get( GasKey.class, key.getName() ); - assertEquals( 1, atm.gases.size() ); - assertEquals( o2.name, atm.gases.get( "100%" ).name ); - assertEquals( o2.name, atm.gasesPerKey.get( key ).name ); - tx.rollback(); - s.close(); + public void testRealMap(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Atmosphere atm = new Atmosphere(); + Atmosphere atm2 = new Atmosphere(); + GasKey key = new GasKey(); + key.setName( "O2" ); + Gas o2 = new Gas(); + o2.name = "oxygen"; + atm.gases.put( "100%", o2 ); + atm.gasesPerKey.put( key, o2 ); + atm2.gases.put( "100%", o2 ); + atm2.gasesPerKey.put( key, o2 ); + session.persist( key ); + session.persist( atm ); + session.persist( atm2 ); + + session.flush(); + session.clear(); + + atm = session.find( Atmosphere.class, atm.id ); + key = session.find( GasKey.class, key.getName() ); + assertThat( atm.gases.size() ).isEqualTo( 1 ); + assertThat( atm.gases.get( "100%" ).name ).isEqualTo( o2.name ); + assertThat( atm.gasesPerKey.get( key ).name ).isEqualTo( o2.name ); + } + ); } @Test - public void testTemporalKeyMap() throws Exception { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Atmosphere atm = new Atmosphere(); - atm.colorPerDate.put( new Date(1234567000), "red" ); - s.persist( atm ); - - s.flush(); - s.clear(); - - atm = (Atmosphere) s.get( Atmosphere.class, atm.id ); - assertEquals( 1, atm.colorPerDate.size() ); - final Date date = atm.colorPerDate.keySet().iterator().next(); - final long diff = new Date( 1234567000 ).getTime() - date.getTime(); - assertTrue( "24h diff max", diff >= 0 && diff < 24*60*60*1000 ); - tx.rollback(); - s.close(); + public void testTemporalKeyMap(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Atmosphere atm = new Atmosphere(); + atm.colorPerDate.put( new Date( 1234567000 ), "red" ); + session.persist( atm ); + + session.flush(); + session.clear(); + + atm = session.find( Atmosphere.class, atm.id ); + assertThat( atm.colorPerDate.size() ).isEqualTo( 1 ); + final Date date = atm.colorPerDate.keySet().iterator().next(); + final long diff = new Date( 1234567000 ).getTime() - date.getTime(); + assertThat( diff >= 0 && diff < 24 * 60 * 60 * 1000 ) + .describedAs( "24h diff max" ) + .isTrue(); + } + ); } @Test - public void testEnumKeyType() throws Exception { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Atmosphere atm = new Atmosphere(); - atm.colorPerLevel.put( Atmosphere.Level.HIGH, "red" ); - s.persist( atm ); - - s.flush(); - s.clear(); - - atm = (Atmosphere) s.get( Atmosphere.class, atm.id ); - assertEquals( 1, atm.colorPerLevel.size() ); - assertEquals( "red", atm.colorPerLevel.get( Atmosphere.Level.HIGH) ); - tx.rollback(); - s.close(); + public void testEnumKeyType(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Atmosphere atm = new Atmosphere(); + atm.colorPerLevel.put( Atmosphere.Level.HIGH, "red" ); + session.persist( atm ); + + session.flush(); + session.clear(); + + atm = session.find( Atmosphere.class, atm.id ); + assertThat( atm.colorPerLevel.size() ).isEqualTo( 1 ); + assertThat( atm.colorPerLevel.get( Atmosphere.Level.HIGH ) ).isEqualTo( "red" ); + } + ); } @Test - public void testEntityKeyElementTarget() throws Exception { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Atmosphere atm = new Atmosphere(); - Gas o2 = new Gas(); - o2.name = "oxygen"; - atm.composition.put( o2, 94.3 ); - s.persist( o2 ); - s.persist( atm ); - - s.flush(); - s.clear(); - - atm = (Atmosphere) s.get( Atmosphere.class, atm.id ); - assertTrue( Hibernate.isInitialized( atm.composition ) ); - assertEquals( 1, atm.composition.size() ); - assertEquals( o2.name, atm.composition.keySet().iterator().next().name ); - tx.rollback(); - s.close(); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - Atmosphere.class, - Gas.class, - GasKey.class - }; + public void testEntityKeyElementTarget(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Atmosphere atm = new Atmosphere(); + Gas o2 = new Gas(); + o2.name = "oxygen"; + atm.composition.put( o2, 94.3 ); + session.persist( o2 ); + session.persist( atm ); + + session.flush(); + session.clear(); + + atm = session.find( Atmosphere.class, atm.id ); + assertThat( Hibernate.isInitialized( atm.composition ) ).isTrue(); + assertThat( atm.composition.size() ).isEqualTo( 1 ); + assertThat( atm.composition.keySet().iterator().next().name ).isEqualTo( o2.name ); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/join/B.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/join/B.java index f7adf21ec4dc..3032e30dba9e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/join/B.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/join/B.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.join; + import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/join/C.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/join/C.java index 02cd7b161b82..6a766a808683 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/join/C.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/join/C.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.join; + import jakarta.persistence.Column; import jakarta.persistence.DiscriminatorValue; import jakarta.persistence.Entity; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/join/DogPk.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/join/DogPk.java index 4f779dc1374a..f9cad8de4083 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/join/DogPk.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/join/DogPk.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.join; + import java.io.Serializable; import jakarta.persistence.Embeddable; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/join/JoinTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/join/JoinTest.java index 519f3b80db7f..0658ccb1eaa6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/join/JoinTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/join/JoinTest.java @@ -9,256 +9,250 @@ import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.JoinType; import jakarta.persistence.criteria.Root; -import java.util.ArrayList; -import java.util.Date; -import java.util.Locale; - -import org.hibernate.query.Query; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.boot.MetadataBuilder; import org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.exception.ConstraintViolationException; import org.hibernate.mapping.Join; +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.SettingProvider; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Date; +import java.util.Locale; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Emmanuel Bernard */ -public class JoinTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + Life.class, + Death.class, + Cat.class, + Dog.class, + A.class, + B.class, + C.class, + SysGroupsOrm.class, + SysUserOrm.class} +) +@SessionFactory +@ServiceRegistry( + settingProviders = @SettingProvider(settingName = AvailableSettings.IMPLICIT_NAMING_STRATEGY, + provider = JoinTest.NamingStrategyProvider.class) +) +public class JoinTest { + + public static class NamingStrategyProvider implements SettingProvider.Provider { + + @Override + public String getSetting() { + return ImplicitNamingStrategyLegacyJpaImpl.INSTANCE.getClass().getName(); + } + } + + @AfterEach + public void cleanup(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); + } + @Test - public void testDefaultValue() { - Join join = metadata().getEntityBinding( Life.class.getName() ).getJoinClosure().get( 0 ); - assertEquals( "ExtendedLife", join.getTable().getName() ); + public void testDefaultValue(SessionFactoryScope scope) { + Join join = scope.getMetadataImplementor().getEntityBinding( Life.class.getName() ).getJoinClosure().get( 0 ); + assertThat( join.getTable().getName() ).isEqualTo( "ExtendedLife" ); org.hibernate.mapping.Column owner = new org.hibernate.mapping.Column(); owner.setName( "LIFE_ID" ); - assertTrue( join.getTable().getPrimaryKey().containsColumn( owner ) ); - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Life life = new Life(); - life.duration = 15; - life.fullDescription = "Long long description"; - s.persist( life ); - tx.commit(); - s.close(); + assertThat( join.getTable().getPrimaryKey().containsColumn( owner ) ).isTrue(); + scope.inTransaction( + session -> { + Life life = new Life(); + life.duration = 15; + life.fullDescription = "Long long description"; + session.persist( life ); + } + ); - s = openSession(); - tx = s.beginTransaction(); - Query q = s.createQuery( "from " + Life.class.getName() ); - life = (Life) q.uniqueResult(); - assertEquals( "Long long description", life.fullDescription ); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + Life life = session.createQuery( "from " + Life.class.getName(), Life.class ).uniqueResult(); + assertThat( life.fullDescription ).isEqualTo( "Long long description" ); + } + ); } @Test - public void testCompositePK() { - Join join = metadata().getEntityBinding( Dog.class.getName() ).getJoinClosure().get( 0 ); - assertEquals( "DogThoroughbred", join.getTable().getName() ); + public void testCompositePK(SessionFactoryScope scope) { + Join join = scope.getMetadataImplementor().getEntityBinding( Dog.class.getName() ).getJoinClosure().get( 0 ); + assertThat( join.getTable().getName() ).isEqualTo( "DogThoroughbred" ); org.hibernate.mapping.Column owner = new org.hibernate.mapping.Column(); owner.setName( "OWNER_NAME" ); - assertTrue( join.getTable().getPrimaryKey().containsColumn( owner ) ); - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Dog dog = new Dog(); - DogPk id = new DogPk(); - id.name = "Thalie"; - id.ownerName = "Martine"; - dog.id = id; - dog.weight = 30; - dog.thoroughbredName = "Colley"; - s.persist( dog ); - tx.commit(); - s.close(); + assertThat( join.getTable().getPrimaryKey().containsColumn( owner ) ).isTrue(); - s = openSession(); - tx = s.beginTransaction(); - Query q = s.createQuery( "from Dog" ); - dog = (Dog) q.uniqueResult(); - assertEquals( "Colley", dog.thoroughbredName ); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + Dog dog = new Dog(); + DogPk id = new DogPk(); + id.name = "Thalie"; + id.ownerName = "Martine"; + dog.id = id; + dog.weight = 30; + dog.thoroughbredName = "Colley"; + session.persist( dog ); + } + ); + + scope.inTransaction( + session -> { + Dog dog = session.createQuery( "from Dog", Dog.class ).uniqueResult(); + assertThat( dog.thoroughbredName ).isEqualTo( "Colley" ); + } + ); } @Test - public void testExplicitValue() { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Death death = new Death(); - death.date = new Date(); - death.howDoesItHappen = "Well, haven't seen it"; - s.persist( death ); - tx.commit(); - s.close(); + public void testExplicitValue(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Death death = new Death(); + death.date = new Date(); + death.howDoesItHappen = "Well, haven't seen it"; + session.persist( death ); + } + ); - s = openSession(); - tx = s.beginTransaction(); - Query q = s.createQuery( "from " + Death.class.getName() ); - death = (Death) q.uniqueResult(); - assertEquals( "Well, haven't seen it", death.howDoesItHappen ); - s.remove( death ); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + Death death = session.createQuery( "from " + Death.class.getName(), Death.class ).uniqueResult(); + assertThat( death.howDoesItHappen ).isEqualTo( "Well, haven't seen it" ); + session.remove( death ); + } + ); } @Test - public void testManyToOne() throws Exception { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Life life = new Life(); - Cat cat = new Cat(); - cat.setName( "kitty" ); - cat.setStoryPart2( "and the story continues" ); - life.duration = 15; - life.fullDescription = "Long long description"; - life.owner = cat; - s.persist( life ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); + public void testManyToOne(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Life life = new Life(); + Cat cat = new Cat(); + cat.setName( "kitty" ); + cat.setStoryPart2( "and the story continues" ); + life.duration = 15; + life.fullDescription = "Long long description"; + life.owner = cat; + session.persist( life ); + } + ); - CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); - CriteriaQuery criteria = criteriaBuilder.createQuery( Life.class ); - Root root = criteria.from( Life.class ); - jakarta.persistence.criteria.Join owner = root.join( "owner", JoinType.INNER ); - criteria.where( criteriaBuilder.equal( owner.get( "name" ), "kitty" ) ); - life = s.createQuery( criteria ).uniqueResult(); + scope.inTransaction( + session -> { + CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); + CriteriaQuery criteria = criteriaBuilder.createQuery( Life.class ); + Root root = criteria.from( Life.class ); + jakarta.persistence.criteria.Join owner = root.join( "owner", JoinType.INNER ); + criteria.where( criteriaBuilder.equal( owner.get( "name" ), "kitty" ) ); + Life life = session.createQuery( criteria ).uniqueResult(); // Criteria crit = s.createCriteria( Life.class ); // crit.createCriteria( "owner" ).add( Restrictions.eq( "name", "kitty" ) ); // life = (Life) crit.uniqueResult(); - assertEquals( "Long long description", life.fullDescription ); - s.remove( life.owner ); - s.remove( life ); - tx.commit(); - s.close(); + assertThat( life.fullDescription ).isEqualTo( "Long long description" ); + session.remove( life.owner ); + session.remove( life ); + } + ); } @Test - public void testReferenceColumnWithBacktics() { - Session s=openSession(); - s.beginTransaction(); - SysGroupsOrm g=new SysGroupsOrm(); - SysUserOrm u=new SysUserOrm(); - u.setGroups( new ArrayList<>() ); - u.getGroups().add( g ); - s.persist( g ); - s.persist( u ); - s.getTransaction().commit(); - s.close(); + public void testReferenceColumnWithBacktics(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + SysGroupsOrm g = new SysGroupsOrm(); + SysUserOrm u = new SysUserOrm(); + u.setGroups( new ArrayList<>() ); + u.getGroups().add( g ); + session.persist( g ); + session.persist( u ); + } + ); } @Test - public void testUniqueConstaintOnSecondaryTable() { + public void testUniqueConstaintOnSecondaryTable(SessionFactoryScope scope) { Cat cat = new Cat(); cat.setStoryPart2( "My long story" ); Cat cat2 = new Cat(); cat2.setStoryPart2( "My long story" ); - Session s = openSession(); - Transaction tx = s.beginTransaction(); - try { - s.persist( cat ); - s.persist( cat2 ); - tx.commit(); - fail( "unique constraints violation on secondary table" ); - } - catch (PersistenceException e) { - try { - assertTyping( ConstraintViolationException.class, e ); - //success - } - finally { - tx.rollback(); - } - } - finally { - s.close(); - } + PersistenceException exception = assertThrows( PersistenceException.class, () -> scope.inTransaction( + session -> { + session.persist( cat ); + session.persist( cat2 ); + } + ), + "Expected unique constraints violation on secondary table" + ); + + assertThat( exception ).isInstanceOf( ConstraintViolationException.class ); + } @Test - public void testFetchModeOnSecondaryTable() { + public void testFetchModeOnSecondaryTable(SessionFactoryScope scope) { Cat cat = new Cat(); cat.setStoryPart2( "My long story" ); - Session s = openSession(); - Transaction tx = s.beginTransaction(); - - s.persist( cat ); - s.flush(); - s.clear(); + scope.inTransaction( + session -> { + session.persist( cat ); + session.flush(); + session.clear(); - s.get( Cat.class, cat.getId() ); - //Find a way to test it, I need to define the secondary table on a subclass - - tx.rollback(); - s.close(); + session.find( Cat.class, cat.getId() ); + //Find a way to test it, I need to define the secondary table on a subclass + } + ); } @Test - public void testCustomSQL() { + public void testCustomSQL(SessionFactoryScope scope) { Cat cat = new Cat(); String storyPart2 = "My long story"; cat.setStoryPart2( storyPart2 ); - Session s = openSession(); - Transaction tx = s.beginTransaction(); - - s.persist( cat ); - s.flush(); - s.clear(); - Cat c = s.get( Cat.class, cat.getId() ); - assertEquals( storyPart2.toUpperCase(Locale.ROOT), c.getStoryPart2() ); + scope.inTransaction( + session -> { + session.persist( cat ); + session.flush(); + session.clear(); - tx.rollback(); - s.close(); + Cat c = session.find( Cat.class, cat.getId() ); + assertThat( c.getStoryPart2() ).isEqualTo( storyPart2.toUpperCase( Locale.ROOT ) ); + } + ); } @Test - public void testMappedSuperclassAndSecondaryTable() { - Session s = openSession( ); - s.getTransaction().begin(); - C c = new C(); - c.setAge( 12 ); - c.setCreateDate( new Date() ); - c.setName( "Bob" ); - s.persist( c ); - s.flush(); - s.clear(); - c= s.get( C.class, c.getId() ); - assertNotNull( c.getCreateDate() ); - assertNotNull( c.getName() ); - s.getTransaction().rollback(); - s.close(); - } - - @Override - protected void configureMetadataBuilder(MetadataBuilder metadataBuilder) { - super.configureMetadataBuilder( metadataBuilder ); - metadataBuilder.applyImplicitNamingStrategy( ImplicitNamingStrategyLegacyJpaImpl.INSTANCE ); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - Life.class, - Death.class, - Cat.class, - Dog.class, - A.class, - B.class, - C.class, - SysGroupsOrm.class, - SysUserOrm.class - }; + public void testMappedSuperclassAndSecondaryTable(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + C c = new C(); + c.setAge( 12 ); + c.setCreateDate( new Date() ); + c.setName( "Bob" ); + session.persist( c ); + session.flush(); + session.clear(); + c = session.find( C.class, c.getId() ); + assertThat( c.getCreateDate() ).isNotNull(); + assertThat( c.getName() ).isNotNull(); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/join/Life.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/join/Life.java index 79369b395f46..7ac37bbef580 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/join/Life.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/join/Life.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.join; + import java.io.Serializable; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/join/SysGroupsOrm.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/join/SysGroupsOrm.java index c3386e147751..137bb2de26d2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/join/SysGroupsOrm.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/join/SysGroupsOrm.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.join; + import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/join/SysUserOrm.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/join/SysUserOrm.java index ad85d25e2f23..8645ba69a64c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/join/SysUserOrm.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/join/SysUserOrm.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.join; + import java.util.Collection; import jakarta.persistence.Column; import jakarta.persistence.Entity; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/loader/LoaderWithInvalidQueryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/loader/LoaderWithInvalidQueryTest.java index 583745419327..d48e71c0dbbe 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/loader/LoaderWithInvalidQueryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/loader/LoaderWithInvalidQueryTest.java @@ -8,60 +8,59 @@ import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; - import org.hibernate.HibernateException; import org.hibernate.annotations.HQLSelect; import org.hibernate.annotations.NamedQuery; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; import org.hibernate.testing.util.ExceptionUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Fail.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * @author Vlad Mihalcea */ -public class LoaderWithInvalidQueryTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class - }; - } - - @Override - public void buildEntityManagerFactory() { - try { - super.buildEntityManagerFactory(); - } - catch (Exception expected) { - HibernateException rootCause = (HibernateException) ExceptionUtil.rootCause( expected ); - Throwable[] suppressed = rootCause.getSuppressed(); - assertEquals( 2, suppressed.length ); - assertTrue( ExceptionUtil.rootCause( suppressed[0] ).getMessage().contains( "Could not resolve root entity '_Person'" ) ); - assertTrue( ExceptionUtil.rootCause( suppressed[1] ).getMessage().contains( "Could not resolve attribute 'valid'" ) ); +@Jpa( + annotatedClasses = { + LoaderWithInvalidQueryTest.Person.class } - } +) +public class LoaderWithInvalidQueryTest { + @Test - public void test() { + public void test(EntityManagerFactoryScope scope) { + Exception expected = assertThrows( Exception.class, () -> scope.inTransaction( + session -> { + fail("Exception expected during the build of the EntityManagerFactory "); + } + ) ); + + HibernateException rootCause = (HibernateException) ExceptionUtil.rootCause( expected ); + Throwable[] suppressed = rootCause.getSuppressed(); + assertThat( suppressed.length ).isEqualTo( 2 ); + assertThat( ExceptionUtil.rootCause( suppressed[0] ).getMessage() ) + .contains( "Could not resolve root entity '_Person'" ); + assertThat( ExceptionUtil.rootCause( suppressed[1] ).getMessage() ) + .contains( "Could not resolve attribute 'valid'" ); } @Entity(name = "Person") @HQLSelect( - query = "SELECT p " + - "FROM Person p " + - "WHERE p.id = ?1 and p.valid = true" + query = "SELECT p " + + "FROM Person p " + + "WHERE p.id = ?1 and p.valid = true" ) @NamedQuery( - name = "another_invalid_sql", - query = "SELECT p " + - "FROM _Person p " + - "WHERE p.id = ?1" + name = "another_invalid_sql", + query = "SELECT p " + + "FROM _Person p " + + "WHERE p.id = ?1" ) public static class Person { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/AbstractLobTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/AbstractLobTest.java index 06de2db391a9..d50b824fe9e4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/AbstractLobTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/AbstractLobTest.java @@ -4,22 +4,20 @@ */ package org.hibernate.orm.test.annotations.lob; -import org.hibernate.dialect.*; -import org.junit.Test; -import org.hibernate.testing.SkipForDialect; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.hibernate.dialect.SybaseDialect; +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.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.assertj.core.api.Assertions.assertThat; /** * @author Gail Badner */ -public abstract class AbstractLobTest - extends BaseCoreFunctionalTestCase { +@SessionFactory +public abstract class AbstractLobTest { protected abstract Class getBookClass(); @@ -41,88 +39,89 @@ protected C createCompiledCode() { return getCompiledCodeClass().newInstance(); } catch (Exception ex) { - throw new RuntimeException( "Could not create an instance of type " + getCompiledCodeClass().getName(), ex ); + throw new RuntimeException( "Could not create an instance of type " + getCompiledCodeClass().getName(), + ex ); } } protected abstract Integer getId(C compiledCode); @Test - public void testSerializableToBlob() throws Exception { + public void testSerializableToBlob(SessionFactoryScope scope) { B book = createBook(); Editor editor = new Editor(); editor.setName( "O'Reilly" ); book.setEditor( editor ); - book.setCode2( new char[] { 'r' } ); + book.setCode2( new char[] {'r'} ); - doInHibernate( this::sessionFactory, session -> { - session.persist( book ); - } ); + scope.inTransaction( session -> + session.persist( book ) + ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { B loadedBook = getBookClass().cast( session.get( getBookClass(), getId( book ) ) ); - assertNotNull( loadedBook.getEditor() ); - assertEquals( book.getEditor().getName(), loadedBook.getEditor().getName() ); + assertThat( loadedBook.getEditor() ).isNotNull(); + assertThat( loadedBook.getEditor().getName() ).isEqualTo( book.getEditor().getName() ); loadedBook.setEditor( null ); } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { B loadedBook = getBookClass().cast( session.get( getBookClass(), getId( book ) ) ); - assertNull( loadedBook.getEditor() ); + assertThat( loadedBook.getEditor() ).isNull(); } ); } @Test - public void testClob() throws Exception { + public void testClob(SessionFactoryScope scope) { B book = createBook(); book.setShortDescription( "Hibernate Bible" ); book.setFullText( "Hibernate in Action aims to..." ); - book.setCode( new Character[] { 'a', 'b', 'c' } ); - book.setCode2( new char[] { 'a', 'b', 'c' } ); + book.setCode( new Character[] {'a', 'b', 'c'} ); + book.setCode2( new char[] {'a', 'b', 'c'} ); - doInHibernate( this::sessionFactory, session -> { - session.persist( book ); - } ); + scope.inTransaction( session -> + session.persist( book ) + ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { B b2 = getBookClass().cast( session.get( getBookClass(), getId( book ) ) ); - assertNotNull( b2 ); - assertEquals( b2.getFullText(), book.getFullText() ); - assertEquals( b2.getCode()[1].charValue(), book.getCode()[1].charValue() ); - assertEquals( b2.getCode2()[2], book.getCode2()[2] ); + assertThat( b2 ).isNotNull(); + assertThat( b2.getFullText() ).isEqualTo( book.getFullText() ); + assertThat( b2.getCode()[1].charValue() ).isEqualTo( book.getCode()[1].charValue() ); + assertThat( b2.getCode2()[2] ).isEqualTo( book.getCode2()[2] ); } ); } @Test - public void testBlob() throws Exception { + public void testBlob(SessionFactoryScope scope) { C cc = createCompiledCode(); Byte[] header = new Byte[2]; - header[0] = new Byte( ( byte ) 3 ); - header[1] = new Byte( ( byte ) 0 ); + header[0] = 3; + header[1] = 0; cc.setHeader( header ); int codeSize = 5; byte[] full = new byte[codeSize]; for ( int i = 0; i < codeSize; i++ ) { - full[i] = ( byte ) ( 1 + i ); + full[i] = (byte) (1 + i); } cc.setFullCode( full ); - doInHibernate( this::sessionFactory, session -> { - session.persist( cc ); - } ); + scope.inTransaction( session -> + session.persist( cc ) + ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { C recompiled = getCompiledCodeClass().cast( session.get( getCompiledCodeClass(), getId( cc ) ) ); - assertEquals( recompiled.getHeader()[1], cc.getHeader()[1] ); - assertEquals( recompiled.getFullCode()[codeSize - 1], cc.getFullCode()[codeSize - 1] ); + assertThat( recompiled.getHeader()[1] ).isEqualTo( cc.getHeader()[1] ); + assertThat( recompiled.getFullCode()[codeSize - 1] ).isEqualTo( cc.getFullCode()[codeSize - 1] ); } ); } @Test - @SkipForDialect( SybaseDialect.class ) - public void testBinary() throws Exception { + @SkipForDialect(dialectClass = SybaseDialect.class, matchSubTypes = true) + public void testBinary(SessionFactoryScope scope) { C cc = createCompiledCode(); byte[] metadata = new byte[2]; @@ -130,13 +129,13 @@ public void testBinary() throws Exception { metadata[1] = ( byte ) 0; cc.setMetadata( metadata ); - doInHibernate( this::sessionFactory, session -> { - session.persist( cc ); - } ); + scope.inTransaction( session -> + session.persist( cc ) + ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { C recompiled = getCompiledCodeClass().cast( session.get( getCompiledCodeClass(), getId( cc ) ) ); - assertEquals( recompiled.getMetadata()[1], cc.getMetadata()[1] ); + assertThat( recompiled.getMetadata()[1] ).isEqualTo( cc.getMetadata()[1] ); } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/Dog.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/Dog.java index 2ab1660e7821..eb64a6aefdf7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/Dog.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/Dog.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.lob; + import java.io.Serializable; public class Dog implements Serializable { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/Editor.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/Editor.java index 2913ccee9455..76955bf81464 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/Editor.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/Editor.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.lob; + import java.io.Serializable; /** diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/ImageHolder.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/ImageHolder.java index 2caf2d42b686..1711ac6da3aa 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/ImageHolder.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/ImageHolder.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.lob; + import java.sql.Types; import org.hibernate.annotations.JdbcTypeCode; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/ImageTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/ImageTest.java index 411c9e132b8f..f5de28da1c83 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/ImageTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/ImageTest.java @@ -4,20 +4,23 @@ */ package org.hibernate.orm.test.annotations.lob; -import java.util.Arrays; - -import org.hibernate.Session; import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; import org.hibernate.dialect.SQLServerDialect; import org.hibernate.dialect.SybaseDialect; +import org.hibernate.testing.orm.junit.DomainModel; +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.SettingProvider; import org.hibernate.type.WrapperArrayHandling; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.fail; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Assert; -import org.junit.Test; -import junit.framework.AssertionFailedError; /** * Tests eager materialization and mutation of data mapped by @@ -27,88 +30,102 @@ */ @RequiresDialect(SQLServerDialect.class) @RequiresDialect(SybaseDialect.class) -public class ImageTest extends BaseCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + ImageHolder.class + }, + annotatedPackageNames = "org.hibernate.orm.test.annotations.lob" +) +@SessionFactory +@ServiceRegistry( + settingProviders = @SettingProvider( + settingName = AvailableSettings.WRAPPER_ARRAY_HANDLING, + provider = ImageTest.WrapperArrayHandlingProvider.class) +) +public class ImageTest { private static final int ARRAY_SIZE = 10000; - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - configuration.setProperty( AvailableSettings.WRAPPER_ARRAY_HANDLING, WrapperArrayHandling.ALLOW ); + public static class WrapperArrayHandlingProvider implements SettingProvider.Provider { + @Override + public WrapperArrayHandling getSetting() { + return WrapperArrayHandling.ALLOW; + } } @Test - public void testBoundedLongByteArrayAccess() { - byte[] original = buildRecursively(ARRAY_SIZE, true); - byte[] changed = buildRecursively(ARRAY_SIZE, false); - - Session s = openSession(); - s.beginTransaction(); - ImageHolder entity = new ImageHolder(); - s.persist(entity); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - entity = (ImageHolder) s.get(ImageHolder.class, entity.getId()); - Assert.assertNull( entity.getLongByteArray() ); - Assert.assertNull( entity.getDog() ); - Assert.assertNull( entity.getPicByteArray() ); - entity.setLongByteArray(original); + public void testBoundedLongByteArrayAccess(SessionFactoryScope scope) { + byte[] original = buildRecursively( ARRAY_SIZE, true ); + byte[] changed = buildRecursively( ARRAY_SIZE, false ); + + ImageHolder e = new ImageHolder(); + scope.inTransaction( + session -> + session.persist( e ) + ); + Dog dog = new Dog(); - dog.setName("rabbit"); - entity.setDog(dog); - entity.setPicByteArray(wrapPrimitive(original)); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - entity = (ImageHolder) s.get(ImageHolder.class, entity.getId()); - Assert.assertEquals( ARRAY_SIZE, entity.getLongByteArray().length ); - assertEquals(original, entity.getLongByteArray()); - Assert.assertEquals( ARRAY_SIZE, entity.getPicByteArray().length ); - assertEquals(original, unwrapNonPrimitive(entity.getPicByteArray())); - Assert.assertNotNull( entity.getDog() ); - Assert.assertEquals( dog.getName(), entity.getDog().getName() ); - entity.setLongByteArray(changed); - entity.setPicByteArray(wrapPrimitive(changed)); - dog.setName("papa"); - entity.setDog(dog); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - entity = (ImageHolder) s.get(ImageHolder.class, entity.getId()); - Assert.assertEquals( ARRAY_SIZE, entity.getLongByteArray().length ); - assertEquals(changed, entity.getLongByteArray()); - Assert.assertEquals( ARRAY_SIZE, entity.getPicByteArray().length ); - assertEquals(changed, unwrapNonPrimitive(entity.getPicByteArray())); - Assert.assertNotNull( entity.getDog() ); - Assert.assertEquals( dog.getName(), entity.getDog().getName() ); - entity.setLongByteArray(null); - entity.setPicByteArray(null); - entity.setDog(null); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - entity = s.get( ImageHolder.class, entity.getId()); - Assert.assertNull( entity.getLongByteArray() ); - Assert.assertNull( entity.getDog() ); - Assert.assertNull( entity.getPicByteArray() ); - s.remove(entity); - s.getTransaction().commit(); - s.close(); + scope.inTransaction( + session -> { + ImageHolder entity = session.get( ImageHolder.class, e.getId() ); + assertThat( entity.getLongByteArray() ).isNull(); + assertThat( entity.getDog() ).isNull(); + assertThat( entity.getPicByteArray() ).isNull(); + entity.setLongByteArray( original ); + + dog.setName( "rabbit" ); + entity.setDog( dog ); + entity.setPicByteArray( wrapPrimitive( original ) ); + } + ); + + scope.inTransaction( + session -> { + ImageHolder entity = session.find( ImageHolder.class, e.getId() ); + assertThat( entity.getLongByteArray().length ).isEqualTo( ARRAY_SIZE ); + assertEquals( original, entity.getLongByteArray() ); + assertThat( entity.getPicByteArray().length ).isEqualTo( ARRAY_SIZE ); + assertEquals( original, unwrapNonPrimitive( entity.getPicByteArray() ) ); + assertThat( entity.getDog() ).isNotNull(); + assertThat( entity.getDog().getName() ).isEqualTo( dog.getName() ); + entity.setLongByteArray( changed ); + entity.setPicByteArray( wrapPrimitive( changed ) ); + dog.setName( "papa" ); + entity.setDog( dog ); + } + ); + + scope.inTransaction( + session -> { + ImageHolder entity = + session.find( ImageHolder.class, e.getId() ); + assertThat( entity.getLongByteArray().length ).isEqualTo( ARRAY_SIZE ); + assertEquals( changed, entity.getLongByteArray() ); + assertThat( entity.getPicByteArray().length ).isEqualTo( ARRAY_SIZE ); + assertEquals( changed, unwrapNonPrimitive( entity.getPicByteArray() ) ); + assertThat( entity.getDog() ).isNotNull(); + assertThat( entity.getDog().getName() ).isEqualTo( dog.getName() ); + entity.setLongByteArray( null ); + entity.setPicByteArray( null ); + entity.setDog( null ); + } + ); + + scope.inTransaction( + session -> { + ImageHolder entity = session.find( ImageHolder.class, e.getId() ); + assertThat( entity.getLongByteArray() ).isNull(); + assertThat( entity.getDog() ).isNull(); + assertThat( entity.getPicByteArray() ).isNull(); + session.remove( entity ); + } + ); } private Byte[] wrapPrimitive(byte[] bytes) { int length = bytes.length; Byte[] result = new Byte[length]; - for (int index = 0; index < length; index++) { - result[index] = Byte.valueOf( bytes[index] ); + for ( int index = 0; index < length; index++ ) { + result[index] = bytes[index]; } return result; } @@ -116,17 +133,17 @@ private Byte[] wrapPrimitive(byte[] bytes) { private byte[] unwrapNonPrimitive(Byte[] bytes) { int length = bytes.length; byte[] result = new byte[length]; - for (int i = 0; i < length; i++) { - result[i] = bytes[i].byteValue(); + for ( int i = 0; i < length; i++ ) { + result[i] = bytes[i]; } return result; } private byte[] buildRecursively(int size, boolean on) { byte[] data = new byte[size]; - data[0] = mask(on); - for (int i = 0; i < size; i++) { - data[i] = mask(on); + data[0] = mask( on ); + for ( int i = 0; i < size; i++ ) { + data[i] = mask( on ); on = !on; } return data; @@ -138,18 +155,8 @@ private byte mask(boolean on) { public static void assertEquals(byte[] val1, byte[] val2) { if ( !Arrays.equals( val1, val2 ) ) { - throw new AssertionFailedError("byte arrays did not match"); + fail( "byte arrays did not match" ); } } - @Override - protected String[] getAnnotatedPackages() { - return new String[] { "org.hibernate.orm.test.annotations.lob" }; - } - - @Override - public Class[] getAnnotatedClasses() { - return new Class[] { ImageHolder.class }; - } - } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/LobTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/LobTest.java index 9aa9038fe90b..0c7867a8685a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/LobTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/LobTest.java @@ -4,13 +4,21 @@ */ package org.hibernate.orm.test.annotations.lob; -import org.hibernate.testing.DialectChecks; -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.RequiresDialectFeature; /** * @author Emmanuel Bernard */ -@RequiresDialectFeature(DialectChecks.SupportsExpectedLobUsagePattern.class) +@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsExpectedLobUsagePattern.class) +@DomainModel( + annotatedClasses = { + Book.class, + CompiledCode.class + } +) public class LobTest extends AbstractLobTest { @Override protected Class getBookClass() { @@ -32,11 +40,4 @@ protected Integer getId(CompiledCode compiledCode) { return compiledCode.getId(); } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Book.class, - CompiledCode.class - }; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/MaterializedBlobTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/MaterializedBlobTest.java index e517a10b36e7..a206d3772482 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/MaterializedBlobTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/MaterializedBlobTest.java @@ -4,66 +4,65 @@ */ package org.hibernate.orm.test.annotations.lob; -import java.util.Arrays; - -import org.hibernate.Session; import org.hibernate.dialect.CockroachDialect; import org.hibernate.metamodel.mapping.AttributeMapping; import org.hibernate.metamodel.mapping.BasicValuedModelPart; import org.hibernate.metamodel.mapping.JdbcMapping; import org.hibernate.persister.entity.EntityPersister; +import org.hibernate.testing.orm.junit.DialectFeatureChecks; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.SkipForDialect; import org.hibernate.type.descriptor.java.PrimitiveByteArrayJavaType; import org.hibernate.type.descriptor.jdbc.BlobJdbcType; - -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; -import org.hibernate.testing.SkipForDialect; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertTrue; /** * @author Steve Ebersole */ -@RequiresDialectFeature(DialectChecks.SupportsExpectedLobUsagePattern.class) -public class MaterializedBlobTest extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { MaterializedBlobEntity.class }; - } +@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsExpectedLobUsagePattern.class) +@DomainModel( + annotatedClasses = { + MaterializedBlobEntity.class + } +) +@SessionFactory +public class MaterializedBlobTest { @Test - @SkipForDialect(value = CockroachDialect.class, comment = "Blob in CockroachDB is same as a varbinary, to assertions will fail") - public void testTypeSelection() { - final EntityPersister entityDescriptor = sessionFactory().getRuntimeMetamodels() + @SkipForDialect(dialectClass = CockroachDialect.class, + reason = "Blob in CockroachDB is same as a varbinary, to assertions will fail") + public void testTypeSelection(SessionFactoryScope scope) { + final EntityPersister entityDescriptor = scope.getSessionFactory().getRuntimeMetamodels() .getMappingMetamodel() .getEntityDescriptor( MaterializedBlobEntity.class.getName() ); final AttributeMapping theBytesAttr = entityDescriptor.findAttributeMapping( "theBytes" ); assertThat( theBytesAttr ).isInstanceOf( BasicValuedModelPart.class ); - final JdbcMapping mapping = ( (BasicValuedModelPart) theBytesAttr ).getJdbcMapping(); - assertTrue( mapping.getJavaTypeDescriptor() instanceof PrimitiveByteArrayJavaType ); - assertTrue( mapping.getJdbcType() instanceof BlobJdbcType ); + final JdbcMapping mapping = ((BasicValuedModelPart) theBytesAttr).getJdbcMapping(); + assertThat( mapping.getJavaTypeDescriptor() ).isInstanceOf( PrimitiveByteArrayJavaType.class ); + assertThat( mapping.getJdbcType() ).isInstanceOf( BlobJdbcType.class ); } @Test - public void testSaving() { + public void testSaving(SessionFactoryScope scope) { byte[] testData = "test data".getBytes(); - Session session = openSession(); - session.beginTransaction(); - MaterializedBlobEntity entity = new MaterializedBlobEntity( "test", testData ); - session.persist( entity ); - session.getTransaction().commit(); - session.close(); + MaterializedBlobEntity e = new MaterializedBlobEntity( "test", testData ); + scope.inTransaction( + session -> + session.persist( e ) + ); - session = openSession(); - session.beginTransaction(); - entity = session.get( MaterializedBlobEntity.class, entity.getId() ); - assertTrue( Arrays.equals( testData, entity.getTheBytes() ) ); - session.remove( entity ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( + session -> { + MaterializedBlobEntity entity = session.find( MaterializedBlobEntity.class, e.getId() ); + assertThat( entity.getTheBytes() ).isEqualTo( testData ); + session.remove( entity ); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/PrimitiveCharacterArrayTextType.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/PrimitiveCharacterArrayTextType.java index f567f9cbf258..f66742af8751 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/PrimitiveCharacterArrayTextType.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/PrimitiveCharacterArrayTextType.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.lob; + import org.hibernate.type.AbstractSingleColumnStandardBasicType; import org.hibernate.type.descriptor.java.PrimitiveCharacterArrayJavaType; import org.hibernate.type.descriptor.jdbc.LongVarcharJdbcType; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/SerializableToImageType.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/SerializableToImageType.java index 9e0ee5fbf1f8..0558be2206d1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/SerializableToImageType.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/SerializableToImageType.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.lob; + import java.io.Serializable; import org.hibernate.type.AbstractSingleColumnStandardBasicType; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/TextTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/TextTest.java index 1e334e578ccb..809cd455b7be 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/TextTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/TextTest.java @@ -4,19 +4,16 @@ */ package org.hibernate.orm.test.annotations.lob; -import java.util.Arrays; - -import org.hibernate.Session; import org.hibernate.dialect.SQLServerDialect; import org.hibernate.dialect.SybaseDialect; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Assert; -import org.junit.Test; -import junit.framework.AssertionFailedError; +import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertNull; /** * Tests eager materialization and mutation of long strings. @@ -25,98 +22,91 @@ */ @RequiresDialect(SQLServerDialect.class) @RequiresDialect(SybaseDialect.class) -public class TextTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { LongStringHolder.class }; - } +@DomainModel( + annotatedPackageNames = "org.hibernate.orm.test.annotations.lob", + annotatedClasses = { + LongStringHolder.class + } +) +@SessionFactory +public class TextTest { private static final int LONG_STRING_SIZE = 10000; @Test - public void testBoundedLongStringAccess() { - String original = buildRecursively(LONG_STRING_SIZE, 'x'); - String changed = buildRecursively(LONG_STRING_SIZE, 'y'); - - Session s = openSession(); - s.beginTransaction(); - LongStringHolder entity = new LongStringHolder(); - s.persist(entity); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - entity = (LongStringHolder) s.get(LongStringHolder.class, entity - .getId()); - assertNull(entity.getLongString()); - assertNull(entity.getName()); - assertNull(entity.getWhatEver()); - entity.setLongString(original); - entity.setName(original.toCharArray()); - entity.setWhatEver(wrapPrimitive(original.toCharArray())); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - entity = (LongStringHolder) s.get(LongStringHolder.class, entity - .getId()); - Assert.assertEquals( LONG_STRING_SIZE, entity.getLongString().length() ); - Assert.assertEquals( original, entity.getLongString() ); - Assert.assertNotNull( entity.getName() ); - Assert.assertEquals( LONG_STRING_SIZE, entity.getName().length ); - assertEquals( original.toCharArray(), entity.getName() ); - Assert.assertNotNull( entity.getWhatEver() ); - Assert.assertEquals( LONG_STRING_SIZE, entity.getWhatEver().length ); - assertEquals( original.toCharArray(), unwrapNonPrimitive( entity.getWhatEver() ) ); - entity.setLongString(changed); - entity.setName(changed.toCharArray()); - entity.setWhatEver(wrapPrimitive(changed.toCharArray())); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - entity = (LongStringHolder) s.get(LongStringHolder.class, entity - .getId()); - Assert.assertEquals( LONG_STRING_SIZE, entity.getLongString().length() ); - Assert.assertEquals( changed, entity.getLongString() ); - Assert.assertNotNull( entity.getName() ); - Assert.assertEquals( LONG_STRING_SIZE, entity.getName().length ); - assertEquals( changed.toCharArray(), entity.getName() ); - Assert.assertNotNull( entity.getWhatEver() ); - Assert.assertEquals( LONG_STRING_SIZE, entity.getWhatEver().length ); - assertEquals( changed.toCharArray(), unwrapNonPrimitive( entity.getWhatEver() ) ); - entity.setLongString(null); - entity.setName(null); - entity.setWhatEver(null); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - entity = (LongStringHolder) s.get(LongStringHolder.class, entity - .getId()); - assertNull(entity.getLongString()); - assertNull(entity.getName()); - assertNull(entity.getWhatEver()); - s.remove(entity); - s.getTransaction().commit(); - s.close(); + public void testBoundedLongStringAccess(SessionFactoryScope scope) { + String original = buildRecursively( LONG_STRING_SIZE, 'x' ); + String changed = buildRecursively( LONG_STRING_SIZE, 'y' ); + + LongStringHolder e = new LongStringHolder(); + scope.inTransaction( + session -> + session.persist( e ) + ); + + scope.inTransaction( + session -> { + LongStringHolder entity = session.find( LongStringHolder.class, e.getId() ); + assertThat( entity.getLongString() ).isNull(); + assertThat( entity.getName() ).isNull(); + assertThat( entity.getWhatEver() ).isNull(); + entity.setLongString( original ); + entity.setName( original.toCharArray() ); + entity.setWhatEver( wrapPrimitive( original.toCharArray() ) ); + } + ); + + + scope.inTransaction( + session -> { + LongStringHolder entity = session.find( LongStringHolder.class, e.getId() ); + assertThat( entity.getLongString().length() ).isEqualTo( LONG_STRING_SIZE ); + assertThat( entity.getLongString() ).isEqualTo( original ); + assertThat( entity.getName() ).isNotNull(); + assertThat( entity.getName().length ).isEqualTo( LONG_STRING_SIZE ); + assertThat( entity.getName() ).isEqualTo( original.toCharArray() ); + assertThat( entity.getWhatEver() ).isNotNull(); + assertThat( entity.getWhatEver().length ).isEqualTo( LONG_STRING_SIZE ); + assertThat( unwrapNonPrimitive( entity.getWhatEver() ) ).isEqualTo( original.toCharArray() ); + entity.setLongString( changed ); + entity.setName( changed.toCharArray() ); + entity.setWhatEver( wrapPrimitive( changed.toCharArray() ) ); + } + ); + + scope.inTransaction( + session -> { + LongStringHolder entity = session.find( LongStringHolder.class, e.getId() ); + assertThat( entity.getLongString().length() ).isEqualTo( LONG_STRING_SIZE ); + assertThat( entity.getLongString() ).isEqualTo( changed ); + assertThat( entity.getName() ).isNotNull(); + assertThat( entity.getName().length ).isEqualTo( LONG_STRING_SIZE ); + assertThat( entity.getName() ).isEqualTo( changed.toCharArray() ); + assertThat( entity.getWhatEver() ).isNotNull(); + assertThat( entity.getWhatEver().length ).isEqualTo( LONG_STRING_SIZE ); + assertThat( unwrapNonPrimitive( entity.getWhatEver() ) ).isEqualTo( changed.toCharArray() ); + entity.setLongString( null ); + entity.setName( null ); + entity.setWhatEver( null ); + } + ); + + scope.inTransaction( + session -> { + LongStringHolder entity = session.find( LongStringHolder.class, e.getId() ); + assertThat( entity.getLongString() ).isNull(); + assertThat( entity.getName() ).isNull(); + assertThat( entity.getWhatEver() ).isNull(); + session.remove( entity ); + } + ); } - public static void assertEquals(char[] val1, char[] val2) { - if ( !Arrays.equals( val1, val2 ) ) { - throw new AssertionFailedError("byte arrays did not match"); - } - } private String buildRecursively(int size, char baseChar) { StringBuilder buff = new StringBuilder(); - for (int i = 0; i < size; i++) { - buff.append(baseChar); + for ( int i = 0; i < size; i++ ) { + buff.append( baseChar ); } return buff.toString(); } @@ -124,8 +114,8 @@ private String buildRecursively(int size, char baseChar) { private Character[] wrapPrimitive(char[] bytes) { int length = bytes.length; Character[] result = new Character[length]; - for (int index = 0; index < length; index++) { - result[index] = Character.valueOf(bytes[index]); + for ( int index = 0; index < length; index++ ) { + result[index] = bytes[index]; } return result; } @@ -133,15 +123,9 @@ private Character[] wrapPrimitive(char[] bytes) { private char[] unwrapNonPrimitive(Character[] bytes) { int length = bytes.length; char[] result = new char[length]; - for (int i = 0; i < length; i++) { - result[i] = bytes[i].charValue(); + for ( int i = 0; i < length; i++ ) { + result[i] = bytes[i]; } return result; } - - @Override - protected String[] getAnnotatedPackages() { - return new String[] { "org.hibernate.orm.test.annotations.lob" }; - } - } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/VersionedBook.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/VersionedBook.java index 15250ed073e0..2ce7046ea1ca 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/VersionedBook.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/VersionedBook.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.lob; + import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/VersionedCompiledCode.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/VersionedCompiledCode.java index f0b1c38f953e..68a540e9bfbc 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/VersionedCompiledCode.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/VersionedCompiledCode.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.lob; + import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/VersionedLobTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/VersionedLobTest.java index dc7f52e86f8f..1bec365c2d08 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/VersionedLobTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/VersionedLobTest.java @@ -4,21 +4,27 @@ */ package org.hibernate.orm.test.annotations.lob; -import org.junit.Test; - -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.testing.DialectChecks; -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.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; /** * @author Gail Badner */ -@RequiresDialectFeature(DialectChecks.SupportsExpectedLobUsagePattern.class) +@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsExpectedLobUsagePattern.class) +@DomainModel( + annotatedClasses = { + VersionedBook.class, + VersionedCompiledCode.class + } +) public class VersionedLobTest extends AbstractLobTest { @Override protected Class getBookClass() { @@ -40,144 +46,136 @@ protected Integer getId(VersionedCompiledCode compiledCode) { return compiledCode.getId(); } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - VersionedBook.class, - VersionedCompiledCode.class - }; + @AfterEach + public void cleanup(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Test - public void testVersionUnchangedPrimitiveCharArray() throws Exception { + public void testVersionUnchangedPrimitiveCharArray(SessionFactoryScope scope) { VersionedBook book = createBook(); Editor editor = new Editor(); editor.setName( "O'Reilly" ); book.setEditor( editor ); - book.setCode2( new char[] { 'r' } ); - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - s.persist( book ); - tx.commit(); - s.close(); - s = openSession(); - tx = s.beginTransaction(); - VersionedBook loadedBook = getBookClass().cast( s.get( getBookClass(), getId( book ) ) ); - assertEquals( loadedBook.getVersion(), Integer.valueOf( 0 ) ); - s.flush(); - assertEquals( loadedBook.getVersion(), Integer.valueOf( 0 ) ); - s.remove( loadedBook ); - tx.commit(); - s.close(); + book.setCode2( new char[] {'r'} ); + + scope.inTransaction( + session -> + session.persist( book ) + ); + + scope.inTransaction( + session -> { + VersionedBook loadedBook = getBookClass().cast( session.find( getBookClass(), getId( book ) ) ); + assertThat( loadedBook.getVersion() ).isEqualTo( 0 ); + session.flush(); + assertThat( loadedBook.getVersion() ).isEqualTo( 0 ); + session.remove( loadedBook ); + } + ); } @Test - public void testVersionUnchangedCharArray() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); + public void testVersionUnchangedCharArray(SessionFactoryScope scope) { VersionedBook b = createBook(); - b.setShortDescription( "Hibernate Bible" ); - b.setCode( new Character[] { 'a', 'b', 'c' } ); - s.persist( b ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - VersionedBook b2 = getBookClass().cast( s.get( getBookClass(), getId( b ) ) ); - assertNotNull( b2 ); - assertEquals( b2.getCode()[1].charValue(), b.getCode()[1].charValue() ); - assertEquals( b2.getVersion(), Integer.valueOf( 0 ) ); - s.flush(); - assertEquals( b2.getVersion(), Integer.valueOf( 0 ) ); - s.remove( b2 ); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + b.setShortDescription( "Hibernate Bible" ); + b.setCode( new Character[] {'a', 'b', 'c'} ); + session.persist( b ); + } + ); + + scope.inTransaction( + session -> { + VersionedBook b2 = getBookClass().cast( session.find( getBookClass(), getId( b ) ) ); + assertThat( b2 ).isNotNull(); + assertThat( b2.getCode()[1].charValue() ).isEqualTo( b.getCode()[1].charValue() ); + assertThat( b2.getVersion() ).isEqualTo( 0 ); + session.flush(); + assertThat( b2.getVersion() ).isEqualTo( 0 ); + session.remove( b2 ); + } + ); } @Test - public void testVersionUnchangedString() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); + public void testVersionUnchangedString(SessionFactoryScope scope) { VersionedBook b = createBook(); - b.setShortDescription( "Hibernate Bible" ); - b.setFullText( "Hibernate in Action aims to..." ); - s.persist( b ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - VersionedBook b2 = getBookClass().cast( s.get( getBookClass(), getId( b ) ) ); - assertNotNull( b2 ); - assertEquals( b2.getFullText(), b.getFullText() ); - assertEquals( b2.getVersion(), Integer.valueOf( 0 ) ); - s.flush(); - assertEquals( b2.getVersion(), Integer.valueOf( 0 ) ); - s.remove( b2 ); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + b.setShortDescription( "Hibernate Bible" ); + b.setFullText( "Hibernate in Action aims to..." ); + session.persist( b ); + } + ); + + scope.inTransaction( + session -> { + VersionedBook b2 = getBookClass().cast( session.find( getBookClass(), getId( b ) ) ); + assertThat( b2 ).isNotNull(); + assertThat( b2.getFullText() ).isEqualTo( b.getFullText() ); + assertThat( b2.getVersion() ).isEqualTo( 0 ); + session.flush(); + assertThat( b2.getVersion() ).isEqualTo( 0 ); + session.remove( b2 ); + } + ); } @Test - @JiraKey( value = "HHH-5811") - public void testVersionUnchangedByteArray() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); + @JiraKey(value = "HHH-5811") + public void testVersionUnchangedByteArray(SessionFactoryScope scope) { VersionedCompiledCode cc = createCompiledCode(); - Byte[] header = new Byte[2]; - header[0] = new Byte( ( byte ) 3 ); - header[1] = new Byte( ( byte ) 0 ); - cc.setHeader( header ); - s.persist( cc ); - tx.commit(); - s.close(); - s = openSession(); - tx = s.beginTransaction(); - VersionedCompiledCode recompiled = getCompiledCodeClass().cast( s.get( getCompiledCodeClass(), getId( cc ) ) ); - assertEquals( recompiled.getHeader()[1], cc.getHeader()[1] ); - assertEquals( recompiled.getVersion(), Integer.valueOf( 0 ) ); - s.flush(); - assertEquals( recompiled.getVersion(), Integer.valueOf( 0 ) ); - s.remove( recompiled ); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + Byte[] header = new Byte[2]; + header[0] = 3; + header[1] = 0; + cc.setHeader( header ); + session.persist( cc ); + } + ); + + scope.inTransaction( + session -> { + VersionedCompiledCode recompiled = getCompiledCodeClass().cast( + session.find( getCompiledCodeClass(), getId( cc ) ) ); + assertThat( recompiled.getHeader()[1] ).isEqualTo( cc.getHeader()[1] ); + assertThat( recompiled.getVersion() ).isEqualTo( 0 ); + session.flush(); + assertThat( recompiled.getVersion() ).isEqualTo( 0 ); + session.remove( recompiled ); + } + ); } @Test - public void testVersionUnchangedPrimitiveByteArray() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); + public void testVersionUnchangedPrimitiveByteArray(SessionFactoryScope scope) { VersionedCompiledCode cc = createCompiledCode(); int codeSize = 5; - byte[] full = new byte[codeSize]; - for ( int i = 0; i < codeSize; i++ ) { - full[i] = ( byte ) ( 1 + i ); - } - cc.setFullCode( full ); - s.persist( cc ); - tx.commit(); - s.close(); - s = openSession(); - tx = s.beginTransaction(); - VersionedCompiledCode recompiled = getCompiledCodeClass().cast( s.get( getCompiledCodeClass(), getId( cc ) ) ); - assertEquals( recompiled.getFullCode()[codeSize - 1], cc.getFullCode()[codeSize - 1] ); - assertEquals( recompiled.getVersion(), Integer.valueOf( 0 ) ); - s.flush(); - assertEquals( recompiled.getVersion(), Integer.valueOf( 0 ) ); - s.remove( recompiled ); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + byte[] full = new byte[codeSize]; + for ( int i = 0; i < codeSize; i++ ) { + full[i] = (byte) (1 + i); + } + cc.setFullCode( full ); + session.persist( cc ); + } + ); + + scope.inTransaction( + session -> { + VersionedCompiledCode recompiled = getCompiledCodeClass().cast( + session.find( getCompiledCodeClass(), getId( cc ) ) ); + assertThat( recompiled.getFullCode()[codeSize - 1] ).isEqualTo( cc.getFullCode()[codeSize - 1] ); + assertThat( recompiled.getVersion() ).isEqualTo( 0 ); + session.flush(); + assertThat( recompiled.getVersion() ).isEqualTo( 0 ); + session.remove( recompiled ); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/WrappedImageType.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/WrappedImageType.java index dc6eba161951..48ed3aef266d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/WrappedImageType.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/WrappedImageType.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.lob; + import org.hibernate.type.AbstractSingleColumnStandardBasicType; import org.hibernate.type.descriptor.java.ByteArrayJavaType; import org.hibernate.type.descriptor.jdbc.LongVarbinaryJdbcType; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/hhh4635/LobTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/hhh4635/LobTest.java index ddead095defc..99565700176b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/hhh4635/LobTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/hhh4635/LobTest.java @@ -5,12 +5,14 @@ package org.hibernate.orm.test.annotations.lob.hhh4635; import org.hibernate.dialect.OracleDialect; -import org.hibernate.query.Query; -import org.hibernate.Session; -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.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; + +import java.util.logging.Logger; import static org.hibernate.Hibernate.getLobHelper; @@ -21,26 +23,28 @@ */ @RequiresDialect( OracleDialect.class ) @JiraKey( value = "HHH-4635" ) -public class LobTest extends BaseCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + LobTestEntity.class + } +) +@SessionFactory +public class LobTest { + static final Logger LOG = Logger.getLogger( LobTest.class.getName() ); @Test - public void hibernateTest() { - printConfig(); + public void hibernateTest(SessionFactoryScope scope) { + printConfig(scope); - Session session = openSession(); - session.beginTransaction(); - LobTestEntity entity = new LobTestEntity(); - entity.setId(1L); - entity.setLobValue(getLobHelper().createBlob(new byte[9999])); - entity.setQwerty(randomString(4000)); - session.persist(entity); - session.getTransaction().commit(); - session.close(); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { LobTestEntity.class }; + scope.inTransaction( + session -> { + LobTestEntity entity = new LobTestEntity(); + entity.setId( 1L ); + entity.setLobValue( getLobHelper().createBlob( new byte[9999] ) ); + entity.setQwerty( randomString( 4000 ) ); + session.persist( entity ); + } + ); } private String randomString( int count ) { @@ -51,16 +55,14 @@ private String randomString( int count ) { return buffer.toString(); } - private void printConfig() { + private void printConfig(SessionFactoryScope scope) { String sql = "select value from V$NLS_PARAMETERS where parameter = 'NLS_CHARACTERSET'"; - Session session = openSession(); - session.beginTransaction(); - Query query = session.createNativeQuery( sql ); - - String s = (String) query.uniqueResult(); - log.debug( "Using Oracle charset " + s ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( + session -> { + String s = session.createNativeQuery( sql, String.class ).uniqueResult(); + LOG.info( "Using Oracle charset " + s ); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/locator/LobLocatorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/locator/LobLocatorTest.java index 797349ed03b6..619007cc4e90 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/locator/LobLocatorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/locator/LobLocatorTest.java @@ -4,28 +4,29 @@ */ package org.hibernate.orm.test.annotations.lob.locator; -import java.sql.SQLException; - -import org.junit.Assert; -import org.junit.Test; - -import org.hibernate.Session; -import org.hibernate.testing.DialectChecks; -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.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.hibernate.type.descriptor.java.DataHelper; +import org.junit.jupiter.api.Test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.BDDAssertions.fail; import static org.hibernate.Hibernate.getLobHelper; /** * @author Lukasz Antoniak */ -public class LobLocatorTest extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { LobHolder.class }; - } +@DomainModel( + annotatedClasses = { + LobHolder.class + } +) +@SessionFactory +public class LobLocatorTest { /** * Specific JDBC drivers (e.g. SQL Server) may not automatically rewind bound input stream @@ -34,47 +35,56 @@ protected Class[] getAnnotatedClasses() { */ @Test @JiraKey(value = "HHH-8193") - @RequiresDialectFeature(DialectChecks.UsesInputStreamToInsertBlob.class) - public void testStreamResetBeforeParameterBinding() throws SQLException { - final Session session = openSession(); + @RequiresDialectFeature(feature = DialectFeatureChecks.UsesInputStreamToInsertBlob.class) + public void testStreamResetBeforeParameterBinding(SessionFactoryScope scope) { - session.getTransaction().begin(); - LobHolder entity = new LobHolder( - getLobHelper().createBlob( "blob".getBytes() ), - getLobHelper().createClob( "clob" ), 0 - ); - session.persist( entity ); - session.getTransaction().commit(); - - final Integer updatesLimit = 3; + scope.inTransaction( + session -> { + LobHolder entity = new LobHolder( + getLobHelper().createBlob( "blob".getBytes() ), + getLobHelper().createClob( "clob" ), 0 + ); + session.persist( entity ); + session.getTransaction().commit(); - for ( int i = 1; i <= updatesLimit; ++i ) { - session.getTransaction().begin(); - entity = (LobHolder) session.get( LobHolder.class, entity.getId() ); - entity.setCounter( i ); - entity = (LobHolder) session.merge( entity ); - session.getTransaction().commit(); - } + final int updatesLimit = 3; - session.getTransaction().begin(); - entity = (LobHolder) session.get( LobHolder.class, entity.getId() ); - entity.setBlobLocator( getLobHelper().createBlob( "updated blob".getBytes() ) ); - entity.setClobLocator( getLobHelper().createClob( "updated clob" ) ); - entity = (LobHolder) session.merge( entity ); - session.getTransaction().commit(); + for ( int i = 1; i <= updatesLimit; ++i ) { + session.getTransaction().begin(); + entity = session.find( LobHolder.class, entity.getId() ); + entity.setCounter( i ); + entity = session.merge( entity ); + session.getTransaction().commit(); + } - session.clear(); + session.getTransaction().begin(); + entity = session.find( LobHolder.class, entity.getId() ); + entity.setBlobLocator( getLobHelper().createBlob( "updated blob".getBytes() ) ); + entity.setClobLocator( getLobHelper().createClob( "updated clob" ) ); + entity = session.merge( entity ); + session.getTransaction().commit(); - session.getTransaction().begin(); - checkState( "updated blob".getBytes(), "updated clob", updatesLimit, (LobHolder) session.get( LobHolder.class, entity.getId() ) ); - session.getTransaction().commit(); + session.clear(); - session.close(); + session.getTransaction().begin(); + try { + checkState( + "updated blob".getBytes(), + "updated clob", + updatesLimit, + session.find( LobHolder.class, entity.getId() ) + ); + } + catch (Exception e) { + fail( e ); + } + } + ); } - private void checkState(byte[] blob, String clob, Integer counter, LobHolder entity) throws SQLException { - Assert.assertEquals( counter, entity.getCounter() ); - Assert.assertArrayEquals( blob, DataHelper.extractBytes( entity.getBlobLocator().getBinaryStream() ) ); - Assert.assertEquals( clob, DataHelper.extractString( entity.getClobLocator() ) ); + private void checkState(byte[] blob, String clob, Integer counter, LobHolder entity) throws Exception { + assertThat( entity.getCounter() ).isEqualTo( counter ); + assertThat( DataHelper.extractBytes( entity.getBlobLocator().getBinaryStream() ) ).isEqualTo( blob ); + assertThat( DataHelper.extractString( entity.getClobLocator() ) ).isEqualTo( clob ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Building.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Building.java index 205d33af5f49..3a62ca186cdb 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Building.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Building.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.manytomany; + import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; @@ -14,7 +15,9 @@ */ @Entity public class Building { - @Id @GeneratedValue private Long id; + @Id + @GeneratedValue + private Long id; @ManyToOne @JoinColumn(name="company_id", referencedColumnName = "name") private BuildingCompany company; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/BuildingCompany.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/BuildingCompany.java index f773ef6105b1..51c3dc89a2e7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/BuildingCompany.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/BuildingCompany.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.manytomany; + import java.util.Date; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; @@ -13,7 +14,10 @@ */ @Entity public class BuildingCompany extends Company { - @Id @GeneratedValue private Long id; + @Id + @GeneratedValue + private Long id; + private Date foundedIn; public Date getFoundedIn() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Cat.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Cat.java index f5f114b9bee2..1a0d3023b763 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Cat.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Cat.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.manytomany; + import java.util.Set; import jakarta.persistence.EmbeddedId; import jakarta.persistence.Entity; @@ -52,9 +53,7 @@ public void setAge(int age) { public boolean equals(Object o) { if ( this == o ) return true; - if ( !( o instanceof Cat ) ) return false; - - final Cat cat = (Cat) o; + if ( !(o instanceof Cat cat) ) return false; if ( !id.equals( cat.id ) ) return false; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/City.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/City.java index aef5c4cd6f6c..8b73e0781eaf 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/City.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/City.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.manytomany; + import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Contractor.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Contractor.java index 0d3bb60cba9b..31a1b3afdd13 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Contractor.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Contractor.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.manytomany; + import java.io.Serializable; import jakarta.persistence.Entity; @@ -12,7 +13,6 @@ * @author Emmanuel Bernard */ @Entity -@SuppressWarnings("serial") public class Contractor extends Employee implements Serializable { private float hourlyRate; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Employee.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Employee.java index df20d52dba19..9f83d4c83c19 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Employee.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Employee.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.manytomany; + import java.io.Serializable; import java.util.Collection; import jakarta.persistence.CascadeType; @@ -24,7 +25,6 @@ */ @Entity @Inheritance(strategy = InheritanceType.JOINED) -@SuppressWarnings("serial") public class Employee implements Serializable { private Integer id; private Collection employers; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Employer.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Employer.java index dbbc3a34bec7..240edeb79cc9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Employer.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Employer.java @@ -25,11 +25,10 @@ */ @Entity() @Table(name="`Employer`") -@SuppressWarnings({"serial", "unchecked"}) public class Employer implements Serializable { private Integer id; - private Collection employees; - private List contractors; + private Collection employees; + private List contractors; @ManyToMany( targetEntity = Contractor.class, @@ -42,11 +41,11 @@ public class Employer implements Serializable { ) @Cascade({org.hibernate.annotations.CascadeType.PERSIST, org.hibernate.annotations.CascadeType.MERGE}) @OrderBy("name desc") - public List getContractors() { + public List getContractors() { return contractors; } - public void setContractors(List contractors) { + public void setContractors(List contractors) { this.contractors = contractors; } @@ -61,7 +60,7 @@ public void setContractors(List contractors) { ) @Cascade({org.hibernate.annotations.CascadeType.PERSIST, org.hibernate.annotations.CascadeType.MERGE}) @OrderBy("name asc") - public Collection getEmployees() { + public Collection getEmployees() { return employees; } @@ -71,7 +70,7 @@ public Integer getId() { return id; } - public void setEmployees(Collection set) { + public void setEmployees(Collection set) { employees = set; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Friend.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Friend.java index a6d85182c1cf..4d7e342f0253 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Friend.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Friend.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.manytomany; + import java.io.Serializable; import java.util.Set; import jakarta.persistence.CascadeType; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Group.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Group.java index 8352612dfe97..68ce2a7830b2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Group.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Group.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.manytomany; + import java.util.Collection; import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Inspector.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Inspector.java index 35ca1ca2fc53..0f9528c6de2e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Inspector.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Inspector.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.manytomany; + import java.io.Serializable; import jakarta.persistence.Column; import jakarta.persistence.Entity; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/InspectorPrefixes.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/InspectorPrefixes.java index 6e6455a184ba..e5d5f8ae70a6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/InspectorPrefixes.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/InspectorPrefixes.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.manytomany; + import java.util.ArrayList; import java.util.List; import jakarta.persistence.Column; @@ -20,17 +21,18 @@ class InspectorPrefixes extends Inspector { @Column(name = "prefixes", nullable = false) private String prefixes; + @ManyToMany() @JoinTable(name = "deserted_area", joinColumns = @JoinColumn(name = "inspector_name", referencedColumnName = "name"), inverseJoinColumns = @JoinColumn(name = "area_id", referencedColumnName = "id")) - private List desertedAreas = new ArrayList(); + private List desertedAreas = new ArrayList<>(); @ManyToMany() @JoinTable(name = "inspector_prefixes_areas", joinColumns = @JoinColumn(name = "inspector_id", referencedColumnName = "inspector_id"), inverseJoinColumns = @JoinColumn(name = "area_id", referencedColumnName = "id")) - private List areas = new ArrayList(); + private List areas = new ArrayList<>(); InspectorPrefixes() { } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/KnownClient.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/KnownClient.java index d0bc010adcab..bf5e305c2b4b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/KnownClient.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/KnownClient.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.manytomany; + import java.util.Set; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Man.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Man.java index 480e50b9d5b4..09e9bbf4dd20 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Man.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Man.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.manytomany; + import java.io.Serializable; import java.util.Set; import jakarta.persistence.CascadeType; @@ -54,8 +55,8 @@ public int hashCode() { public boolean equals(Object obj) { //a NPE can occurs, but I don't expect equals to be used before pk is set - if ( obj != null && obj instanceof Man ) { - return getId().equals( ( (Man) obj ).getId() ); + if ( obj instanceof Man m ) { + return getId().equals( m.getId() ); } else { return false; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/ManyToManyInverseJoinColumnSortedSetTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/ManyToManyInverseJoinColumnSortedSetTest.java index 52fe655acf57..0c0f390c3b58 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/ManyToManyInverseJoinColumnSortedSetTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/ManyToManyInverseJoinColumnSortedSetTest.java @@ -13,21 +13,31 @@ import org.hibernate.annotations.SortNatural; +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.Entity; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.JoinTable; import jakarta.persistence.ManyToMany; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; @JiraKey(value = "HHH-16031") -public class ManyToManyInverseJoinColumnSortedSetTest extends BaseCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + ManyToManyInverseJoinColumnSortedSetTest.ContainingEntity.class, + ManyToManyInverseJoinColumnSortedSetTest.ContainedEntity.class + } +) +@SessionFactory +public class ManyToManyInverseJoinColumnSortedSetTest { + @Test - public void testDefault() { - inTransaction( session -> { + public void testDefault(SessionFactoryScope scope) { + scope.inTransaction( session -> { ContainingEntity containing = new ContainingEntity(); containing.setId( 0 ); @@ -46,14 +56,14 @@ public void testDefault() { session.persist( containing ); } ); - inTransaction( session -> { + scope.inTransaction( session -> { ContainingEntity containing = session.get( ContainingEntity.class, 0 ); assertThat( containing.getContained() ) .extracting( ContainedEntity::getId ) .containsExactly( 1, 2 ); } ); - inTransaction( session -> { + scope.inTransaction( session -> { ContainingEntity containing = session.get( ContainingEntity.class, 0 ); ContainedEntity contained1 = session.get( ContainedEntity.class, 1 ); contained1.getContaining().remove( containing ); @@ -65,7 +75,7 @@ public void testDefault() { // Try again from a new transaction; // with the bug unsolved, getContained() returns an empty collection! - inTransaction( session -> { + scope.inTransaction( session -> { ContainingEntity containing = session.get( ContainingEntity.class, 0 ); assertThat( containing.getContained() ) .extracting( ContainedEntity::getId ) @@ -73,14 +83,6 @@ public void testDefault() { } ); } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - ContainingEntity.class, - ContainedEntity.class - }; - } - @Entity(name = "containing") public static class ContainingEntity { @Id diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/ManyToManyMaxFetchDepth0Test.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/ManyToManyMaxFetchDepth0Test.java index 67bd8a87e504..8914a5bef12b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/ManyToManyMaxFetchDepth0Test.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/ManyToManyMaxFetchDepth0Test.java @@ -4,18 +4,29 @@ */ package org.hibernate.orm.test.annotations.manytomany; -import org.hibernate.cfg.Configuration; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Environment; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.Setting; +import org.hibernate.testing.orm.junit.SettingProvider; /** * Many to many tests using max_fetch_depth == 0 * * @author Gail Badner */ +@ServiceRegistry( + settings = @Setting(name = Environment.MAX_FETCH_DEPTH, value = "0"), + settingProviders = { + @SettingProvider( + settingName = AvailableSettings.DEFAULT_LIST_SEMANTICS, + provider = ManyToManyTest.ListSemanticProvider.class + ), + @SettingProvider( + settingName = AvailableSettings.IMPLICIT_NAMING_STRATEGY, + provider = ManyToManyTest.ImplicitNamingStrategyProvider.class + ) + } +) public class ManyToManyMaxFetchDepth0Test extends ManyToManyTest { - @Override - protected void configure(Configuration cfg) { - cfg.setProperty( Environment.MAX_FETCH_DEPTH, 0 ); - super.configure( cfg ); - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/ManyToManyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/ManyToManyTest.java index c25be94c7f1f..813bf17df6fe 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/ManyToManyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/ManyToManyTest.java @@ -4,36 +4,34 @@ */ package org.hibernate.orm.test.annotations.manytomany; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Join; import jakarta.persistence.criteria.JoinType; import jakarta.persistence.criteria.Root; - import org.hibernate.Hibernate; -import org.hibernate.Session; -import org.hibernate.Transaction; +import org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl; import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; 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.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.SettingProvider; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; /** * Many to many tests @@ -41,69 +39,117 @@ * @author Emmanuel Bernard */ @SuppressWarnings("unchecked") -public class ManyToManyTest extends BaseCoreFunctionalTestCase { - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - configuration.setProperty( AvailableSettings.DEFAULT_LIST_SEMANTICS, CollectionClassification.BAG ); -// configuration.setImplicitNamingStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE ); +@DomainModel( + annotatedClasses = { + Friend.class, + Employer.class, + Employee.class, + Contractor.class, + Man.class, + Woman.class, + Store.class, + KnownClient.class, + Supplier.class, + City.class, + Cat.class, + Group.class, + GroupWithSet.class, + Permission.class, + Zone.class, + Inspector.class, + InspectorPrefixes.class, + BuildingCompany.class, + Building.class, + PhoneNumber.class, + ProgramManager.class + } +) +@SessionFactory +@ServiceRegistry( + settingProviders = { + @SettingProvider( + settingName = AvailableSettings.DEFAULT_LIST_SEMANTICS, + provider = ManyToManyTest.ListSemanticProvider.class + ), + @SettingProvider( + settingName = AvailableSettings.IMPLICIT_NAMING_STRATEGY, + provider = ManyToManyTest.ImplicitNamingStrategyProvider.class + ) + } +) +public class ManyToManyTest { + + public static class ListSemanticProvider implements SettingProvider.Provider { + @Override + public CollectionClassification getSetting() { + return CollectionClassification.BAG; + } + } + + public static class ImplicitNamingStrategyProvider + implements SettingProvider.Provider { + @Override + public ImplicitNamingStrategyLegacyJpaImpl getSetting() { + return ImplicitNamingStrategyLegacyJpaImpl.INSTANCE; + } + } + + @AfterEach + public void tearDown(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Test - public void testDefault() { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); + public void testDefault(SessionFactoryScope scope) { Store fnac = new Store(); - fnac.setName( "Fnac" ); KnownClient emmanuel = new KnownClient(); - emmanuel.setName( "Emmanuel" ); - emmanuel.setStores( new HashSet<>() ); - fnac.setCustomers( new HashSet<>() ); - fnac.getCustomers().add( emmanuel ); - emmanuel.getStores().add( fnac ); - fnac.setImplantedIn( new HashSet<>() ); City paris = new City(); - fnac.getImplantedIn().add( paris ); - paris.setName( "Paris" ); - s.persist( fnac ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - Store store; - KnownClient knownClient; - City city; - store = s.get( Store.class, fnac.getId() ); - assertNotNull( store ); - assertNotNull( store.getCustomers() ); - assertEquals( 1, store.getCustomers().size() ); - knownClient = store.getCustomers().iterator().next(); - assertEquals( emmanuel.getName(), knownClient.getName() ); - assertNotNull( store.getImplantedIn() ); - assertEquals( 1, store.getImplantedIn().size() ); - city = store.getImplantedIn().iterator().next(); - assertEquals( paris.getName(), city.getName() ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - knownClient = s.get( KnownClient.class, emmanuel.getId() ); - assertNotNull( knownClient ); - assertNotNull( knownClient.getStores() ); - assertEquals( 1, knownClient.getStores().size() ); - store = knownClient.getStores().iterator().next(); - assertEquals( fnac.getName(), store.getName() ); - tx.commit(); - s.close(); + + scope.inTransaction( + session -> { + fnac.setName( "Fnac" ); + emmanuel.setName( "Emmanuel" ); + emmanuel.setStores( new HashSet<>() ); + fnac.setCustomers( new HashSet<>() ); + fnac.getCustomers().add( emmanuel ); + emmanuel.getStores().add( fnac ); + fnac.setImplantedIn( new HashSet<>() ); + fnac.getImplantedIn().add( paris ); + paris.setName( "Paris" ); + session.persist( fnac ); + } + ); + + scope.inTransaction( + session -> { + Store store = session.find( Store.class, fnac.getId() ); + assertThat( store ).isNotNull(); + assertThat( store.getCustomers() ).isNotNull(); + assertThat( store.getCustomers().size() ).isEqualTo( 1 ); + KnownClient knownClient = store.getCustomers().iterator().next(); + assertThat( knownClient.getName() ).isEqualTo( emmanuel.getName() ); + assertThat( store.getImplantedIn() ).isNotNull(); + assertThat( store.getImplantedIn().size() ).isEqualTo( 1 ); + City city = store.getImplantedIn().iterator().next(); + assertThat( city.getName() ).isEqualTo( paris.getName() ); + } + ); + + scope.inTransaction( + session -> { + KnownClient knownClient = session.find( KnownClient.class, emmanuel.getId() ); + assertThat( knownClient ).isNotNull(); + assertThat( knownClient.getStores() ).isNotNull(); + assertThat( knownClient.getStores().size() ).isEqualTo( 1 ); + Store store = knownClient.getStores().iterator().next(); + assertThat( store.getName() ).isEqualTo( fnac.getName() ); + } + ); } @Test - public void testCanUseCriteriaQuery() { - inTransaction( s -> { + public void testCanUseCriteriaQuery(SessionFactoryScope scope) { + scope.inTransaction( s -> { Store fnac = new Store(); fnac.setName( "Fnac" ); Supplier emi = new Supplier(); @@ -115,346 +161,356 @@ public void testCanUseCriteriaQuery() { s.persist( fnac ); } ); - inTransaction( s -> { + scope.inTransaction( s -> { CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); CriteriaQuery criteria = criteriaBuilder.createQuery( Supplier.class ); Root root = criteria.from( Supplier.class ); Join suppStores = root.join( "suppStores", JoinType.INNER ); criteria.where( criteriaBuilder.equal( suppStores.get( "name" ), "Fnac" ) ); - List result = s.createQuery( criteria ).list(); + List result = s.createQuery( criteria ).list(); // List result = s.createCriteria( Supplier.class ).createAlias( "suppStores", "s" ).add( // Restrictions.eq( "s.name", "Fnac" ) ).list(); - assertEquals( 1, result.size() ); + assertThat( result.size() ).isEqualTo( 1 ); } ); } @Test - public void testDefaultCompositePk() { - Session s; - Transaction tx; - - s = openSession(); - tx = s.beginTransaction(); - CatPk catPk = new CatPk(); - catPk.setName( "Minou" ); - catPk.setThoroughbred( "Persan" ); + public void testDefaultCompositePk(SessionFactoryScope scope) { Cat cat = new Cat(); - cat.setId( catPk ); - cat.setAge( 32 ); Woman woman = new Woman(); - WomanPk womanPk = new WomanPk(); - womanPk.setFirstName( "Emma" ); - womanPk.setLastName( "Peel" ); - woman.setId( womanPk ); - woman.setCats( new HashSet<>() ); - woman.getCats().add( cat ); - cat.setHumanContacts( new HashSet() ); - cat.getHumanContacts().add( woman ); - s.persist( woman ); - s.persist( cat ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - Cat sameCat = s.get( Cat.class, cat.getId() ); - assertNotNull( sameCat ); - assertNotNull( sameCat.getHumanContacts() ); - assertEquals( 1, sameCat.getHumanContacts().size() ); - Woman sameWoman = sameCat.getHumanContacts().iterator().next(); - assertEquals( sameWoman.getId().getLastName(), woman.getId().getLastName() ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - sameWoman = s.get( Woman.class, woman.getId() ); - assertNotNull( sameWoman ); - assertNotNull( sameWoman.getCats() ); - assertEquals( 1, sameWoman.getCats().size() ); - sameCat = sameWoman.getCats().iterator().next(); - assertEquals( cat.getAge(), sameCat.getAge() ); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + CatPk catPk = new CatPk(); + catPk.setName( "Minou" ); + catPk.setThoroughbred( "Persan" ); + cat.setId( catPk ); + cat.setAge( 32 ); + WomanPk womanPk = new WomanPk(); + womanPk.setFirstName( "Emma" ); + womanPk.setLastName( "Peel" ); + woman.setId( womanPk ); + woman.setCats( new HashSet<>() ); + woman.getCats().add( cat ); + cat.setHumanContacts( new HashSet<>() ); + cat.getHumanContacts().add( woman ); + session.persist( woman ); + session.persist( cat ); + } + ); + + scope.inTransaction( + session -> { + Cat sameCat = session.find( Cat.class, cat.getId() ); + assertThat( sameCat ).isNotNull(); + assertThat( sameCat.getHumanContacts() ).isNotNull(); + assertThat( sameCat.getHumanContacts().size() ).isEqualTo( 1 ); + Woman sameWoman = sameCat.getHumanContacts().iterator().next(); + assertThat( sameWoman.getId().getLastName() ).isEqualTo( woman.getId().getLastName() ); + } + ); + + scope.inTransaction( + session -> { + Woman sameWoman = session.find( Woman.class, woman.getId() ); + assertThat( sameWoman ).isNotNull(); + assertThat( sameWoman.getCats() ).isNotNull(); + assertThat( sameWoman.getCats().size() ).isEqualTo( 1 ); + Cat sameCat = sameWoman.getCats().iterator().next(); + assertThat( sameCat.getAge() ).isEqualTo( cat.getAge() ); + } + ); } @Test - public void testMappedBy() { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); + public void testMappedBy(SessionFactoryScope scope) { Store fnac = new Store(); - fnac.setName( "Fnac" ); Supplier emi = new Supplier(); - emi.setName( "Emmanuel" ); - emi.setSuppStores( new HashSet<>() ); - fnac.setSuppliers( new HashSet<>() ); - fnac.getSuppliers().add( emi ); - emi.getSuppStores().add( fnac ); - s.persist( fnac ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - Store store; - Supplier supplier; - store = s.get( Store.class, fnac.getId() ); - assertNotNull( store ); - assertNotNull( store.getSuppliers() ); - assertEquals( 1, store.getSuppliers().size() ); - supplier = store.getSuppliers().iterator().next(); - assertEquals( emi.getName(), supplier.getName() ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - supplier = s.get( Supplier.class, emi.getId() ); - assertNotNull( supplier ); - assertNotNull( supplier.getSuppStores() ); - assertEquals( 1, supplier.getSuppStores().size() ); - store = supplier.getSuppStores().iterator().next(); - assertEquals( fnac.getName(), store.getName() ); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + fnac.setName( "Fnac" ); + emi.setName( "Emmanuel" ); + emi.setSuppStores( new HashSet<>() ); + fnac.setSuppliers( new HashSet<>() ); + fnac.getSuppliers().add( emi ); + emi.getSuppStores().add( fnac ); + session.persist( fnac ); + } + ); + + scope.inTransaction( + session -> { + Store store = session.find( Store.class, fnac.getId() ); + assertThat( store ).isNotNull(); + assertThat( store.getSuppliers() ).isNotNull(); + assertThat( store.getSuppliers().size() ).isEqualTo( 1 ); + Supplier supplier = store.getSuppliers().iterator().next(); + assertThat( supplier.getName() ).isEqualTo( emi.getName() ); + } + ); + + scope.inTransaction( + session -> { + Supplier supplier = session.find( Supplier.class, emi.getId() ); + assertThat( supplier ).isNotNull(); + assertThat( supplier.getSuppStores() ).isNotNull(); + assertThat( supplier.getSuppStores().size() ).isEqualTo( 1 ); + Store store = supplier.getSuppStores().iterator().next(); + assertThat( store.getName() ).isEqualTo( fnac.getName() ); + } + ); } @Test - public void testBasic() { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - Employer er = new Employer(); - Employee ee = new Employee(); - s.persist( ee ); - Set erColl = new HashSet(); - Collection eeColl = new ArrayList(); - erColl.add( ee ); - eeColl.add( er ); - er.setEmployees( erColl ); - ee.setEmployers( eeColl ); - //s.persist(ee); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - er = s.getReference( Employer.class, er.getId() ); - assertNotNull( er ); - assertNotNull( er.getEmployees() ); - assertEquals( 1, er.getEmployees().size() ); - Employee eeFromDb = (Employee) er.getEmployees().iterator().next(); - assertEquals( ee.getId(), eeFromDb.getId() ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - ee = s.get( Employee.class, ee.getId() ); - assertNotNull( ee ); - assertFalse( "ManyToMany mappedBy lazyness", Hibernate.isInitialized( ee.getEmployers() ) ); - tx.commit(); - assertFalse( "ManyToMany mappedBy lazyness", Hibernate.isInitialized( ee.getEmployers() ) ); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - ee = s.get( Employee.class, ee.getId() ); - assertNotNull( ee ); - er = ee.getEmployers().iterator().next(); - assertTrue( "second join non lazy", Hibernate.isInitialized( er ) ); - s.remove( er ); - s.remove( ee ); - tx.commit(); - s.close(); + public void testBasic(SessionFactoryScope scope) { + Employer e = new Employer(); + Employee e1 = new Employee(); + scope.inTransaction( + session -> { + session.persist( e1 ); + Set erColl = new HashSet<>(); + Collection eeColl = new ArrayList<>(); + erColl.add( e1 ); + eeColl.add( e ); + e.setEmployees( erColl ); + e1.setEmployers( eeColl ); + } + ); + + scope.inTransaction( + session -> { + Employer er = session.getReference( Employer.class, e.getId() ); + assertThat( er ).isNotNull(); + assertThat( er.getEmployees() ).isNotNull(); + assertThat( er.getEmployees().size() ).isEqualTo( 1 ); + Employee eeFromDb = (Employee) er.getEmployees().iterator().next(); + assertThat( eeFromDb.getId() ).isEqualTo( e1.getId() ); + } + ); + + scope.inSession( + session -> { + try { + session.getTransaction().begin(); + Employee ee = session.find( Employee.class, e1.getId() ); + assertThat( ee ).isNotNull(); + assertThat( Hibernate.isInitialized( ee.getEmployers() ) ) + .describedAs( "ManyToMany mappedBy lazyness" ) + .isFalse(); + session.getTransaction().commit(); + assertThat( Hibernate.isInitialized( ee.getEmployers() ) ) + .describedAs( "ManyToMany mappedBy lazyness" ) + .isFalse(); + } + finally { + if ( session.getTransaction().isActive() ) { + session.getTransaction().rollback(); + } + } + } + ); + + scope.inTransaction( + session -> { + Employee ee = session.find( Employee.class, e1.getId() ); + assertThat( ee ).isNotNull(); + Employer er = ee.getEmployers().iterator().next(); + assertThat( Hibernate.isInitialized( er ) ) + .describedAs( "second join non lazy" ) + .isTrue(); + session.remove( er ); + session.remove( ee ); + } + ); } @Test - public void testOrderByEmployee() { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - Employer employer = new Employer(); - Employee employee1 = new Employee(); - employee1.setName( "Emmanuel" ); - Employee employee2 = new Employee(); - employee2.setName( "Alice" ); - s.persist( employee1 ); - s.persist( employee2 ); - Set erColl = new HashSet(); - Collection eeColl = new ArrayList(); - Collection eeColl2 = new ArrayList(); - erColl.add( employee1 ); - erColl.add( employee2 ); - eeColl.add( employer ); - eeColl2.add( employer ); - employer.setEmployees( erColl ); - employee1.setEmployers( eeColl ); - employee2.setEmployers( eeColl2 ); - - s.flush(); - s.clear(); - - employer = s.get( Employer.class, employer.getId() ); - assertNotNull( employer ); - assertNotNull( employer.getEmployees() ); - assertEquals( 2, employer.getEmployees().size() ); - Employee eeFromDb = (Employee) employer.getEmployees().iterator().next(); - assertEquals( employee2.getName(), eeFromDb.getName() ); - tx.rollback(); - s.close(); + public void testOrderByEmployee(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Employer employer = new Employer(); + Employee employee1 = new Employee(); + employee1.setName( "Emmanuel" ); + Employee employee2 = new Employee(); + employee2.setName( "Alice" ); + session.persist( employee1 ); + session.persist( employee2 ); + Set erColl = new HashSet<>(); + Collection eeColl = new ArrayList<>(); + Collection eeColl2 = new ArrayList<>(); + erColl.add( employee1 ); + erColl.add( employee2 ); + eeColl.add( employer ); + eeColl2.add( employer ); + employer.setEmployees( erColl ); + employee1.setEmployers( eeColl ); + employee2.setEmployers( eeColl2 ); + + session.flush(); + session.clear(); + + employer = session.find( Employer.class, employer.getId() ); + assertThat( employer ).isNotNull(); + assertThat( employer.getEmployees() ).isNotNull(); + assertThat( employer.getEmployees().size() ).isEqualTo( 2 ); + Employee eeFromDb = (Employee) employer.getEmployees().iterator().next(); + assertThat( eeFromDb.getName() ).isEqualTo( employee2.getName() ); + } + ); } // HHH-4394 @Test - public void testOrderByContractor() { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - - // create some test entities - Employer employer = new Employer(); - Contractor contractor1 = new Contractor(); - contractor1.setName( "Emmanuel" ); - contractor1.setHourlyRate(100.0f); - Contractor contractor2 = new Contractor(); - contractor2.setName( "Hardy" ); - contractor2.setHourlyRate(99.99f); - s.persist( contractor1 ); - s.persist( contractor2 ); - - // add contractors to employer - List setOfContractors = new ArrayList(); - setOfContractors.add( contractor1 ); - setOfContractors.add( contractor2 ); - employer.setContractors( setOfContractors ); - - // add employer to contractors - Collection employerListContractor1 = new ArrayList(); - employerListContractor1.add( employer ); - contractor1.setEmployers( employerListContractor1 ); - - Collection employerListContractor2 = new ArrayList(); - employerListContractor2.add( employer ); - contractor2.setEmployers( employerListContractor2 ); - - s.flush(); - s.clear(); - - // assertions - employer = s.get( Employer.class, employer.getId() ); - assertNotNull( employer ); - assertNotNull( employer.getContractors() ); - assertEquals( 2, employer.getContractors().size() ); - Contractor firstContractorFromDb = (Contractor) employer.getContractors().iterator().next(); - assertEquals( contractor2.getName(), firstContractorFromDb.getName() ); - tx.rollback(); - s.close(); + public void testOrderByContractor(SessionFactoryScope scope) { + scope.inTransaction( + sesssion -> { + // tag::tagname[] + // create some test entities + Employer employer = new Employer(); + Contractor contractor1 = new Contractor(); + contractor1.setName( "Emmanuel" ); + contractor1.setHourlyRate( 100.0f ); + Contractor contractor2 = new Contractor(); + contractor2.setName( "Hardy" ); + contractor2.setHourlyRate( 99.99f ); + sesssion.persist( contractor1 ); + sesssion.persist( contractor2 ); + + // add contractors to employer + List setOfContractors = new ArrayList<>(); + setOfContractors.add( contractor1 ); + setOfContractors.add( contractor2 ); + employer.setContractors( setOfContractors ); + + // add employer to contractors + Collection employerListContractor1 = new ArrayList<>(); + employerListContractor1.add( employer ); + contractor1.setEmployers( employerListContractor1 ); + + Collection employerListContractor2 = new ArrayList<>(); + employerListContractor2.add( employer ); + contractor2.setEmployers( employerListContractor2 ); + + sesssion.flush(); + sesssion.clear(); + + // assertions + employer = sesssion.find( Employer.class, employer.getId() ); + assertThat( employer ).isNotNull(); + assertThat( employer.getContractors() ).isNotNull(); + assertThat( employer.getContractors().size() ).isEqualTo( 2 ); + Contractor firstContractorFromDb = (Contractor) employer.getContractors().iterator().next(); + assertThat( firstContractorFromDb.getName() ).isEqualTo( contractor2.getName() ); + // end::tagname[] + } + ); } @Test - public void testRemoveInBetween() { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - Employer er = new Employer(); - Employee ee = new Employee(); + public void testRemoveInBetween(SessionFactoryScope scope) { + Employer e = new Employer(); + Employee ee1 = new Employee(); Employee ee2 = new Employee(); - s.persist( ee ); - s.persist( ee2 ); - Set erColl = new HashSet(); - Collection eeColl = new ArrayList(); - erColl.add( ee ); - erColl.add( ee2 ); - eeColl.add( er ); - er.setEmployees( erColl ); - ee.setEmployers( eeColl ); - //s.persist(ee); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - er = s.getReference( Employer.class, er.getId() ); - assertNotNull( er ); - assertNotNull( er.getEmployees() ); - assertEquals( 2, er.getEmployees().size() ); - Iterator iterator = er.getEmployees().iterator(); - Employee eeFromDb = (Employee) iterator.next(); - if ( eeFromDb.getId().equals( ee.getId() ) ) { - eeFromDb = (Employee) iterator.next(); - } - assertEquals( ee2.getId(), eeFromDb.getId() ); - er.getEmployees().remove( eeFromDb ); - eeFromDb.getEmployers().remove( er ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - ee = s.get( Employee.class, ee.getId() ); - assertNotNull( ee ); - assertFalse( "ManyToMany mappedBy lazyness", Hibernate.isInitialized( ee.getEmployers() ) ); - tx.commit(); - assertFalse( "ManyToMany mappedBy lazyness", Hibernate.isInitialized( ee.getEmployers() ) ); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - ee = s.get( Employee.class, ee.getId() ); - assertNotNull( ee ); - er = ee.getEmployers().iterator().next(); - assertTrue( "second join non lazy", Hibernate.isInitialized( er ) ); - assertEquals( 1, er.getEmployees().size() ); - s.remove( er ); - s.remove( ee ); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + session.persist( ee1 ); + session.persist( ee2 ); + Set erColl = new HashSet<>(); + Collection eeColl = new ArrayList<>(); + erColl.add( ee1 ); + erColl.add( ee2 ); + eeColl.add( e ); + e.setEmployees( erColl ); + ee1.setEmployers( eeColl ); + //s.persist(ee); + } + ); + + scope.inTransaction( + session -> { + Employer er = session.getReference( Employer.class, e.getId() ); + assertThat( er ).isNotNull(); + assertThat( er.getEmployees() ).isNotNull(); + assertThat( er.getEmployees().size() ).isEqualTo( 2 ); + Iterator iterator = er.getEmployees().iterator(); + Employee eeFromDb = iterator.next(); + if ( eeFromDb.getId().equals( ee1.getId() ) ) { + eeFromDb = iterator.next(); + } + assertThat( eeFromDb.getId() ).isEqualTo( ee2.getId() ); + er.getEmployees().remove( eeFromDb ); + eeFromDb.getEmployers().remove( er ); + } + ); + + scope.inSession( + session -> { + try { + session.getTransaction().begin(); + Employee ee = session.find( Employee.class, ee1.getId() ); + assertThat( ee ).isNotNull(); + assertThat( Hibernate.isInitialized( ee.getEmployers() ) ) + .describedAs( "ManyToMany mappedBy lazyness" ) + .isFalse(); + session.getTransaction().commit(); + assertThat( Hibernate.isInitialized( ee.getEmployers() ) ) + .describedAs( "ManyToMany mappedBy lazyness" ) + .isFalse(); + } + finally { + if ( session.getTransaction().isActive() ) { + session.getTransaction().rollback(); + } + } + } + ); + + scope.inTransaction( + session -> { + Employee ee = session.find( Employee.class, ee1.getId() ); + assertThat( ee ).isNotNull(); + Employer er = ee.getEmployers().iterator().next(); + assertThat( Hibernate.isInitialized( er ) ) + .describedAs( "second join non lazy" ) + .isTrue(); + assertThat( er.getEmployees().size() ).isEqualTo( 1 ); + session.remove( er ); + session.remove( ee ); + } + ); } @Test - public void testSelf() { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - Friend f = new Friend(); + public void testSelf(SessionFactoryScope scope) { + Friend friend = new Friend(); Friend sndF = new Friend(); - f.setName( "Starsky" ); - sndF.setName( "Hutch" ); - Set frnds = new HashSet(); - frnds.add( sndF ); - f.setFriends( frnds ); - //Starsky is a friend of Hutch but hutch is not - s.persist( f ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - f = s.getReference( Friend.class, f.getId() ); - assertNotNull( f ); - assertNotNull( f.getFriends() ); - assertEquals( 1, f.getFriends().size() ); - Friend fromDb2ndFrnd = f.getFriends().iterator().next(); - assertEquals( fromDb2ndFrnd.getId(), sndF.getId() ); - assertEquals( 0, fromDb2ndFrnd.getFriends().size() ); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + friend.setName( "Starsky" ); + sndF.setName( "Hutch" ); + Set frnds = new HashSet<>(); + frnds.add( sndF ); + friend.setFriends( frnds ); + //Starsky is a friend of Hutch but hutch is not + session.persist( friend ); + } + ); + + scope.inTransaction( + session -> { + Friend f = session.getReference( Friend.class, friend.getId() ); + assertThat( f ).isNotNull(); + assertThat( f.getFriends() ).isNotNull(); + assertThat( f.getFriends().size() ).isEqualTo( 1 ); + Friend fromDb2ndFrnd = f.getFriends().iterator().next(); + assertThat( fromDb2ndFrnd.getId() ).isEqualTo( sndF.getId() ); + assertThat( fromDb2ndFrnd.getFriends().size() ).isEqualTo( 0 ); + } + ); } @Test - public void testCompositePk() { - Session s; - Transaction tx; - + public void testCompositePk(SessionFactoryScope scope) { ManPk m1pk = new ManPk(); m1pk.setElder( true ); m1pk.setFirstName( "Lucky" ); @@ -498,189 +554,196 @@ public void testCompositePk() { mens2.add( m2 ); w2.setMens( mens2 ); - s = openSession(); - tx = s.beginTransaction(); - s.persist( m1 ); - s.persist( m2 ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - m1 = s.getReference( Man.class, m1pk ); - assertFalse( m1.getWomens().isEmpty() ); - assertEquals( 1, m1.getWomens().size() ); - w1 = s.getReference( Woman.class, w1pk ); - assertFalse( w1.getMens().isEmpty() ); - assertEquals( 2, w1.getMens().size() ); - - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + session.persist( m1 ); + session.persist( m2 ); + } + ); + + scope.inTransaction( + session -> { + Man m = session.getReference( Man.class, m1pk ); + assertThat( m.getWomens() ).isNotEmpty(); + assertThat( m.getWomens().size() ).isEqualTo( 1 ); + Woman w = session.getReference( Woman.class, w1pk ); + assertThat( w.getMens() ).isNotEmpty(); + assertThat( w.getMens().size() ).isEqualTo( 2 ); + } + ); } @Test - public void testAssociationTableUniqueConstraints() { - Session s = openSession(); - Permission readAccess = new Permission(); - readAccess.setPermission( "read" ); - readAccess.setExpirationDate( new Date() ); - Collection coll = new ArrayList<>( 2 ); - coll.add( readAccess ); - coll.add( readAccess ); - Group group = new Group(); - group.setId( new Integer( 1 ) ); - group.setPermissions( coll ); - s.getTransaction().begin(); - try { - s.persist( group ); - s.getTransaction().commit(); - fail( "Unique constraints not applied on association table" ); - } - catch (Exception e) { - //success - s.getTransaction().rollback(); - } - finally { - s.close(); - } + public void testAssociationTableUniqueConstraints(SessionFactoryScope scope) { + scope.inSession( + session -> { + Permission readAccess = new Permission(); + readAccess.setPermission( "read" ); + readAccess.setExpirationDate( new Date() ); + Collection coll = new ArrayList<>( 2 ); + coll.add( readAccess ); + coll.add( readAccess ); + Group group = new Group(); + group.setId( 1 ); + group.setPermissions( coll ); + session.getTransaction().begin(); + try { + session.persist( group ); + session.getTransaction().commit(); + fail( "Unique constraints not applied on association table" ); + } + catch (Exception e) { + //success + session.getTransaction().rollback(); + } + } + ); } @Test - public void testAssociationTableAndOrderBy() { - Session s = openSession(); - s.enableFilter( "Groupfilter" ); - Permission readAccess = new Permission(); - readAccess.setPermission( "read" ); - readAccess.setExpirationDate( new Date() ); - Permission writeAccess = new Permission(); - writeAccess.setPermission( "write" ); - writeAccess.setExpirationDate( new Date( new Date().getTime() - 10*60*1000 ) ); - Collection coll = new ArrayList<>( 2 ); - coll.add( readAccess ); - coll.add( writeAccess ); - Group group = new Group(); - group.setId( new Integer( 1 ) ); - group.setPermissions( coll ); - s.getTransaction().begin(); - s.persist( group ); - s.flush(); - s.clear(); - group = s.get( Group.class, group.getId() ); - s.createQuery( "select g from Group g join fetch g.permissions").list(); - assertEquals( "write", group.getPermissions().iterator().next().getPermission() ); - s.getTransaction().rollback(); - s.close(); + public void testAssociationTableAndOrderBy(SessionFactoryScope scope) { + scope.inTransaction( + s -> { + s.enableFilter( "Groupfilter" ); + + Permission readAccess = new Permission(); + readAccess.setPermission( "read" ); + readAccess.setExpirationDate( new Date() ); + + Permission writeAccess = new Permission(); + writeAccess.setPermission( "write" ); + writeAccess.setExpirationDate( new Date( new Date().getTime() - 10 * 60 * 1000 ) ); + + Collection coll = new ArrayList<>( 2 ); + coll.add( readAccess ); + coll.add( writeAccess ); + + Group group = new Group(); + group.setId( 1 ); + group.setPermissions( coll ); + + s.persist( group ); + s.flush(); + s.clear(); + group = s.get( Group.class, group.getId() ); + s.createQuery( "select g from Group g join fetch g.permissions", Group.class ).list(); + assertThat( group.getPermissions().iterator().next().getPermission() ).isEqualTo( "write" ); + } + ); } @Test - public void testAssociationTableAndOrderByWithSet() { - Session s = openSession(); - s.enableFilter( "Groupfilter" ); - - Permission readAccess = new Permission(); - readAccess.setPermission( "read" ); - readAccess.setExpirationDate( new Date() ); - - Permission writeAccess = new Permission(); - writeAccess.setPermission( "write" ); - writeAccess.setExpirationDate( new Date( new Date().getTime() - 10*60*1000 ) ); - - Permission executeAccess = new Permission(); - executeAccess.setPermission( "execute" ); - executeAccess.setExpirationDate( new Date( new Date().getTime() - 5*60*1000 ) ); - - Set coll = new HashSet<>( 3 ); - coll.add( readAccess ); - coll.add( writeAccess ); - coll.add( executeAccess ); - - GroupWithSet group = new GroupWithSet(); - group.setId( new Integer( 1 ) ); - group.setPermissions( coll ); - s.getTransaction().begin(); - s.persist( group ); - s.flush(); - s.clear(); - - group = s.get( GroupWithSet.class, group.getId() ); - s.createQuery( "select g from Group g join fetch g.permissions").list(); - Iterator permIter = group.getPermissions().iterator(); - assertEquals( "write", permIter.next().getPermission() ); - assertEquals( "execute", permIter.next().getPermission() ); - assertEquals( "read", permIter.next().getPermission() ); - s.getTransaction().rollback(); - s.close(); + public void testAssociationTableAndOrderByWithSet(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.enableFilter( "Groupfilter" ); + + Permission readAccess = new Permission(); + readAccess.setPermission( "read" ); + readAccess.setExpirationDate( new Date() ); + + Permission writeAccess = new Permission(); + writeAccess.setPermission( "write" ); + writeAccess.setExpirationDate( new Date( new Date().getTime() - 10 * 60 * 1000 ) ); + + Permission executeAccess = new Permission(); + executeAccess.setPermission( "execute" ); + executeAccess.setExpirationDate( new Date( new Date().getTime() - 5 * 60 * 1000 ) ); + + Set coll = new HashSet<>( 3 ); + coll.add( readAccess ); + coll.add( writeAccess ); + coll.add( executeAccess ); + + GroupWithSet group = new GroupWithSet(); + group.setId( 1 ); + group.setPermissions( coll ); + + session.persist( group ); + session.flush(); + session.clear(); + + group = session.find( GroupWithSet.class, group.getId() ); + session.createQuery( "select g from Group g join fetch g.permissions", Group.class ).list(); + Iterator permIter = group.getPermissions().iterator(); + assertThat( permIter.next().getPermission() ).isEqualTo( "write" ); + assertThat( permIter.next().getPermission() ).isEqualTo( "execute" ); + assertThat( permIter.next().getPermission() ).isEqualTo( "read" ); + } + ); } @Test - public void testJoinedSubclassManyToMany() { - Session s = openSession(); + public void testJoinedSubclassManyToMany(SessionFactoryScope scope) { Zone a = new Zone(); - InspectorPrefixes ip = new InspectorPrefixes( "dgi" ); - Transaction tx = s.beginTransaction(); - s.persist( a ); - s.persist( ip ); - ip.getAreas().add( a ); - tx.commit(); - s.close(); - s = openSession(); - tx = s.beginTransaction(); - ip = s.get( InspectorPrefixes.class, ip.getId() ); - assertNotNull( ip ); - assertEquals( 1, ip.getAreas().size() ); - assertEquals( a.getId(), ip.getAreas().get( 0 ).getId() ); - s.remove( ip ); - s.remove( ip.getAreas().get( 0 ) ); - tx.commit(); - s.close(); + InspectorPrefixes i = new InspectorPrefixes( "dgi" ); + scope.inTransaction( + session -> { + session.persist( a ); + session.persist( i ); + i.getAreas().add( a ); + } + ); + + scope.inTransaction( + session -> { + InspectorPrefixes ip = session.find( InspectorPrefixes.class, i.getId() ); + assertThat( ip ).isNotNull(); + assertThat( ip.getAreas().size() ).isEqualTo( 1 ); + assertThat( ip.getAreas().get( 0 ).getId() ).isEqualTo( a.getId() ); + session.remove( ip ); + session.remove( ip.getAreas().get( 0 ) ); + } + ); } @Test - public void testJoinedSubclassManyToManyWithNonPkReference() { - Session s = openSession(); + public void testJoinedSubclassManyToManyWithNonPkReference(SessionFactoryScope scope) { + InspectorPrefixes i = new InspectorPrefixes( "dgi" ); Zone a = new Zone(); - InspectorPrefixes ip = new InspectorPrefixes( "dgi" ); - ip.setName( "Inspector" ); - Transaction tx = s.beginTransaction(); - s.persist( a ); - s.persist( ip ); - ip.getDesertedAreas().add( a ); - tx.commit(); - s.close(); - s = openSession(); - tx = s.beginTransaction(); - ip = s.get( InspectorPrefixes.class, ip.getId() ); - assertNotNull( ip ); - assertEquals( 1, ip.getDesertedAreas().size() ); - assertEquals( a.getId(), ip.getDesertedAreas().get( 0 ).getId() ); - s.remove( ip ); - s.remove( ip.getDesertedAreas().get( 0 ) ); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + i.setName( "Inspector" ); + session.persist( a ); + session.persist( i ); + i.getDesertedAreas().add( a ); + } + ); + + scope.inTransaction( + session -> { + InspectorPrefixes ip = session.find( InspectorPrefixes.class, i.getId() ); + assertThat( ip ).isNotNull(); + assertThat( ip.getDesertedAreas().size() ).isEqualTo( 1 ); + assertThat( ip.getDesertedAreas().get( 0 ).getId() ).isEqualTo( a.getId() ); + session.remove( ip ); + session.remove( ip.getDesertedAreas().get( 0 ) ); + } + ); } @Test - public void testReferencedColumnNameToSuperclass() { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - BuildingCompany comp = new BuildingCompany(); - comp.setFoundedIn( new Date() ); - comp.setName( "Builder century corp."); - s.persist( comp ); - Building building = new Building(); - building.setCompany( comp ); - s.persist( building ); - s.flush(); - s.clear(); - building = s.get( Building.class, building.getId() ); - assertEquals( comp.getName(), building.getCompany().getName() ); - tx.rollback(); - s.close(); + public void testReferencedColumnNameToSuperclass(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + BuildingCompany comp = new BuildingCompany(); + comp.setFoundedIn( new Date() ); + comp.setName( "Builder century corp." ); + session.persist( comp ); + Building building = new Building(); + building.setCompany( comp ); + session.persist( building ); + session.flush(); + session.clear(); + building = session.find( Building.class, building.getId() ); + assertThat( building.getCompany().getName() ).isEqualTo( comp.getName() ); + } + ); } @Test - @JiraKey( value = "HHH-4685" ) - public void testManyToManyEmbeddableBiDirectionalDotNotationInMappedBy() { + @JiraKey(value = "HHH-4685") + public void testManyToManyEmbeddableBiDirectionalDotNotationInMappedBy(SessionFactoryScope scope) { // Section 11.1.25 // The ManyToMany annotation may be used within an embeddable class contained within an entity class to specify a // relationship to a collection of entities[101]. If the relationship is bidirectional and the entity containing @@ -689,37 +752,37 @@ public void testManyToManyEmbeddableBiDirectionalDotNotationInMappedBy() { // notation syntax must be used in the mappedBy element to indicate the relationship attribute within the embedded // attribute. The value of each identifier used with the dot notation is the name of the respective embedded field // or property. - Session s; - s = openSession(); - s.getTransaction().begin(); Employee e = new Employee(); - e.setName( "Sharon" ); - List phoneNumbers = new ArrayList<>(); - Collection employees = new ArrayList<>(); - employees.add( e ); - ContactInfo contactInfo = new ContactInfo(); - PhoneNumber number = new PhoneNumber(); - number.setEmployees( employees ); - phoneNumbers.add( number ); - contactInfo.setPhoneNumbers( phoneNumbers ); - e.setContactInfo( contactInfo ); - s.persist( e ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.getTransaction().begin(); - e = s.get( e.getClass(),e.getId() ); - // follow both directions of many to many association - assertEquals("same employee", e.getName(), e.getContactInfo().getPhoneNumbers().get(0).getEmployees().iterator().next().getName()); - s.getTransaction().commit(); - - s.close(); + scope.inTransaction( + session -> { + e.setName( "Sharon" ); + List phoneNumbers = new ArrayList<>(); + Collection employees = new ArrayList<>(); + employees.add( e ); + ContactInfo contactInfo = new ContactInfo(); + PhoneNumber number = new PhoneNumber(); + number.setEmployees( employees ); + phoneNumbers.add( number ); + contactInfo.setPhoneNumbers( phoneNumbers ); + e.setContactInfo( contactInfo ); + session.persist( e ); + } + ); + + scope.inTransaction( + session -> { + Employee employee = session.find( e.getClass(), e.getId() ); + // follow both directions of many to many association + assertThat( employee.getName() ) + .isSameAs( employee.getContactInfo().getPhoneNumbers().get( 0 ).getEmployees().iterator() + .next().getName() ); + } + ); } @Test - @JiraKey( value = "HHH-4685" ) - public void testOneToManyEmbeddableBiDirectionalDotNotationInMappedBy() { + @JiraKey(value = "HHH-4685") + public void testOneToManyEmbeddableBiDirectionalDotNotationInMappedBy(SessionFactoryScope scope) { // Section 11.1.26 // The ManyToOne annotation may be used within an embeddable class to specify a relationship from the embeddable // class to an entity class. If the relationship is bidirectional, the non-owning OneToMany entity side must use the @@ -727,57 +790,29 @@ public void testOneToManyEmbeddableBiDirectionalDotNotationInMappedBy() { // or property on the owning side of the relationship. The dot (".") notation syntax must be used in the mappedBy // element to indicate the relationship attribute within the embedded attribute. The value of each identifier used // with the dot notation is the name of the respective embedded field or property. - Session s; - s = openSession(); - s.getTransaction().begin(); Employee e = new Employee(); - JobInfo job = new JobInfo(); - job.setJobDescription( "Sushi Chef" ); - ProgramManager pm = new ProgramManager(); - Collection employees = new ArrayList<>(); - employees.add(e); - pm.setManages( employees ); - job.setPm(pm); - e.setJobInfo( job ); - s.persist( e ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.getTransaction().begin(); - e = s.get( e.getClass(), e.getId() ); - assertEquals( "same job in both directions", - e.getJobInfo().getJobDescription(), - e.getJobInfo().getPm().getManages().iterator().next().getJobInfo().getJobDescription() ); - s.getTransaction().commit(); - s.close(); + scope.inTransaction( + session -> { + JobInfo job = new JobInfo(); + job.setJobDescription( "Sushi Chef" ); + ProgramManager pm = new ProgramManager(); + Collection employees = new ArrayList<>(); + employees.add( e ); + pm.setManages( employees ); + job.setPm( pm ); + e.setJobInfo( job ); + session.persist( e ); + } + ); + + scope.inTransaction( + session -> { + Employee employee = session.find( e.getClass(), e.getId() ); + assertThat( employee.getJobInfo().getJobDescription() ) + .describedAs( "same job in both directions" ) + .isSameAs( employee.getJobInfo().getPm().getManages().iterator().next().getJobInfo() + .getJobDescription() ); + } + ); } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - Friend.class, - Employer.class, - Employee.class, - Contractor.class, - Man.class, - Woman.class, - Store.class, - KnownClient.class, - Supplier.class, - City.class, - Cat.class, - Group.class, - GroupWithSet.class, - Permission.class, - Zone.class, - Inspector.class, - InspectorPrefixes.class, - BuildingCompany.class, - Building.class, - PhoneNumber.class, - ProgramManager.class - }; - } - } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Permission.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Permission.java index 4d2784c9cc3b..41c8760a55b1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Permission.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Permission.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.manytomany; + import java.util.Date; import jakarta.persistence.Entity; import jakarta.persistence.Id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/PhoneNumber.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/PhoneNumber.java index 7d1178147ecf..f4f0380860e0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/PhoneNumber.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/PhoneNumber.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.manytomany; + import java.util.Collection; import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/ProgramManager.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/ProgramManager.java index 7dda90888b90..acfc79c368be 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/ProgramManager.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/ProgramManager.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.manytomany; + import java.util.Collection; import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Store.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Store.java index 90df0e4bf8bb..c0333348a283 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Store.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Store.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.manytomany; + import java.util.Set; import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Supplier.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Supplier.java index fd59a3ab81ed..394f1e9bfe0e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Supplier.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Supplier.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.manytomany; + import java.util.Set; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Woman.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Woman.java index 821ad25f4c5f..d16b62a52011 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Woman.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Woman.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.manytomany; + import java.io.Serializable; import java.util.Set; import jakarta.persistence.CascadeType; @@ -81,8 +82,8 @@ public int hashCode() { public boolean equals(Object obj) { //a NPE can occurs, but I don't expect equals to be used before pk is set - if ( obj != null && obj instanceof Woman ) { - return getId().equals( ( (Woman) obj ).getId() ); + if ( obj instanceof Woman w ) { + return getId().equals( w.getId() ); } else { return false; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Zone.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Zone.java index 7971b4e205bf..f0d65ce273cc 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Zone.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Zone.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.manytomany; + import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/defaults/City.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/defaults/City.java index 058c725c2c4a..f0016ddccb08 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/defaults/City.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/defaults/City.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.manytomany.defaults; + import java.util.Set; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/defaults/Employee.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/defaults/Employee.java index adb07e79d916..cc72425f345e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/defaults/Employee.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/defaults/Employee.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.manytomany.defaults; + import java.io.Serializable; import jakarta.persistence.Column; import jakarta.persistence.Embedded; @@ -19,7 +20,6 @@ */ @Entity @Inheritance(strategy = InheritanceType.JOINED) -@SuppressWarnings("serial") public class Employee implements Serializable { private Integer id; private String name; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/defaults/JpaCompliantManyToManyImplicitNamingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/defaults/JpaCompliantManyToManyImplicitNamingTest.java index 80c18a00376c..c2527a122c9a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/defaults/JpaCompliantManyToManyImplicitNamingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/defaults/JpaCompliantManyToManyImplicitNamingTest.java @@ -4,11 +4,14 @@ */ package org.hibernate.orm.test.annotations.manytomany.defaults; -import org.hibernate.boot.MetadataBuilder; +import org.hibernate.boot.model.naming.ImplicitNamingStrategy; import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl; - +import org.hibernate.cfg.AvailableSettings; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.SettingProvider; +import org.junit.jupiter.api.Test; /** * Tests names generated for @JoinTable and @JoinColumn for unidirectional and bidirectional @@ -16,16 +19,26 @@ * * @author Gail Badner */ +@ServiceRegistry( + settingProviders = { + @SettingProvider( + settingName = AvailableSettings.IMPLICIT_NAMING_STRATEGY, + provider = JpaCompliantManyToManyImplicitNamingTest.ImplicitNamingStrategyProvider.class + ) + } +) public class JpaCompliantManyToManyImplicitNamingTest extends ManyToManyImplicitNamingTest { - @Override - protected void configureMetadataBuilder(MetadataBuilder metadataBuilder) { - super.configureMetadataBuilder( metadataBuilder ); - metadataBuilder.applyImplicitNamingStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE ); + + public static class ImplicitNamingStrategyProvider implements SettingProvider.Provider { + @Override + public ImplicitNamingStrategy getSetting() { + return ImplicitNamingStrategyJpaCompliantImpl.INSTANCE; + } } @Test - @JiraKey( value = "HHH-9390") - public void testUnidirOwnerPrimaryTableAssocEntityNamePKOverride() { + @JiraKey(value = "HHH-9390") + public void testUnidirOwnerPrimaryTableAssocEntityNamePKOverride(SessionFactoryScope scope) { // City.stolenItems; associated entity: Item // City has @Entity with no name configured and @Table(name = "tbl_city") // Item has @Entity(name="ITEM") and no @Table @@ -38,13 +51,14 @@ public void testUnidirOwnerPrimaryTableAssocEntityNamePKOverride() { null, "tbl_city_ITEM", "City_id", - "stolenItems_iId" + "stolenItems_iId", + scope ); } @Test - @JiraKey( value = "HHH-9390") - public void testUnidirOwnerEntityNamePrimaryTableOverride() { + @JiraKey(value = "HHH-9390") + public void testUnidirOwnerEntityNamePrimaryTableOverride(SessionFactoryScope scope) { // Category.clients: associated entity: KnownClient // Category has @Entity(name="CATEGORY") @Table(name="CATEGORY_TAB") // KnownClient has @Entity with no name configured and no @Table @@ -57,8 +71,8 @@ public void testUnidirOwnerEntityNamePrimaryTableOverride() { null, "CATEGORY_TAB_KnownClient", "CATEGORY_id", - "clients_id" - + "clients_id", + scope ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/defaults/KnownClient.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/defaults/KnownClient.java index 467cc0bad6a5..8fbf2c27ef27 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/defaults/KnownClient.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/defaults/KnownClient.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.manytomany.defaults; + import java.util.Set; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/defaults/ManyToManyImplicitNamingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/defaults/ManyToManyImplicitNamingTest.java index 59f185f34463..34e4b58f0457 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/defaults/ManyToManyImplicitNamingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/defaults/ManyToManyImplicitNamingTest.java @@ -4,19 +4,22 @@ */ package org.hibernate.orm.test.annotations.manytomany.defaults; -import org.hibernate.boot.MetadataBuilder; +import org.hibernate.boot.model.naming.ImplicitNamingStrategy; import org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl; +import org.hibernate.boot.spi.MetadataImplementor; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.mapping.ForeignKey; import org.hibernate.mapping.PersistentClass; -import org.hibernate.type.EntityType; - +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -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.SettingProvider; +import org.hibernate.type.EntityType; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests names generated for {@code @JoinTable} and {@code @JoinColumn} for unidirectional @@ -28,15 +31,38 @@ * * @author Gail Badner */ -public class ManyToManyImplicitNamingTest extends BaseNonConfigCoreFunctionalTestCase { - @Override - protected void configureMetadataBuilder(MetadataBuilder metadataBuilder) { - super.configureMetadataBuilder( metadataBuilder ); - metadataBuilder.applyImplicitNamingStrategy( ImplicitNamingStrategyLegacyJpaImpl.INSTANCE ); +@DomainModel( + annotatedClasses = { + Category.class, + City.class, + Employee.class, + Item.class, + KnownClient.class, + PhoneNumber.class, + Store.class, + } +) +@ServiceRegistry( + settingProviders = { + @SettingProvider( + settingName = AvailableSettings.IMPLICIT_NAMING_STRATEGY, + provider = ManyToManyImplicitNamingTest.ImplicitNamingStrategyProvider.class + ) + } +) +@SessionFactory +public class ManyToManyImplicitNamingTest { + + public static class ImplicitNamingStrategyProvider + implements SettingProvider.Provider { + @Override + public ImplicitNamingStrategy getSetting() { + return ImplicitNamingStrategyLegacyJpaImpl.INSTANCE; + } } @Test - public void testBidirNoOverrides() { + public void testBidirNoOverrides(SessionFactoryScope scope) { // Employee.contactInfo.phoneNumbers: associated entity: PhoneNumber // both have @Entity with no name configured and default primary table names; // Primary table names default to unqualified entity classes. @@ -49,12 +75,13 @@ public void testBidirNoOverrides() { "employees", "Employee_PhoneNumber", "employees_id", - "phoneNumbers_phNumber" + "phoneNumbers_phNumber", + scope ); } @Test - public void testBidirOwnerPKOverride() { + public void testBidirOwnerPKOverride(SessionFactoryScope scope) { // Store.customers; associated entity: KnownClient // both have @Entity with no name configured and default primary table names // Primary table names default to unqualified entity classes. @@ -67,12 +94,13 @@ public void testBidirOwnerPKOverride() { "stores", "Store_KnownClient", "stores_sId", - "customers_id" + "customers_id", + scope ); } @Test - public void testUnidirOwnerPKAssocEntityNamePKOverride() { + public void testUnidirOwnerPKAssocEntityNamePKOverride(SessionFactoryScope scope) { // Store.items; associated entity: Item // Store has @Entity with no name configured and no @Table // Item has @Entity(name="ITEM") and no @Table @@ -85,13 +113,13 @@ public void testUnidirOwnerPKAssocEntityNamePKOverride() { null, "Store_ITEM", "Store_sId", - "items_iId" - + "items_iId", + scope ); } @Test - public void testUnidirOwnerPKAssocPrimaryTableNameOverride() { + public void testUnidirOwnerPKAssocPrimaryTableNameOverride(SessionFactoryScope scope) { // Store.implantedIn; associated entity: City // Store has @Entity with no name configured and no @Table // City has @Entity with no name configured and @Table(name = "tbl_city") @@ -104,12 +132,13 @@ public void testUnidirOwnerPKAssocPrimaryTableNameOverride() { null, "Store_tbl_city", "Store_sId", - "implantedIn_id" + "implantedIn_id", + scope ); } @Test - public void testUnidirOwnerPKAssocEntityNamePrimaryTableOverride() { + public void testUnidirOwnerPKAssocEntityNamePrimaryTableOverride(SessionFactoryScope scope) { // Store.categories; associated entity: Category // Store has @Entity with no name configured and no @Table // Category has @Entity(name="CATEGORY") @Table(name="CATEGORY_TAB") @@ -122,12 +151,13 @@ public void testUnidirOwnerPKAssocEntityNamePrimaryTableOverride() { null, "Store_CATEGORY_TAB", "Store_sId", - "categories_id" + "categories_id", + scope ); } @Test - public void testUnidirOwnerEntityNamePKAssocPrimaryTableOverride() { + public void testUnidirOwnerEntityNamePKAssocPrimaryTableOverride(SessionFactoryScope scope) { // Item.producedInCities: associated entity: City // Item has @Entity(name="ITEM") and no @Table // City has @Entity with no name configured and @Table(name = "tbl_city") @@ -140,13 +170,14 @@ public void testUnidirOwnerEntityNamePKAssocPrimaryTableOverride() { null, "ITEM_tbl_city", "ITEM_iId", - "producedInCities_id" + "producedInCities_id", + scope ); } @Test - @JiraKey( value = "HHH-9390") - public void testUnidirOwnerEntityNamePrimaryTableOverride() { + @JiraKey(value = "HHH-9390") + public void testUnidirOwnerEntityNamePrimaryTableOverride(SessionFactoryScope scope) { // Category.clients: associated entity: KnownClient // Category has @Entity(name="CATEGORY") @Table(name="CATEGORY_TAB") // KnownClient has @Entity with no name configured and no @Table @@ -160,8 +191,8 @@ public void testUnidirOwnerEntityNamePrimaryTableOverride() { null, "CATEGORY_TAB_KnownClient", "CATEGORY_TAB_id", - "clients_id" - + "clients_id", + scope ); } @@ -171,61 +202,50 @@ protected void checkDefaultJoinTablAndJoinColumnNames( String inverseCollectionPropertyName, String expectedCollectionTableName, String ownerForeignKeyNameExpected, - String inverseForeignKeyNameExpected) { - final org.hibernate.mapping.Collection collection = metadata().getCollectionBinding( ownerEntityClass.getName() + '.' + ownerCollectionPropertyName ); + String inverseForeignKeyNameExpected, + SessionFactoryScope scope) { + MetadataImplementor metadata = scope.getMetadataImplementor(); + final org.hibernate.mapping.Collection collection = metadata.getCollectionBinding( + ownerEntityClass.getName() + '.' + ownerCollectionPropertyName ); final org.hibernate.mapping.Table table = collection.getCollectionTable(); - assertEquals( expectedCollectionTableName, table.getName() ); + assertThat( table.getName() ).isEqualTo( expectedCollectionTableName ); - final org.hibernate.mapping.Collection ownerCollection = metadata().getCollectionBinding( + final org.hibernate.mapping.Collection ownerCollection = metadata.getCollectionBinding( ownerEntityClass.getName() + '.' + ownerCollectionPropertyName ); // The default owner and inverse join columns can only be computed if they have PK with 1 column. - assertEquals ( 1, ownerCollection.getOwner().getKey().getColumnSpan() ); - assertEquals( ownerForeignKeyNameExpected, ownerCollection.getKey().getColumns().get(0).getText() ); + assertThat( ownerCollection.getOwner().getKey().getColumnSpan() ).isEqualTo( 1 ); + assertThat( ownerCollection.getKey().getColumns().get( 0 ).getText() ).isEqualTo( ownerForeignKeyNameExpected ); - final EntityType associatedEntityType = (EntityType) ownerCollection.getElement().getType(); + final EntityType associatedEntityType = (EntityType) ownerCollection.getElement().getType(); final PersistentClass associatedPersistentClass = - metadata().getEntityBinding( associatedEntityType.getAssociatedEntityName() ); - assertEquals( 1, associatedPersistentClass.getKey().getColumnSpan() ); + metadata.getEntityBinding( associatedEntityType.getAssociatedEntityName() ); + assertThat( associatedPersistentClass.getKey().getColumnSpan() ).isEqualTo( 1 ); if ( inverseCollectionPropertyName != null ) { - final org.hibernate.mapping.Collection inverseCollection = metadata().getCollectionBinding( + final org.hibernate.mapping.Collection inverseCollection = metadata.getCollectionBinding( associatedPersistentClass.getEntityName() + '.' + inverseCollectionPropertyName ); - assertEquals( - inverseForeignKeyNameExpected, - inverseCollection.getKey().getSelectables().get( 0 ).getText() - ); + assertThat( inverseCollection.getKey().getSelectables().get( 0 ).getText() ) + .isEqualTo( inverseForeignKeyNameExpected ); } boolean hasOwnerFK = false; boolean hasInverseFK = false; for ( final ForeignKey fk : ownerCollection.getCollectionTable().getForeignKeyCollection() ) { - assertSame( ownerCollection.getCollectionTable(), fk.getTable() ); + assertThat( fk.getTable() ).isSameAs( ownerCollection.getCollectionTable() ); if ( fk.getColumnSpan() > 1 ) { continue; } if ( fk.getColumn( 0 ).getText().equals( ownerForeignKeyNameExpected ) ) { - assertSame( ownerCollection.getOwner().getTable(), fk.getReferencedTable() ); + assertThat( fk.getReferencedTable() ).isSameAs( ownerCollection.getOwner().getTable() ); hasOwnerFK = true; } else if ( fk.getColumn( 0 ).getText().equals( inverseForeignKeyNameExpected ) ) { - assertSame( associatedPersistentClass.getTable(), fk.getReferencedTable() ); + assertThat( fk.getReferencedTable() ).isSameAs( associatedPersistentClass.getTable() ); hasInverseFK = true; } } - assertTrue( hasOwnerFK ); - assertTrue( hasInverseFK ); + assertThat( hasOwnerFK ).isTrue(); + assertThat( hasInverseFK ).isTrue(); } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - Category.class, - City.class, - Employee.class, - Item.class, - KnownClient.class, - PhoneNumber.class, - Store.class, - }; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/defaults/PhoneNumber.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/defaults/PhoneNumber.java index ebaf9186d752..a6938419382f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/defaults/PhoneNumber.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/defaults/PhoneNumber.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.manytomany.defaults; + import java.util.Collection; import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoone/ManyToOneTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoone/ManyToOneTest.java index 5f5d7e2e9425..8fbac5cd543f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoone/ManyToOneTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoone/ManyToOneTest.java @@ -20,6 +20,7 @@ import org.junit.jupiter.api.Test; import java.util.ArrayList; +import java.util.List; import static org.hibernate.cfg.MappingSettings.IMPLICIT_NAMING_STRATEGY; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -128,7 +129,7 @@ public void testCascade(SessionFactoryScope factoryScope) { var discount = new Discount(); discount.setDiscount( 20.12 ); var customer = new Customer(); - var discounts = new ArrayList<>(); + List discounts = new ArrayList<>(); discounts.add( discount ); customer.setName( "Quentin Tarantino" ); discount.setOwner( customer ); @@ -144,7 +145,7 @@ public void testCascade(SessionFactoryScope factoryScope) { var customer = new Customer(); customer.setName( "Clooney" ); discount.setOwner( customer ); - var discounts = new ArrayList<>(); + List discounts = new ArrayList<>(); discounts.add( discount ); customer.setDiscountTickets( discounts ); } ); @@ -163,7 +164,7 @@ public void testFetch(SessionFactoryScope factoryScope) { var discount = new Discount(); discount.setDiscount( 20 ); var customer = new Customer(); - var discounts = new ArrayList<>(); + List discounts = new ArrayList<>(); discounts.add( discount ); customer.setName( "Quentin Tarantino" ); discount.setOwner( customer ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/CamelCaseToUnderscoresNamingStrategyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/CamelCaseToUnderscoresNamingStrategyTest.java index 8914440ec292..25e9c2538458 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/CamelCaseToUnderscoresNamingStrategyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/CamelCaseToUnderscoresNamingStrategyTest.java @@ -5,40 +5,39 @@ package org.hibernate.orm.test.annotations.namingstrategy; import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.model.naming.PhysicalNamingStrategySnakeCaseImpl; import org.hibernate.cfg.Environment; import org.hibernate.mapping.PersistentClass; import org.hibernate.service.ServiceRegistry; - import org.hibernate.testing.ServiceRegistryBuilder; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import jakarta.persistence.Entity; -import jakarta.persistence.Id; -import jakarta.persistence.Table; +import org.hibernate.testing.orm.junit.BaseUnitTest; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Test harness for HHH-17310. * * @author Anilabha Baral */ -public class CamelCaseToUnderscoresNamingStrategyTest extends BaseUnitTestCase { +@BaseUnitTest +public class CamelCaseToUnderscoresNamingStrategyTest { private ServiceRegistry serviceRegistry; - @Before + @BeforeAll public void setUp() { serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry( Environment.getProperties() ); } - @After + @AfterAll public void tearDown() { if ( serviceRegistry != null ) { ServiceRegistryBuilder.destroy( serviceRegistry ); @@ -46,7 +45,7 @@ public void tearDown() { } @Test - public void testWithWordWithDigitNamingStrategy() throws Exception { + public void testWithWordWithDigitNamingStrategy() { Metadata metadata = new MetadataSources( serviceRegistry ) .addAnnotatedClass( B.class ) .getMetadataBuilder() @@ -54,30 +53,18 @@ public void testWithWordWithDigitNamingStrategy() throws Exception { .build(); PersistentClass entityBinding = metadata.getEntityBinding( B.class.getName() ); - assertEquals( - "word_with_digit_d1", - entityBinding.getProperty( "wordWithDigitD1" ).getSelectables().get( 0 ).getText() - ); - assertEquals( - "abcd_efgh_i21", - entityBinding.getProperty( "AbcdEfghI21" ).getSelectables().get( 0 ).getText() - ); - assertEquals( - "hello1", - entityBinding.getProperty( "hello1" ).getSelectables().get( 0 ).getText() - ); - assertEquals( - "hello1_d2", - entityBinding.getProperty( "hello1D2" ).getSelectables().get( 0 ).getText() - ); - assertEquals( - "hello3d4", - entityBinding.getProperty( "hello3d4" ).getSelectables().get( 0 ).getText() - ); - assertEquals( - "Quoted-ColumnName", - entityBinding.getProperty( "quoted" ).getSelectables().get( 0 ).getText() - ); + assertThat( entityBinding.getProperty( "wordWithDigitD1" ).getSelectables().get( 0 ).getText() ) + .isEqualTo( "word_with_digit_d1" ); + assertThat( entityBinding.getProperty( "AbcdEfghI21" ).getSelectables().get( 0 ).getText() ) + .isEqualTo( "abcd_efgh_i21" ); + assertThat( entityBinding.getProperty( "hello1" ).getSelectables().get( 0 ).getText() ) + .isEqualTo( "hello1" ); + assertThat( entityBinding.getProperty( "hello1D2" ).getSelectables().get( 0 ).getText() ) + .isEqualTo( "hello1_d2" ); + assertThat( entityBinding.getProperty( "hello3d4" ).getSelectables().get( 0 ).getText() ) + .isEqualTo( "hello3d4" ); + assertThat( entityBinding.getProperty( "quoted" ).getSelectables().get( 0 ).getText() ) + .isEqualTo( "Quoted-ColumnName" ); } @Entity diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/LongKeyNamingStrategyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/LongKeyNamingStrategyTest.java index d9a868509c76..692f6e0f9cb8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/LongKeyNamingStrategyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/LongKeyNamingStrategyTest.java @@ -12,59 +12,62 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; import jakarta.persistence.UniqueConstraint; - import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.cfg.Environment; import org.hibernate.service.ServiceRegistry; - import org.hibernate.testing.ServiceRegistryBuilder; +import org.hibernate.testing.orm.junit.BaseUnitTest; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Test harness for HHH-11089. * * @author Vlad Mihalcea */ -@JiraKey( value = "HHH-11089" ) -public class LongKeyNamingStrategyTest extends BaseUnitTestCase { +@JiraKey(value = "HHH-11089") +@BaseUnitTest +public class LongKeyNamingStrategyTest { private ServiceRegistry serviceRegistry; - @Before + @BeforeAll public void setUp() { serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry( Environment.getProperties() ); } - @After + @AfterAll public void tearDown() { if ( serviceRegistry != null ) { ServiceRegistryBuilder.destroy( serviceRegistry ); } } + @Test - public void testWithCustomNamingStrategy() throws Exception { + public void testWithCustomNamingStrategy() { Metadata metadata = new MetadataSources( serviceRegistry ) - .addAnnotatedClass(Address.class) - .addAnnotatedClass(Person.class) + .addAnnotatedClass( Address.class ) + .addAnnotatedClass( Person.class ) .getMetadataBuilder() .applyImplicitNamingStrategy( new LongIdentifierNamingStrategy() ) .build(); - var foreignKey = metadata.getEntityBinding(Address.class.getName()).getTable().getForeignKeyCollection().iterator().next(); - assertEquals( "FK_way_longer_than_the_30_char", foreignKey.getName() ); + var foreignKey = metadata.getEntityBinding( Address.class.getName() ).getTable().getForeignKeyCollection() + .iterator().next(); + assertThat( foreignKey.getName() ).isEqualTo( "FK_way_longer_than_the_30_char" ); - var uniqueKey = metadata.getEntityBinding(Address.class.getName()).getTable().getUniqueKeys().values().iterator().next(); - assertEquals( "UK_way_longer_than_the_30_char", uniqueKey.getName() ); + var uniqueKey = metadata.getEntityBinding( Address.class.getName() ).getTable().getUniqueKeys().values() + .iterator().next(); + assertThat( uniqueKey.getName() ).isEqualTo( "UK_way_longer_than_the_30_char" ); - var index = metadata.getEntityBinding(Address.class.getName()).getTable().getIndexes().values().iterator().next(); - assertEquals( "IDX_way_longer_than_the_30_cha", index.getName() ); + var index = metadata.getEntityBinding( Address.class.getName() ).getTable().getIndexes().values().iterator() + .next(); + assertThat( index.getName() ).isEqualTo( "IDX_way_longer_than_the_30_cha" ); } @Entity(name = "Address") @@ -73,7 +76,8 @@ public void testWithCustomNamingStrategy() throws Exception { columnNames = { "city", "streetName", "streetNumber" }), - indexes = @Index( name = "IDX_way_longer_than_the_30_characters_limit", columnList = "city, streetName, streetNumber") + indexes = @Index(name = "IDX_way_longer_than_the_30_characters_limit", + columnList = "city, streetName, streetNumber") ) public class Address { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/NamingStrategyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/NamingStrategyTest.java index f9926371ed28..8a1d28b313c5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/NamingStrategyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/NamingStrategyTest.java @@ -4,7 +4,6 @@ */ package org.hibernate.orm.test.annotations.namingstrategy; -import java.util.Locale; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.model.naming.Identifier; @@ -14,32 +13,33 @@ import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; import org.hibernate.mapping.Collection; import org.hibernate.mapping.PersistentClass; -import org.hibernate.mapping.Selectable; import org.hibernate.service.ServiceRegistry; - 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.hibernate.testing.orm.junit.BaseUnitTest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Locale; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Test harness for ANN-716. * * @author Hardy Ferentschik */ -public class NamingStrategyTest extends BaseUnitTestCase { +@BaseUnitTest +public class NamingStrategyTest { private ServiceRegistry serviceRegistry; - @Before + @BeforeEach public void setUp() { serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry( Environment.getProperties() ); } - @After + @AfterEach public void tearDown() { if ( serviceRegistry != null ) { ServiceRegistryBuilder.destroy( serviceRegistry ); @@ -47,10 +47,10 @@ public void tearDown() { } @Test - public void testWithCustomNamingStrategy() throws Exception { + public void testWithCustomNamingStrategy() { new MetadataSources( serviceRegistry ) - .addAnnotatedClass(Address.class) - .addAnnotatedClass(Person.class) + .addAnnotatedClass( Address.class ) + .addAnnotatedClass( Person.class ) .getMetadataBuilder() .applyPhysicalNamingStrategy( new DummyNamingStrategy() ) .build(); @@ -59,7 +59,7 @@ public void testWithCustomNamingStrategy() throws Exception { @Test public void testWithUpperCaseNamingStrategy() throws Exception { Metadata metadata = new MetadataSources( serviceRegistry ) - .addAnnotatedClass(A.class) + .addAnnotatedClass( A.class ) .getMetadataBuilder() .applyPhysicalNamingStrategy( new PhysicalNamingStrategyStandardImpl() { @Override @@ -71,14 +71,14 @@ public Identifier toPhysicalColumnName( .build(); PersistentClass entityBinding = metadata.getEntityBinding( A.class.getName() ); - assertEquals("NAME", - ((Selectable) entityBinding.getProperty( "name" ).getSelectables().get( 0 ) ).getText()); - assertEquals("VALUE", - ((Selectable) entityBinding.getProperty( "value" ).getSelectables().get( 0 ) ).getText()); + assertThat( entityBinding.getProperty( "name" ).getSelectables().get( 0 ).getText() ) + .isEqualTo( "NAME" ); + assertThat( entityBinding.getProperty( "value" ).getSelectables().get( 0 ).getText() ) + .isEqualTo( "VALUE" ); } @Test - public void testWithJpaCompliantNamingStrategy() throws Exception { + public void testWithJpaCompliantNamingStrategy() { Metadata metadata = new MetadataSources( serviceRegistry ) .addAnnotatedClass( A.class ) .addAnnotatedClass( AddressEntry.class ) @@ -87,15 +87,15 @@ public void testWithJpaCompliantNamingStrategy() throws Exception { .build(); Collection collectionBinding = metadata.getCollectionBinding( A.class.getName() + ".address" ); - assertEquals( - "Expecting A#address collection table name (implicit) to be [A_address] per JPA spec (section 11.1.8)", - "A_ADDRESS", - collectionBinding.getCollectionTable().getQuotedName().toUpperCase(Locale.ROOT) - ); + assertThat( collectionBinding.getCollectionTable().getQuotedName().toUpperCase( Locale.ROOT ) ) + .describedAs( + "Expecting A#address collection table name (implicit) to be [A_address] per JPA spec (section 11.1.8)" + ) + .isEqualTo( "A_ADDRESS" ); } @Test - public void testWithoutCustomNamingStrategy() throws Exception { + public void testWithoutCustomNamingStrategy() { new MetadataSources( serviceRegistry ) .addAnnotatedClass( Address.class ) .addAnnotatedClass( Person.class ) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/charset/AbstractCharsetNamingStrategyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/charset/AbstractCharsetNamingStrategyTest.java index 35f4de1d5086..9bf628ad25e3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/charset/AbstractCharsetNamingStrategyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/charset/AbstractCharsetNamingStrategyTest.java @@ -4,40 +4,41 @@ */ package org.hibernate.orm.test.annotations.namingstrategy.charset; -import java.util.Map; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Index; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; import jakarta.persistence.UniqueConstraint; - import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Environment; import org.hibernate.internal.util.PropertiesHelper; +import org.hibernate.orm.test.annotations.namingstrategy.LongIdentifierNamingStrategy; import org.hibernate.service.ServiceRegistry; - import org.hibernate.testing.ServiceRegistryBuilder; +import org.hibernate.testing.orm.junit.BaseUnitTest; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.hibernate.orm.test.annotations.namingstrategy.LongIdentifierNamingStrategy; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; /** * @author Vlad Mihalcea */ -@JiraKey( value = "HHH-12357" ) -public abstract class AbstractCharsetNamingStrategyTest extends BaseUnitTestCase { +@JiraKey(value = "HHH-12357") +@BaseUnitTest +public abstract class AbstractCharsetNamingStrategyTest { protected ServiceRegistry serviceRegistry; - @Before + @BeforeAll public void setUp() { Map properties = PropertiesHelper.map( Environment.getProperties() ); properties.put( AvailableSettings.HBM2DDL_CHARSET_NAME, charsetName() ); @@ -46,29 +47,33 @@ public void setUp() { protected abstract String charsetName(); - @After + @AfterAll public void tearDown() { if ( serviceRegistry != null ) { ServiceRegistryBuilder.destroy( serviceRegistry ); } } + @Test - public void testWithCustomNamingStrategy() throws Exception { + public void testWithCustomNamingStrategy() { Metadata metadata = new MetadataSources( serviceRegistry ) - .addAnnotatedClass(Address.class) - .addAnnotatedClass(Person.class) + .addAnnotatedClass( Address.class ) + .addAnnotatedClass( Person.class ) .getMetadataBuilder() .applyImplicitNamingStrategy( new LongIdentifierNamingStrategy() ) .build(); - var uniqueKey = metadata.getEntityBinding(Address.class.getName()).getTable().getUniqueKeys().values().iterator().next(); - assertEquals( expectedUniqueKeyName(), uniqueKey.getName() ); + var uniqueKey = metadata.getEntityBinding( Address.class.getName() ).getTable().getUniqueKeys().values() + .iterator().next(); + assertThat( uniqueKey.getName() ).isEqualTo( expectedUniqueKeyName() ); - var foreignKey = metadata.getEntityBinding(Address.class.getName()).getTable().getForeignKeyCollection().iterator().next(); - assertEquals( expectedForeignKeyName(), foreignKey.getName() ); + var foreignKey = metadata.getEntityBinding( Address.class.getName() ).getTable().getForeignKeyCollection() + .iterator().next(); + assertThat( foreignKey.getName() ).isEqualTo( expectedForeignKeyName() ); - var index = metadata.getEntityBinding(Address.class.getName()).getTable().getIndexes().values().iterator().next(); - assertEquals( expectedIndexName(), index.getName() ); + var index = metadata.getEntityBinding( Address.class.getName() ).getTable().getIndexes().values().iterator() + .next(); + assertThat( index.getName() ).isEqualTo( expectedIndexName() ); } protected abstract String expectedUniqueKeyName(); @@ -82,7 +87,7 @@ public void testWithCustomNamingStrategy() throws Exception { columnNames = { "city", "stradă" }), - indexes = @Index( columnList = "city, stradă") + indexes = @Index(columnList = "city, stradă") ) public class Address { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Child.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Child.java index 71f58e5f116e..ac04a12f98e7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Child.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Child.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.onetomany; + import java.io.Serializable; import jakarta.persistence.Column; import jakarta.persistence.Entity; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/City.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/City.java index b10d996a7f7d..4eb07e2cf46c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/City.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/City.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.onetomany; + import java.util.ArrayList; import java.util.List; import jakarta.persistence.Entity; @@ -67,7 +68,7 @@ public void setMainStreets(List streets) { } public void addMainStreet(Street street) { - if ( mainStreets == null ) mainStreets = new ArrayList(); + if ( mainStreets == null ) mainStreets = new ArrayList<>(); mainStreets.add( street ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/DefaultNullOrderingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/DefaultNullOrderingTest.java index f1ccf192e2a2..d9c74b743d08 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/DefaultNullOrderingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/DefaultNullOrderingTest.java @@ -4,25 +4,27 @@ */ package org.hibernate.orm.test.annotations.onetomany; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Nulls; import jakarta.persistence.criteria.Root; - -import org.junit.Assert; -import org.junit.Test; - import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; 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.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.SettingProvider; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Lukasz Antoniak @@ -30,20 +32,32 @@ @JiraKey(value = "HHH-465") @RequiresDialect(value = H2Dialect.class, comment = "By default H2 places NULL values first, so testing 'NULLS LAST' expression.") -public class DefaultNullOrderingTest extends BaseCoreFunctionalTestCase { - @Override - protected void configure(Configuration configuration) { - configuration.setProperty( AvailableSettings.DEFAULT_NULL_ORDERING, Nulls.LAST ); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Monkey.class, Troop.class, Soldier.class }; +@DomainModel( + annotatedClasses = { + Monkey.class, + Troop.class, + Soldier.class + } +) +@SessionFactory +@ServiceRegistry( + settingProviders = @SettingProvider( + settingName = AvailableSettings.DEFAULT_NULL_ORDERING, + provider = DefaultNullOrderingTest.NullOrderingProvider.class) +) +public class DefaultNullOrderingTest { + + public static class NullOrderingProvider implements SettingProvider.Provider { + + @Override + public Nulls getSetting() { + return Nulls.LAST; + } } @Test - public void testHqlDefaultNullOrdering() { - inSession( session -> { + public void testHqlDefaultNullOrdering(SessionFactoryScope scope) { + scope.inSession( session -> { // Populating database with test data. try { session.getTransaction().begin(); @@ -56,9 +70,9 @@ public void testHqlDefaultNullOrdering() { session.getTransaction().commit(); session.getTransaction().begin(); - List orderedResults = (List) session.createQuery( "from Monkey m order by m.name" ) + List orderedResults = session.createQuery( "from Monkey m order by m.name", Monkey.class ) .list(); // Should order by NULLS LAST. - Assert.assertEquals( Arrays.asList( monkey2, monkey1 ), orderedResults ); + assertThat( orderedResults ).isEqualTo( Arrays.asList( monkey2, monkey1 ) ); session.getTransaction().commit(); session.clear(); @@ -69,18 +83,17 @@ public void testHqlDefaultNullOrdering() { session.remove( monkey2 ); session.getTransaction().commit(); } - catch (Exception e) { + finally { if ( session.getTransaction().isActive() ) { session.getTransaction().rollback(); } - throw e; } } ); } @Test - public void testAnnotationsDefaultNullOrdering() { - inSession( + public void testAnnotationsDefaultNullOrdering(SessionFactoryScope scope) { + scope.inSession( session -> { try { // Populating database with test data. @@ -99,10 +112,10 @@ public void testAnnotationsDefaultNullOrdering() { session.clear(); session.getTransaction().begin(); - troop = (Troop) session.get( Troop.class, troop.getId() ); + troop = session.find( Troop.class, troop.getId() ); Iterator iterator = troop.getSoldiers().iterator(); // Should order by NULLS LAST. - Assert.assertEquals( ranger.getName(), iterator.next().getName() ); - Assert.assertNull( iterator.next().getName() ); + assertThat( iterator.next().getName() ).isEqualTo( ranger.getName() ); + assertThat( iterator.next().getName() ).isNull(); session.getTransaction().commit(); session.clear(); @@ -112,21 +125,20 @@ public void testAnnotationsDefaultNullOrdering() { session.remove( troop ); session.getTransaction().commit(); } - catch (Exception e) { + finally { if ( session.getTransaction().isActive() ) { session.getTransaction().rollback(); } - throw e; } } ); } @Test - public void testCriteriaDefaultNullOrdering() { - inSession( + public void testCriteriaDefaultNullOrdering(SessionFactoryScope scope) { + scope.inSession( session -> { - try{ + try { // Populating database with test data. session.getTransaction().begin(); Monkey monkey1 = new Monkey(); @@ -143,7 +155,8 @@ public void testCriteriaDefaultNullOrdering() { Root root = criteria.from( Monkey.class ); criteria.orderBy( criteriaBuilder.asc( root.get( "name" ) ) ); - Assert.assertEquals( Arrays.asList( monkey2, monkey1 ), session.createQuery( criteria ).list() ); + assertThat( session.createQuery( criteria ).list() ) + .isEqualTo( Arrays.asList( monkey2, monkey1 ) ); // Criteria criteria = session.createCriteria( Monkey.class ); // criteria.addOrder( org.hibernate.criterion.Order.asc( "name" ) ); // Should order by NULLS LAST. @@ -158,11 +171,10 @@ public void testCriteriaDefaultNullOrdering() { session.remove( monkey2 ); session.getTransaction().commit(); } - catch (Exception e) { + finally { if ( session.getTransaction().isActive() ) { session.getTransaction().rollback(); } - throw e; } } ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Model.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Model.java index f18726edf90e..79a10d2130e7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Model.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Model.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.onetomany; + import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Monkey.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Monkey.java index 8f8415726cee..91b1f72223ca 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Monkey.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Monkey.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.onetomany; + import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/OneToManyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/OneToManyTest.java index 6aa474f18c8b..2a516a07ec11 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/OneToManyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/OneToManyTest.java @@ -4,28 +4,14 @@ */ package org.hibernate.orm.test.annotations.onetomany; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeSet; import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.OneToMany; -import jakarta.persistence.PersistenceException; - import org.hibernate.AnnotationException; import org.hibernate.Hibernate; -import org.hibernate.Session; -import org.hibernate.Transaction; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; import org.hibernate.boot.MetadataSources; @@ -36,31 +22,36 @@ import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Table; import org.hibernate.metamodel.CollectionClassification; - -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.hibernate.testing.util.ServiceRegistryUtil; - import org.hibernate.orm.test.annotations.Customer; import org.hibernate.orm.test.annotations.Discount; import org.hibernate.orm.test.annotations.Passport; import org.hibernate.orm.test.annotations.Ticket; import org.hibernate.orm.test.annotations.TicketComparator; -import org.junit.Assert; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DialectFeatureChecks; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialectFeature; +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.SettingProvider; +import org.hibernate.testing.util.ServiceRegistryUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Fail.fail; import static org.hibernate.cfg.AvailableSettings.DEFAULT_LIST_SEMANTICS; -import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; -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; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * Test various case of a one to many relationship. @@ -68,335 +59,382 @@ * @author Emmanuel Bernard * @author Hardy Ferentschik */ -@SuppressWarnings("unchecked") -public class OneToManyTest extends BaseNonConfigCoreFunctionalTestCase { - @Test - public void testColumnDefinitionPropagation() throws Exception { - Session s; - s = openSession(); - s.getTransaction().begin(); - Politician casimir = new Politician(); - casimir.setName( "Casimir" ); - PoliticalParty dream = new PoliticalParty(); - dream.setName( "Dream" ); - dream.addPolitician( casimir ); - s.persist( dream ); - s.getTransaction().commit(); - s.clear(); - - Transaction tx = s.beginTransaction(); - s.remove( s.get( PoliticalParty.class, dream.getName() ) ); - tx.commit(); - s.close(); +@DomainModel( + annotatedClasses = { + Troop.class, + Soldier.class, + Customer.class, + Ticket.class, + Discount.class, + Passport.class, + Parent.class, + Child.class, + Trainer.class, + Tiger.class, + Monkey.class, + City.class, + Street.class, + PoliticalParty.class, + Politician.class, + Person.class, + Organisation.class, + OrganisationUser.class, + Model.class, + OneToManyTest.OnDeleteUnidirectionalOneToManyParent.class, + OneToManyTest.OnDeleteUnidirectionalOneToManyChild.class + }, + xmlMappings = "org/hibernate/orm/test/annotations/onetomany/orm.xml" +) +@SessionFactory +@ServiceRegistry( + settingProviders = @SettingProvider( + settingName = DEFAULT_LIST_SEMANTICS, + provider = OneToManyTest.ListSemanticProvider.class + ) +) +public class OneToManyTest { + + public static class ListSemanticProvider implements SettingProvider.Provider { + + @Override + public CollectionClassification getSetting() { + return CollectionClassification.BAG; + } + } + + @AfterEach + public void afterEach(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Test - public void testListWithBagSemanticAndOrderBy() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - City paris = new City(); - paris.setName( "Paris" ); - s.persist( paris ); - Street rochechoir = new Street(); - rochechoir.setStreetName( "Rochechoir" ); - rochechoir.setCity( paris ); - Street chmpsElysees = new Street(); - chmpsElysees.setStreetName( "Champs Elysees" ); - chmpsElysees.setCity( paris ); - Street grandeArmee = new Street(); - grandeArmee.setStreetName( "Grande Armee" ); - grandeArmee.setCity( paris ); - s.persist( rochechoir ); - s.persist( chmpsElysees ); - s.persist( grandeArmee ); - paris.addMainStreet( chmpsElysees ); - paris.addMainStreet( grandeArmee ); - - s.flush(); - s.clear(); - - // Assert the primary key value relationship amongst the 3 streets... - Assert.assertTrue( rochechoir.getId() < chmpsElysees.getId() ); - Assert.assertTrue( chmpsElysees.getId() < grandeArmee.getId() ); - - paris = ( City ) s.get( City.class, paris.getId() ); - - // City.streets is defined to be ordered by name primarily... - assertEquals( 3, paris.getStreets().size() ); - assertEquals( chmpsElysees.getStreetName(), paris.getStreets().get( 0 ).getStreetName() ); - assertEquals( grandeArmee.getStreetName(), paris.getStreets().get( 1 ).getStreetName() ); - // City.mainStreets is defined to be ordered by street id - List mainStreets = paris.getMainStreets(); - assertEquals( 2, mainStreets.size() ); - Integer previousId = -1; - for ( Street street : mainStreets ) { - assertTrue( previousId < street.getId() ); - previousId = street.getId(); - } - tx.rollback(); - s.close(); + public void testColumnDefinitionPropagation(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Politician casimir = new Politician(); + casimir.setName( "Casimir" ); + PoliticalParty dream = new PoliticalParty(); + dream.setName( "Dream" ); + dream.addPolitician( casimir ); + session.persist( dream ); + session.getTransaction().commit(); + session.clear(); + + session.beginTransaction(); + session.remove( session.find( PoliticalParty.class, dream.getName() ) ); + } + ); + } + @Test + public void testListWithBagSemanticAndOrderBy(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + City paris = new City(); + paris.setName( "Paris" ); + session.persist( paris ); + Street rochechoir = new Street(); + rochechoir.setStreetName( "Rochechoir" ); + rochechoir.setCity( paris ); + Street chmpsElysees = new Street(); + chmpsElysees.setStreetName( "Champs Elysees" ); + chmpsElysees.setCity( paris ); + Street grandeArmee = new Street(); + grandeArmee.setStreetName( "Grande Armee" ); + grandeArmee.setCity( paris ); + session.persist( rochechoir ); + session.persist( chmpsElysees ); + session.persist( grandeArmee ); + paris.addMainStreet( chmpsElysees ); + paris.addMainStreet( grandeArmee ); + + session.flush(); + session.clear(); + + // Assert the primary key value relationship amongst the 3 streets... + assertThat( rochechoir.getId() ).isLessThan( chmpsElysees.getId() ); + assertThat( chmpsElysees.getId() ).isLessThan( grandeArmee.getId() ); + + paris = session.find( City.class, paris.getId() ); + + // City.streets is defined to be ordered by name primarily... + assertThat( paris.getStreets().size() ).isEqualTo( 3 ); + assertThat( paris.getStreets().get( 0 ).getStreetName() ).isEqualTo( chmpsElysees.getStreetName() ); + assertThat( paris.getStreets().get( 1 ).getStreetName() ).isEqualTo( grandeArmee.getStreetName() ); + // City.mainStreets is defined to be ordered by street id + List mainStreets = paris.getMainStreets(); + assertThat( mainStreets.size() ).isEqualTo( 2 ); + Integer previousId = -1; + for ( Street street : mainStreets ) { + assertThat( previousId ).isLessThan( street.getId() ); + previousId = street.getId(); + } + } + ); } @Test - public void testUnidirectionalDefault() throws Exception { - Session s; - Transaction tx; - Trainer trainer = new Trainer(); - trainer.setName( "First trainer" ); + public void testUnidirectionalDefault(SessionFactoryScope scope) { + Trainer t = new Trainer(); + t.setName( "First trainer" ); Tiger regularTiger = new Tiger(); regularTiger.setName( "Regular Tiger" ); Tiger whiteTiger = new Tiger(); whiteTiger.setName( "White Tiger" ); - trainer.setTrainedTigers( new HashSet() ); - s = openSession(); - tx = s.beginTransaction(); - s.persist( trainer ); - s.persist( regularTiger ); - s.persist( whiteTiger ); - trainer.getTrainedTigers().add( regularTiger ); - trainer.getTrainedTigers().add( whiteTiger ); - - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - trainer = s.get( Trainer.class, trainer.getId() ); - assertNotNull( trainer ); - assertNotNull( trainer.getTrainedTigers() ); - assertEquals( 2, trainer.getTrainedTigers().size() ); - tx.rollback(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - trainer = new Trainer(); - trainer.setName( "new trainer" ); - trainer.setTrainedTigers( new HashSet<>() ); - trainer.getTrainedTigers().add( whiteTiger ); - try { - s.persist( trainer ); - tx.commit(); - fail( "A one to many should not allow several trainer per Tiger" ); - } - catch (PersistenceException ce) { - try { - assertTyping( ConstraintViolationException.class, ce ); - //success - - } - finally { - tx.rollback(); - } - } - s.close(); + t.setTrainedTigers( new HashSet<>() ); + scope.inTransaction( + session -> { + session.persist( t ); + session.persist( regularTiger ); + session.persist( whiteTiger ); + t.getTrainedTigers().add( regularTiger ); + t.getTrainedTigers().add( whiteTiger ); + } + ); + + scope.inTransaction( + session -> { + Trainer trainer = session.find( Trainer.class, t.getId() ); + assertThat( trainer ).isNotNull(); + assertThat( trainer.getTrainedTigers() ).isNotNull(); + assertThat( trainer.getTrainedTigers().size() ).isEqualTo( 2 ); + } + ); + + assertThrows( ConstraintViolationException.class, () -> scope.inSession( + session -> { + Trainer trainer = new Trainer(); + trainer.setName( "new trainer" ); + trainer.setTrainedTigers( new HashSet<>() ); + trainer.getTrainedTigers().add( whiteTiger ); + try { + session.getTransaction().begin(); + session.persist( trainer ); + session.getTransaction().commit(); + fail( "A one to many should not allow several trainer per Tiger" ); + } + finally { + if ( session.getTransaction().isActive() ) { + session.getTransaction().rollback(); + } + } + } + ) ); } @Test - public void testUnidirectionalExplicit() throws Exception { - Session s; - Transaction tx; - Trainer trainer = new Trainer(); - trainer.setName( "First trainer" ); + public void testUnidirectionalExplicit(SessionFactoryScope scope) { + Trainer t = new Trainer(); + t.setName( "First trainer" ); Monkey regularMonkey = new Monkey(); regularMonkey.setName( "Regular Monkey" ); Monkey miniMonkey = new Monkey(); miniMonkey.setName( "Mini Monkey" ); - trainer.setTrainedMonkeys( new HashSet() ); - s = openSession(); - tx = s.beginTransaction(); - s.persist( trainer ); - s.persist( regularMonkey ); - s.persist( miniMonkey ); - trainer.getTrainedMonkeys().add( regularMonkey ); - trainer.getTrainedMonkeys().add( miniMonkey ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - trainer = s.get( Trainer.class, trainer.getId() ); - assertNotNull( trainer ); - assertNotNull( trainer.getTrainedMonkeys() ); - assertEquals( 2, trainer.getTrainedMonkeys().size() ); - - //test suppression of trainer wo monkey - final Set monkeySet = new HashSet( trainer.getTrainedMonkeys() ); - s.remove( trainer ); - s.flush(); - tx.commit(); - - s.clear(); - - tx = s.beginTransaction(); - for ( Monkey m : monkeySet ) { - final Object managedMonkey = s.get( Monkey.class, m.getId() ); - assertNotNull( "No trainers but monkeys should still be here", managedMonkey ); - } - - //clean up - for ( Monkey m : monkeySet ) { - final Object managedMonkey = s.get( Monkey.class, m.getId() ); - s.remove(managedMonkey); - } - s.flush(); - tx.commit(); - s.close(); + t.setTrainedMonkeys( new HashSet<>() ); + scope.inTransaction( + session -> { + session.persist( t ); + session.persist( regularMonkey ); + session.persist( miniMonkey ); + t.getTrainedMonkeys().add( regularMonkey ); + t.getTrainedMonkeys().add( miniMonkey ); + } + ); + + scope.inTransaction( + session -> { + Trainer trainer = session.find( Trainer.class, t.getId() ); + assertThat( trainer ).isNotNull(); + assertThat( trainer.getTrainedMonkeys() ).isNotNull(); + assertThat( trainer.getTrainedMonkeys().size() ).isEqualTo( 2 ); + + //test suppression of trainer wo monkey + final Set monkeySet = new HashSet<>( trainer.getTrainedMonkeys() ); + session.remove( trainer ); + session.flush(); + session.getTransaction().commit(); + + session.clear(); + + session.beginTransaction(); + for ( Monkey m : monkeySet ) { + final Object managedMonkey = session.find( Monkey.class, m.getId() ); + assertThat( managedMonkey ) + .describedAs( "No trainers but monkeys should still be here" ) + .isNotNull(); + } + + //clean up + for ( Monkey m : monkeySet ) { + final Object managedMonkey = session.find( Monkey.class, m.getId() ); + session.remove( managedMonkey ); + } + session.flush(); + } + ); } @Test - public void testFetching() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - Troop t = new Troop(); - t.setName( "Final cut" ); - Soldier vandamme = new Soldier(); - vandamme.setName( "JC Vandamme" ); - t.addSoldier( vandamme ); + public void testFetching(SessionFactoryScope scope) { + Troop troop = new Troop(); Soldier rambo = new Soldier(); - rambo.setName( "Rambo" ); - t.addSoldier( rambo ); - s.persist( t ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - t = s.get( Troop.class, t.getId() ); - assertNotNull( t.getSoldiers() ); - assertFalse( Hibernate.isInitialized( t.getSoldiers() ) ); - assertEquals( 2, t.getSoldiers().size() ); - assertEquals( rambo.getName(), t.getSoldiers().iterator().next().getName() ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - t = ( Troop ) s.createQuery( "from " + Troop.class.getName() + " as t where t.id = :id" ) - .setParameter( "id", t.getId() ).uniqueResult(); - assertFalse( Hibernate.isInitialized( t.getSoldiers() ) ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - rambo = s.get( Soldier.class, rambo.getId() ); - assertTrue( Hibernate.isInitialized( rambo.getTroop() ) ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - rambo = ( Soldier ) s.createQuery( "from " + Soldier.class.getName() + " as s where s.id = :rid" ) - .setParameter( "rid", rambo.getId() ).uniqueResult(); - assertTrue( "fetching strategy used when we do query", Hibernate.isInitialized( rambo.getTroop() ) ); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + troop.setName( "Final cut" ); + Soldier vandamme = new Soldier(); + vandamme.setName( "JC Vandamme" ); + troop.addSoldier( vandamme ); + rambo.setName( "Rambo" ); + troop.addSoldier( rambo ); + session.persist( troop ); + } + ); + + scope.inTransaction( + session -> { + Troop t = session.find( Troop.class, troop.getId() ); + assertThat( t.getSoldiers() ).isNotNull(); + assertThat( Hibernate.isInitialized( t.getSoldiers() ) ).isFalse(); + assertThat( t.getSoldiers().size() ).isEqualTo( 2 ); + assertThat( t.getSoldiers().iterator().next().getName() ).isEqualTo( rambo.getName() ); + } + ); + + scope.inTransaction( + session -> { + Troop t = session.createQuery( "from " + Troop.class.getName() + " as t where t.id = :id", + Troop.class ) + .setParameter( "id", troop.getId() ).uniqueResult(); + assertThat( Hibernate.isInitialized( t.getSoldiers() ) ).isFalse(); + } + ); + + scope.inTransaction( + session -> { + Soldier r = session.find( Soldier.class, rambo.getId() ); + assertThat( Hibernate.isInitialized( r.getTroop() ) ).isTrue(); + } + ); + + scope.inTransaction( + session -> { + Soldier r = session.createQuery( "from " + Soldier.class.getName() + " as s where s.id = :rid", + Soldier.class ) + .setParameter( "rid", rambo.getId() ) + .uniqueResult(); + assertThat( Hibernate.isInitialized( r.getTroop() ) ) + .describedAs( "fetching strategy used when we do query" ) + .isTrue(); + } + ); } @Test - public void testCascadeDeleteOrphan() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); + public void testCascadeDeleteOrphan(SessionFactoryScope scope) { Troop disney = new Troop(); - disney.setName( "Disney" ); Soldier mickey = new Soldier(); - mickey.setName( "Mickey" ); - disney.addSoldier( mickey ); - s.persist( disney ); - tx.commit(); - s.close(); - s = openSession(); - tx = s.beginTransaction(); - Troop troop = s.get( Troop.class, disney.getId() ); - Soldier soldier = troop.getSoldiers().iterator().next(); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + disney.setName( "Disney" ); + mickey.setName( "Mickey" ); + disney.addSoldier( mickey ); + session.persist( disney ); + } + ); + + Troop troop = scope.fromTransaction( + session -> { + Troop t = session.find( Troop.class, disney.getId() ); + t.getSoldiers().iterator().next(); + return t; + } + ); + troop.getSoldiers().clear(); - s = openSession(); - tx = s.beginTransaction(); - s.merge( troop ); - tx.commit(); - s.close(); - s = openSession(); - tx = s.beginTransaction(); - soldier = s.get( Soldier.class, mickey.getId() ); - assertNull( "delete-orphan should work", soldier ); - troop = s.get( Troop.class, disney.getId() ); - s.remove( troop ); - tx.commit(); - s.close(); + + scope.inTransaction( + session -> + session.merge( troop ) + ); + + scope.inTransaction( + session -> { + Soldier soldier = session.find( Soldier.class, mickey.getId() ); + assertThat( soldier ) + .describedAs( "delete-orphan should work" ) + .isNull(); + session.remove( session.find( Troop.class, disney.getId() ) ); + } + ); } @Test - public void testCascadeDelete() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); + public void testCascadeDelete(SessionFactoryScope scope) { Troop disney = new Troop(); - disney.setName( "Disney" ); Soldier mickey = new Soldier(); - mickey.setName( "Mickey" ); - disney.addSoldier( mickey ); - s.persist( disney ); - tx.commit(); - s.close(); - s = openSession(); - tx = s.beginTransaction(); - Troop troop = s.get( Troop.class, disney.getId() ); - s.remove( troop ); - tx.commit(); - s.close(); - s = openSession(); - tx = s.beginTransaction(); - Soldier soldier = ( Soldier ) s.get( Soldier.class, mickey.getId() ); - assertNull( "delete-orphan should work", soldier ); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + disney.setName( "Disney" ); + mickey.setName( "Mickey" ); + disney.addSoldier( mickey ); + session.persist( disney ); + } + ); + scope.inTransaction( + session -> { + Troop troop = session.find( Troop.class, disney.getId() ); + session.remove( troop ); + } + ); + + scope.inTransaction( + session -> { + Soldier soldier = session.find( Soldier.class, mickey.getId() ); + assertThat( soldier ) + .describedAs( "delete-orphan should work" ) + .isNull(); + } + ); } @Test - @RequiresDialectFeature(DialectChecks.SupportsCascadeDeleteCheck.class) - public void testCascadeDeleteWithUnidirectionalAssociation() throws Exception { + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsCascadeDeleteCheck.class) + public void testCascadeDeleteWithUnidirectionalAssociation(SessionFactoryScope scope) { OnDeleteUnidirectionalOneToManyChild child = new OnDeleteUnidirectionalOneToManyChild(); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { OnDeleteUnidirectionalOneToManyParent parent = new OnDeleteUnidirectionalOneToManyParent(); - parent.children = Collections.singletonList( child); + parent.children = Collections.singletonList( child ); session.persist( parent ); } ); - doInHibernate( this::sessionFactory, session -> { - session.createQuery("delete from OnDeleteUnidirectionalOneToManyParent").executeUpdate(); - } ); + scope.inTransaction( session -> + session.createMutationQuery( "delete from OnDeleteUnidirectionalOneToManyParent" ).executeUpdate() + ); - doInHibernate( this::sessionFactory, session -> { - OnDeleteUnidirectionalOneToManyChild e1 = session.get( OnDeleteUnidirectionalOneToManyChild.class, child.id ); - assertNull( "delete cascade should work", e1 ); + scope.inTransaction( session -> { + OnDeleteUnidirectionalOneToManyChild e1 = session.find( + OnDeleteUnidirectionalOneToManyChild.class, + child.id ); + assertThat( e1 ).describedAs( "delete cascade should work" ).isNull(); } ); } @Test - public void testOnDeleteWithoutJoinColumn() throws Exception { + public void testOnDeleteWithoutJoinColumn() { StandardServiceRegistry serviceRegistry = ServiceRegistryUtil.serviceRegistry(); try { - new MetadataSources( serviceRegistry ) - .addAnnotatedClass( OnDeleteUnidirectionalOneToMany.class ) - .addAnnotatedClass( ParentUnawareChild.class ) - .getMetadataBuilder() - .build(); - } - catch ( AnnotationException e ) { - assertTrue(e.getMessage().contains( "is annotated '@OnDelete' and must explicitly specify a '@JoinColumn'" )); + AnnotationException e = assertThrows( AnnotationException.class, + () -> new MetadataSources( serviceRegistry ) + .addAnnotatedClass( OnDeleteUnidirectionalOneToMany.class ) + .addAnnotatedClass( ParentUnawareChild.class ) + .getMetadataBuilder() + .build() + ); + assertThat( e.getMessage() ) + .contains( "is annotated '@OnDelete' and must explicitly specify a '@JoinColumn'" ); + } finally { StandardServiceRegistryBuilder.destroy( serviceRegistry ); @@ -404,179 +442,136 @@ public void testOnDeleteWithoutJoinColumn() throws Exception { } @Test - public void testSimpleOneToManySet() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - Ticket t = new Ticket(); - t.setNumber( "33A" ); + public void testSimpleOneToManySet(SessionFactoryScope scope) { + Customer customer = new Customer(); Ticket t2 = new Ticket(); - t2.setNumber( "234ER" ); - Customer c = new Customer(); - s.persist( c ); - //s.persist(t); - SortedSet tickets = new TreeSet( new TicketComparator() ); - tickets.add( t ); - tickets.add( t2 ); - c.setTickets( tickets ); - - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - c = ( Customer ) s.getReference( Customer.class, c.getId() ); - assertNotNull( c ); - assertTrue( Hibernate.isInitialized( c.getTickets() ) ); - assertNotNull( c.getTickets() ); - tickets = c.getTickets(); - assertTrue( tickets.size() > 0 ); - assertEquals( t2.getNumber(), c.getTickets().first().getNumber() ); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + Ticket t = new Ticket(); + t.setNumber( "33A" ); + t2.setNumber( "234ER" ); + session.persist( customer ); + //s.persist(t); + SortedSet tickets = new TreeSet<>( new TicketComparator() ); + tickets.add( t ); + tickets.add( t2 ); + customer.setTickets( tickets ); + } + ); + + scope.inTransaction( + session -> { + Customer c = session.getReference( Customer.class, customer.getId() ); + assertThat( c ).isNotNull(); + assertThat( Hibernate.isInitialized( c.getTickets() ) ).isTrue(); + assertThat( c.getTickets() ).isNotNull(); + SortedSet tickets = c.getTickets(); + assertThat( tickets.size() ).isGreaterThan( 0 ); + assertThat( c.getTickets().first().getNumber() ).isEqualTo( t2.getNumber() ); + } + ); } @Test - public void testSimpleOneToManyCollection() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - Discount d = new Discount(); - d.setDiscount( 10 ); + public void testSimpleOneToManyCollection(SessionFactoryScope scope) { Customer c = new Customer(); - List discounts = new ArrayList(); - discounts.add( d ); - d.setOwner( c ); - c.setDiscountTickets( discounts ); - s.persist( c ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - c = ( Customer ) s.getReference( Customer.class, c.getId() ); - assertNotNull( c ); - assertFalse( Hibernate.isInitialized( c.getDiscountTickets() ) ); - assertNotNull( c.getDiscountTickets() ); - Collection collecDiscount = c.getDiscountTickets(); - assertTrue( collecDiscount.size() > 0 ); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + Discount d = new Discount(); + d.setDiscount( 10 ); + List discounts = new ArrayList<>(); + discounts.add( d ); + d.setOwner( c ); + c.setDiscountTickets( discounts ); + session.persist( c ); + } + ); + + scope.inTransaction( + session -> { + Customer customer = session.getReference( Customer.class, c.getId() ); + assertThat( customer ).isNotNull(); + assertThat( Hibernate.isInitialized( customer.getDiscountTickets() ) ) + .isFalse(); + assertThat( customer.getDiscountTickets() ).isNotNull(); + Collection collecDiscount = customer.getDiscountTickets(); + assertThat( collecDiscount.size() ).isGreaterThan( 0 ); + } + ); } @Test - public void testJoinColumns() throws Exception { - Parent parent = new Parent(); + public void testJoinColumns(SessionFactoryScope scope) { + Parent p = new Parent(); ParentPk pk = new ParentPk(); pk.firstName = "Bruce"; pk.lastName = "Willis"; pk.isMale = true; - parent.id = pk; - parent.age = 40; + p.id = pk; + p.age = 40; Child child = new Child(); Child child2 = new Child(); - parent.addChild( child ); - parent.addChild( child2 ); - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - s.persist( parent ); - tx.commit(); - s.close(); - - assertNotNull( child.id ); - assertNotNull( child2.id ); - assertNotSame( child.id, child2.id ); - - s = openSession(); - tx = s.beginTransaction(); - parent = ( Parent ) s.get( Parent.class, pk ); - assertNotNull( parent.children ); - Hibernate.initialize( parent.children ); - assertEquals( 2, parent.children.size() ); - tx.commit(); - s.close(); + p.addChild( child ); + p.addChild( child2 ); + scope.inTransaction( + session -> + session.persist( p ) + ); + + assertThat( child.id ).isNotNull(); + assertThat( child2.id ).isNotNull(); + assertThat( child.id ).isNotSameAs( child2.id ); + + scope.inTransaction( + session -> { + Parent parent = session.find( Parent.class, pk ); + assertThat( parent.children ).isNotNull(); + Hibernate.initialize( parent.children ); + assertThat( parent.children.size() ).isEqualTo( 2 ); + } + ); } @Test - @JiraKey( value = "HHH-4394" ) - public void testOrderByOnSuperclassProperty() { + @JiraKey(value = "HHH-4394") + public void testOrderByOnSuperclassProperty(SessionFactoryScope scope) { OrganisationUser user = new OrganisationUser(); user.setFirstName( "Emmanuel" ); user.setLastName( "Bernard" ); - user.setIdPerson( 1l ); + user.setIdPerson( 1L ); user.setSomeText( "SomeText" ); Organisation org = new Organisation(); - org.setIdOrganisation( 1l ); + org.setIdOrganisation( 1L ); org.setName( "S Diego Zoo" ); user.setOrganisation( org ); - Session s = openSession(); - s.getTransaction().begin(); - s.persist( user ); - s.persist( org ); - s.flush(); - s.clear(); - s.createQuery( "select org from Organisation org left join fetch org.organisationUsers" ).list(); - s.getTransaction().rollback(); - s.close(); + scope.inTransaction( + session -> { + session.persist( user ); + session.persist( org ); + session.flush(); + session.clear(); + session.createQuery( "select org from Organisation org left join fetch org.organisationUsers", + Organisation.class ) + .list(); + } + ); } @Test - @JiraKey( value = "HHH-4605" ) - public void testJoinColumnConfiguredInXml() { - PersistentClass pc = metadata().getEntityBinding( Model.class.getName() ); + @JiraKey(value = "HHH-4605") + public void testJoinColumnConfiguredInXml(SessionFactoryScope scope) { + PersistentClass pc = scope.getMetadataImplementor().getEntityBinding( Model.class.getName() ); Table table = pc.getRootTable(); - Iterator iter = table.getColumns().iterator(); boolean joinColumnFound = false; - while(iter.hasNext()) { - Column column = (Column) iter.next(); - if(column.getName().equals( "model_manufacturer_join" )) { + for ( Column column : table.getColumns() ) { + if ( column.getName().equals( "model_manufacturer_join" ) ) { joinColumnFound = true; + break; } } - assertTrue( "The mapping defines a joing column which could not be found in the metadata.", joinColumnFound ); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Troop.class, - Soldier.class, - Customer.class, - Ticket.class, - Discount.class, - Passport.class, - Parent.class, - Child.class, - Trainer.class, - Tiger.class, - Monkey.class, - City.class, - Street.class, - PoliticalParty.class, - Politician.class, - Person.class, - Organisation.class, - OrganisationUser.class, - Model.class, - OnDeleteUnidirectionalOneToManyParent.class, - OnDeleteUnidirectionalOneToManyChild.class - }; - } - - @Override - protected String[] getXmlFiles() { - return new String[] { "org/hibernate/orm/test/annotations/onetomany/orm.xml" }; - } - - @Override - protected void addSettings(Map settings) { - super.addSettings( settings ); - // needed for `#testListWithBagSemanticAndOrderBy` - settings.put( DEFAULT_LIST_SEMANTICS, CollectionClassification.BAG.name() ); + assertThat( joinColumnFound ) + .describedAs( "The mapping defines a joing column which could not be found in the metadata." ) + .isTrue(); } @Entity(name = "OnDeleteUnidirectionalOneToManyParent") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Organisation.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Organisation.java index cf68fcf568e6..deb2798253b1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Organisation.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Organisation.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.onetomany; + import java.io.Serializable; import java.util.Set; import jakarta.persistence.CascadeType; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/OrganisationUser.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/OrganisationUser.java index 9a1c0ed6ba46..167d733a5548 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/OrganisationUser.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/OrganisationUser.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.onetomany; + import java.io.Serializable; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; @@ -30,7 +31,7 @@ public void setSomeText(String someText) { this.someText = someText; } - @Column( name = "some_text", nullable=true,length=1024) + @Column( name = "some_text", length=1024) public String getSomeText() { return someText; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Parent.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Parent.java index b811b286ab36..9f518ebccfd5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Parent.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Parent.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.onetomany; + import java.io.Serializable; import java.util.HashSet; import java.util.Set; @@ -34,8 +35,8 @@ public int hashCode() { public boolean equals(Object obj) { //a NPE can occurs, but I don't expect equals to be used before pk is set - if ( obj != null && obj instanceof Parent ) { - return id.equals( ( (Parent) obj ).id ); + if ( obj instanceof Parent p ) { + return id.equals( p.id ); } else { return false; @@ -44,7 +45,7 @@ public boolean equals(Object obj) { public void addChild(Child child) { if ( children == null ) { - children = new HashSet(); + children = new HashSet<>(); } child.parent = this; children.add( child ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Person.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Person.java index 0fe9af08a590..51bebcad8ee2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Person.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Person.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.onetomany; + import java.io.Serializable; import jakarta.persistence.Column; import jakarta.persistence.Entity; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/PoliticalParty.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/PoliticalParty.java index c691d4a76b42..c617a823e839 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/PoliticalParty.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/PoliticalParty.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.onetomany; + import java.util.HashSet; import java.util.Set; import jakarta.persistence.CascadeType; @@ -17,7 +18,7 @@ @Entity public class PoliticalParty { private String name; - private Set politicians = new HashSet(); + private Set politicians = new HashSet<>(); @Id @Column(columnDefinition = "VARCHAR(60)") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Politician.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Politician.java index 583ab20c485a..5293bd2224e8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Politician.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Politician.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.onetomany; + import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Soldier.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Soldier.java index 07609da4a116..d0664bfae172 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Soldier.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Soldier.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.onetomany; + import jakarta.persistence.Entity; import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; @@ -50,13 +51,9 @@ public void setTroop(Troop troop) { @Override public boolean equals(Object o) { if ( this == o ) return true; - if ( !( o instanceof Soldier ) ) return false; - - final Soldier soldier = (Soldier) o; - - if ( name != null ? !name.equals( soldier.name ) : soldier.name != null ) return false; + if ( !(o instanceof Soldier soldier) ) return false; - return true; + return name != null ? name.equals( soldier.name ) : soldier.name == null; } @Override diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Street.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Street.java index 7665562d5298..bd31384ba3f5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Street.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Street.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.onetomany; + import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Tiger.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Tiger.java index 443bfc1523ef..e77a6de4935f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Tiger.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Tiger.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.onetomany; + import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Trainer.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Trainer.java index 4daf72408c14..dbaded46fb32 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Trainer.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Trainer.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.onetomany; + import java.util.Set; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Troop.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Troop.java index d3379652acb5..b7a62612849c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Troop.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Troop.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.onetomany; + import java.util.HashSet; import java.util.Set; import jakarta.persistence.CascadeType; @@ -58,7 +59,7 @@ public void setName(String name) { } public void addSoldier(Soldier s) { - if ( soldiers == null ) soldiers = new HashSet(); + if ( soldiers == null ) soldiers = new HashSet<>(); soldiers.add( s ); s.setTroop( this ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Address.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Address.java index fc23441b8a62..7224ab96d0c5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Address.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Address.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.onetoone; + import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Body.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Body.java index a8811c8c7e7a..92506bb3e5f5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Body.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Body.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.onetoone; + import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.OneToOne; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Client.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Client.java index c1ecb0158a0f..f06d9bf317c4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Client.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Client.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.onetoone; + import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Computer.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Computer.java index 61c3dcd95edb..a2921152728f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Computer.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Computer.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.onetoone; + import jakarta.persistence.AttributeOverride; import jakarta.persistence.AttributeOverrides; import jakarta.persistence.CascadeType; @@ -36,13 +37,9 @@ public void setSerial(SerialNumber serial) { public boolean equals(Object o) { if ( this == o ) return true; - if ( !( o instanceof Computer ) ) return false; - - final Computer computer = (Computer) o; - - if ( !id.equals( computer.id ) ) return false; + if ( !(o instanceof Computer computer) ) return false; - return true; + return id.equals( computer.id ); } public int hashCode() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Heart.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Heart.java index 5cbc21b93298..dac5702e8ad4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Heart.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Heart.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.onetoone; + import jakarta.persistence.Entity; import jakarta.persistence.Id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OneToOneJoinTableUniquenessTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OneToOneJoinTableUniquenessTest.java index 55ef6cbc4241..ea69d639af23 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OneToOneJoinTableUniquenessTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OneToOneJoinTableUniquenessTest.java @@ -4,10 +4,6 @@ */ package org.hibernate.orm.test.annotations.onetoone; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.util.List; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; @@ -17,75 +13,91 @@ import jakarta.persistence.JoinTable; import jakarta.persistence.OneToOne; import jakarta.persistence.Table; - import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; 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.After; -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.hibernate.testing.orm.junit.SettingProvider; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -@JiraKey(value = "HHH-13959") -public class OneToOneJoinTableUniquenessTest extends BaseCoreFunctionalTestCase { - File output; - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Profile.class, PersonRole.class }; - } +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; - @Override - protected void configure(Configuration configuration) { +import static org.assertj.core.api.Assertions.assertThat; - try { - output = File.createTempFile( "update_script", ".sql" ); - } - catch (IOException e) { - e.printStackTrace(); - fail( e.getMessage() ); +@JiraKey(value = "HHH-13959") +@DomainModel( + annotatedClasses = { + OneToOneJoinTableUniquenessTest.Profile.class, + OneToOneJoinTableUniquenessTest.PersonRole.class + } +) +@SessionFactory +@ServiceRegistry( + settings = { + @Setting(name = AvailableSettings.JAKARTA_HBM2DDL_SCRIPTS_ACTION, value = "create"), + @Setting(name = AvailableSettings.JAKARTA_HBM2DDL_DATABASE_ACTION, value = "create-drop"), + @Setting(name = AvailableSettings.FORMAT_SQL, value = "false") + }, + settingProviders = @SettingProvider( + settingName = AvailableSettings.JAKARTA_HBM2DDL_SCRIPTS_CREATE_TARGET, + provider = OneToOneJoinTableUniquenessTest.ScriptCreateTargetProvider.class + ) +) +public class OneToOneJoinTableUniquenessTest { + + public static class ScriptCreateTargetProvider implements SettingProvider.Provider { + static Path path; + + @Override + public String getSetting() { + try { + File output = File.createTempFile( "update_script", ".sql" ); + path = output.toPath(); + return path.toString(); + } + catch (IOException e) { + throw new RuntimeException( e ); + } } - String value = output.toPath().toString(); - configuration.setProperty( AvailableSettings.JAKARTA_HBM2DDL_SCRIPTS_CREATE_TARGET, value ); - configuration.setProperty( AvailableSettings.JAKARTA_HBM2DDL_SCRIPTS_ACTION, "create" ); - configuration.setProperty( AvailableSettings.JAKARTA_HBM2DDL_DATABASE_ACTION, "create-drop" ); - configuration.setProperty( AvailableSettings.FORMAT_SQL, "false" ); } - @After - public void tearDown() { - inTransaction( - session -> { - session.createQuery( "delete from PersonRole" ).executeUpdate(); - session.createQuery( "delete from Profile" ).executeUpdate(); - } - ); + @AfterEach + public void tearDown(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Test @RequiresDialect(H2Dialect.class) - public void testJoinTableColumnAreBothNotNull() throws Exception { - List commands = Files.readAllLines( output.toPath() ); + public void testJoinTableColumnAreBothNotNull(SessionFactoryScope scope) throws Exception { + scope.getSessionFactory(); + List commands = Files.readAllLines( ScriptCreateTargetProvider.path ); boolean isJoinTableCreated = false; for ( String command : commands ) { String lowerCaseCommand = command.toLowerCase(); if ( lowerCaseCommand.contains( "create table profile_person_role" ) ) { isJoinTableCreated = true; - assertTrue( lowerCaseCommand.contains( "personrole_roleid bigint not null" ) ); - assertTrue( lowerCaseCommand.contains( "id bigint not null" ) ); + assertThat( lowerCaseCommand ).contains( "personrole_roleid bigint not null" ); + assertThat( lowerCaseCommand ).contains( "id bigint not null" ); } } - assertTrue( "The Join table was not created", isJoinTableCreated ); + assertThat( isJoinTableCreated ) + .describedAs( "The Join table was not created" ) + .isTrue(); } @Test - public void testPersistProfile() { - inTransaction( + public void testPersistProfile(SessionFactoryScope scope) { + scope.inTransaction( session -> { Profile p = new Profile(); session.persist( p ); @@ -94,8 +106,8 @@ public void testPersistProfile() { } @Test - public void testPersistPersonRole() { - inTransaction( + public void testPersistPersonRole(SessionFactoryScope scope) { + scope.inTransaction( session -> { PersonRole personRole = new PersonRole(); session.persist( personRole ); @@ -104,8 +116,8 @@ public void testPersistPersonRole() { } @Test - public void testPersistBothSameTime() { - inTransaction( + public void testPersistBothSameTime(SessionFactoryScope scope) { + scope.inTransaction( session -> { PersonRole personRole = new PersonRole(); Profile profile = new Profile(); @@ -118,8 +130,8 @@ public void testPersistBothSameTime() { } @Test - public void testPersistBothAndAssociateLater() { - inTransaction( + public void testPersistBothAndAssociateLater(SessionFactoryScope scope) { + scope.inTransaction( session -> { PersonRole personRole = new PersonRole(); Profile profile = new Profile(); @@ -159,7 +171,7 @@ public void setId(Long id) { @OneToOne(fetch = FetchType.LAZY) @JoinTable( name = "profile_person_role", - inverseJoinColumns = { @JoinColumn(unique = true, nullable = false) } + inverseJoinColumns = {@JoinColumn(unique = true, nullable = false)} ) public PersonRole getPersonRole() { return this.personRole; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OneToOneTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OneToOneTest.java index 6d0c77f1e7f3..d2d7978c28c4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OneToOneTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OneToOneTest.java @@ -4,10 +4,10 @@ */ package org.hibernate.orm.test.annotations.onetoone; -import java.util.List; - -import org.hibernate.Session; -import org.hibernate.Transaction; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; +import org.hibernate.Hibernate; import org.hibernate.orm.test.annotations.Customer; import org.hibernate.orm.test.annotations.Discount; import org.hibernate.orm.test.annotations.Passport; @@ -16,30 +16,52 @@ import org.hibernate.query.criteria.HibernateCriteriaBuilder; import org.hibernate.query.criteria.JpaCriteriaQuery; import org.hibernate.query.criteria.JpaRoot; - +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.hibernate.testing.transaction.TransactionUtil; -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 jakarta.persistence.criteria.CriteriaBuilder; -import jakarta.persistence.criteria.CriteriaQuery; -import jakarta.persistence.criteria.Root; +import java.util.List; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; /** * @author Emmanuel Bernard */ -public class OneToOneTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + PartyAffiliate.class, + Party.class, + Trousers.class, + TrousersZip.class, + Customer.class, + Ticket.class, + Discount.class, + Passport.class, + Client.class, + Address.class, + Computer.class, + SerialNumber.class, + Body.class, + Heart.class, + Owner.class, + OwnerAddress.class + } +) +@SessionFactory +public class OneToOneTest { + + @AfterEach + public void tearDown(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); + } + @Test - public void testEagerFetching() { + public void testEagerFetching(SessionFactoryScope scope) { final String clientName = "Emmanuel"; - TransactionUtil.doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { Client c = new Client(); c.setName( clientName ); Address a = new Address(); @@ -48,24 +70,26 @@ public void testEagerFetching() { session.persist( c ); } ); - final Client client = TransactionUtil.doInHibernate( this::sessionFactory, session -> { - Query q = session.createQuery( "select c from Client c where c.name = :name" ); + final Client client = scope.fromTransaction( session -> { + Query q = session.createQuery( "select c from Client c where c.name = :name", Client.class ); q.setParameter( "name", clientName ); - Client c = (Client) q.uniqueResult(); + Client c = q.uniqueResult(); //c = (Client) s.get(Client.class, c.getId()); - assertNotNull( c ); + assertThat( c ).isNotNull(); return c; } ); - assertNotNull( client.getAddress() ); - //assertTrue( "Should be eager fetched", Hibernate.isInitialized( c.getAddress() ) ); + assertThat( client.getAddress() ).isNotNull(); + assertThat( Hibernate.isInitialized( client.getAddress() ) ) + .describedAs( "Should be eager fetched" ) + .isTrue(); } @Test - public void testDefaultOneToOne() { + public void testDefaultOneToOne(SessionFactoryScope scope) { //test a default one to one and a mappedBy in the other side - Long customerId = TransactionUtil.doInHibernate( this::sessionFactory, session -> { + Long customerId = scope.fromTransaction( session -> { Customer c = new Customer(); c.setName( "Hibernatus" ); Passport p = new Passport(); @@ -77,86 +101,86 @@ public void testDefaultOneToOne() { return c.getId(); } ); - TransactionUtil.doInHibernate( this::sessionFactory, session -> { - Customer c = session.get( Customer.class, customerId ); - assertNotNull( c ); + scope.inTransaction( session -> { + Customer c = session.find( Customer.class, customerId ); + assertThat( c ).isNotNull(); Passport p = c.getPassport(); - assertNotNull( p ); - assertEquals( "123456789", p.getNumber() ); - assertNotNull( p.getOwner() ); - assertEquals( "Hibernatus", p.getOwner().getName() ); + assertThat( p ).isNotNull(); + assertThat( p.getNumber() ).isEqualTo( "123456789" ); + assertThat( p.getOwner() ).isNotNull(); + assertThat( p.getOwner().getName() ).isEqualTo( "Hibernatus" ); } ); } @Test - public void testOneToOneWithExplicitFk() { + public void testOneToOneWithExplicitFk(SessionFactoryScope scope) { final Client c = new Client(); Address a = new Address(); a.setCity( "Paris" ); c.setName( "Emmanuel" ); c.setAddress( a ); - TransactionUtil.doInHibernate( this::sessionFactory, session -> { - session.persist( c ); - } ); + scope.inTransaction( session -> + session.persist( c ) + ); - TransactionUtil.doInHibernate( this::sessionFactory, session -> { - Client client = session.get( Client.class, c.getId() ); + scope.inTransaction( session -> { + Client client = session.find( Client.class, c.getId() ); - assertNotNull( client ); - assertNotNull( client.getAddress() ); - assertEquals( "Paris", client.getAddress().getCity() ); + assertThat( client ).isNotNull(); + assertThat( client.getAddress() ).isNotNull(); + assertThat( client.getAddress().getCity() ).isEqualTo( "Paris" ); } ); } @Test - public void testOneToOneWithExplicitSecondaryTableFk() { + public void testOneToOneWithExplicitSecondaryTableFk(SessionFactoryScope scope) { final Client c = new Client(); Address a = new Address(); a.setCity( "Paris" ); c.setName( "Emmanuel" ); c.setSecondaryAddress( a ); - TransactionUtil.doInHibernate( this::sessionFactory, session -> { - session.persist( c ); - } ); + scope.inTransaction( session -> + session.persist( c ) + ); - TransactionUtil.doInHibernate( this::sessionFactory, session -> { - final Client client = session.get( Client.class, c.getId() ); + scope.inTransaction( session -> { + final Client client = session.find( Client.class, c.getId() ); - assertNotNull( client ); - assertNotNull( client.getSecondaryAddress() ); - assertEquals( "Paris", client.getSecondaryAddress().getCity() ); + assertThat( client ).isNotNull(); + assertThat( client.getSecondaryAddress() ).isNotNull(); + assertThat( client.getSecondaryAddress().getCity() ).isEqualTo( "Paris" ); } ); } @Test - public void testUnidirectionalTrueOneToOne() { + public void testUnidirectionalTrueOneToOne(SessionFactoryScope scope) { final Body b = new Body(); final Heart h = new Heart(); b.setHeart( h ); b.setId( 1 ); h.setId( b.getId() ); //same PK - TransactionUtil.doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { session.persist( h ); session.persist( b ); } ); - TransactionUtil.doInHibernate( this::sessionFactory, session -> { - final Body body = session.get( Body.class, b.getId() ); + scope.inTransaction( session -> { + final Body body = session.find( Body.class, b.getId() ); - assertNotNull( body ); - assertNotNull( body.getHeart() ); - assertEquals( h.getId(), body.getHeart().getId() ); + assertThat( body ).isNotNull(); + assertThat( body.getHeart() ).isNotNull(); + assertThat( body.getHeart().getId() ).isEqualTo( h.getId() ); } ); } @Test - public void testCompositePk() { + public void testCompositePk(SessionFactoryScope scope) { final ComputerPk cid = new ComputerPk(); final SerialNumber sn = new SerialNumber(); - TransactionUtil.doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { cid.setBrand( "IBM" ); cid.setModel( "ThinkPad" ); Computer c = new Computer(); @@ -171,116 +195,104 @@ public void testCompositePk() { session.persist( c ); } ); - TransactionUtil.doInHibernate( this::sessionFactory, session -> { - Computer c = session.get( Computer.class, cid ); - assertNotNull( c ); - assertNotNull( c.getSerial() ); - assertEquals( sn.getValue(), c.getSerial().getValue() ); + scope.inTransaction( session -> { + Computer c = session.find( Computer.class, cid ); + assertThat( c ).isNotNull(); + assertThat( c.getSerial() ).isNotNull(); + assertThat( c.getSerial().getValue() ).isEqualTo( sn.getValue() ); } ); } @Test - public void testBidirectionalTrueOneToOne() { - try (Session s = openSession()) { - Party party = new Party(); - PartyAffiliate affiliate = new PartyAffiliate(); - affiliate.partyId = "id"; - party.partyId = "id"; - party.partyAffiliate = affiliate; - affiliate.party = party; - - s.getTransaction().begin(); - try { - - s.persist( party ); - s.getTransaction().commit(); - } - catch (Exception e) { - if ( s.getTransaction() != null && s.getTransaction().isActive() ) { - s.getTransaction().rollback(); + public void testBidirectionalTrueOneToOne(SessionFactoryScope scope) { + scope.inSession( + session -> { + try { + Party party = new Party(); + PartyAffiliate affiliate = new PartyAffiliate(); + affiliate.partyId = "id"; + party.partyId = "id"; + party.partyAffiliate = affiliate; + affiliate.party = party; + + session.beginTransaction(); + + session.persist( party ); + session.getTransaction().commit(); + + session.clear(); + + session.beginTransaction(); + + affiliate = session.find( PartyAffiliate.class, "id" ); + assertThat( affiliate.party ).isNotNull(); + assertThat( affiliate.party.partyId ).isEqualTo( affiliate.partyId ); + + session.clear(); + + party = session.find( Party.class, "id" ); + assertThat( party.partyAffiliate ).isNotNull(); + assertThat( party.partyAffiliate.partyId ).isEqualTo( party.partyId ); + + session.remove( party ); + session.remove( party.partyAffiliate ); + session.getTransaction().commit(); + } + finally { + if ( session.getTransaction() != null && session.getTransaction().isActive() ) { + session.getTransaction().rollback(); + } + } } - throw e; - } - - s.clear(); - - Transaction tx = s.beginTransaction(); - try { - affiliate = s.get( PartyAffiliate.class, "id" ); - assertNotNull( affiliate.party ); - assertEquals( affiliate.partyId, affiliate.party.partyId ); - - s.clear(); - - party = s.get( Party.class, "id" ); - assertNotNull( party.partyAffiliate ); - assertEquals( party.partyId, party.partyAffiliate.partyId ); - - s.remove( party ); - s.remove( party.partyAffiliate ); - tx.commit(); - } - catch (Exception e) { - if ( s.getTransaction() != null && s.getTransaction().isActive() ) { - s.getTransaction().rollback(); - } - throw e; - } - } + ); } @Test - public void testBidirectionalFkOneToOne() { - try (Session s = openSession()) { - s.getTransaction().begin(); - Trousers trousers = new Trousers(); - TrousersZip zip = new TrousersZip(); - try { - trousers.id = 1; - zip.id = 2; - trousers.zip = zip; - zip.trousers = trousers; - s.persist( trousers ); - s.persist( zip ); - s.getTransaction().commit(); - } - catch (Exception e) { - if ( s.getTransaction() != null && s.getTransaction().isActive() ) { - s.getTransaction().rollback(); + public void testBidirectionalFkOneToOne(SessionFactoryScope scope) { + scope.inSession( + session -> { + try { + session.beginTransaction(); + Trousers trousers = new Trousers(); + TrousersZip zip = new TrousersZip(); + + trousers.id = 1; + zip.id = 2; + trousers.zip = zip; + zip.trousers = trousers; + session.persist( trousers ); + session.persist( zip ); + session.getTransaction().commit(); + + session.clear(); + + session.beginTransaction(); + trousers = session.find( Trousers.class, trousers.id ); + assertThat( trousers.zip ).isNotNull(); + assertThat( trousers.zip.id ).isEqualTo( zip.id ); + + session.clear(); + + zip = session.find( TrousersZip.class, zip.id ); + assertThat( zip.trousers ).isNotNull(); + assertThat( zip.trousers.id ).isEqualTo( trousers.id ); + + session.remove( zip ); + session.remove( zip.trousers ); + session.getTransaction().commit(); + } + finally { + if ( session.getTransaction() != null && session.getTransaction().isActive() ) { + session.getTransaction().rollback(); + } + } } - throw e; - } - - s.clear(); - - Transaction tx = s.beginTransaction(); - try { - trousers = s.get( Trousers.class, trousers.id ); - assertNotNull( trousers.zip ); - assertEquals( zip.id, trousers.zip.id ); - - s.clear(); - - zip = s.get( TrousersZip.class, zip.id ); - assertNotNull( zip.trousers ); - assertEquals( trousers.id, zip.trousers.id ); - - s.remove( zip ); - s.remove( zip.trousers ); - tx.commit(); - } - catch (Exception e) { - if ( s.getTransaction() != null && s.getTransaction().isActive() ) { - s.getTransaction().rollback(); - } - throw e; - } - } + ); } @Test - public void testForeignGenerator() { - TransactionUtil.doInHibernate( this::sessionFactory, session -> { + public void testForeignGenerator(SessionFactoryScope scope) { + scope.inTransaction( session -> { Owner owner = new Owner(); OwnerAddress address = new OwnerAddress(); owner.setAddress( address ); @@ -288,81 +300,81 @@ public void testForeignGenerator() { session.persist( owner ); session.flush(); session.clear(); - owner = session.get( Owner.class, owner.getId() ); - assertNotNull( owner ); - assertNotNull( owner.getAddress() ); - assertEquals( owner.getId(), owner.getAddress().getId() ); + owner = session.find( Owner.class, owner.getId() ); + assertThat( owner ).isNotNull(); + assertThat( owner.getAddress() ).isNotNull(); + assertThat( owner.getAddress().getId() ).isEqualTo( owner.getId() ); } ); } @Test @JiraKey(value = "HHH-6723") - public void testPkOneToOneSelectStatementDoesNotGenerateExtraJoin() { + public void testPkOneToOneSelectStatementDoesNotGenerateExtraJoin(SessionFactoryScope scope) { // This test uses an interceptor to verify that correct number of joins are generated. - TransactionUtil.doInHibernate( this::sessionFactory, s -> { + scope.inTransaction( session -> { Owner owner = new Owner(); OwnerAddress address = new OwnerAddress(); owner.setAddress( address ); address.setOwner( owner ); - s.persist( owner ); - s.flush(); - s.clear(); - - owner = s.get( Owner.class, owner.getId() ); - assertNotNull( owner ); - assertNotNull( owner.getAddress() ); - assertEquals( owner.getId(), owner.getAddress().getId() ); - s.flush(); - s.clear(); - - address = s.get( OwnerAddress.class, address.getId() ); - assertNotNull( address ); - assertNotNull( address.getOwner() ); - assertEquals( address.getId(), address.getOwner().getId() ); - - s.flush(); - s.clear(); - - CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); + session.persist( owner ); + session.flush(); + session.clear(); + + owner = session.find( Owner.class, owner.getId() ); + assertThat( owner ).isNotNull(); + assertThat( owner.getAddress() ).isNotNull(); + assertThat( owner.getAddress().getId() ).isEqualTo( owner.getId() ); + session.flush(); + session.clear(); + + address = session.find( OwnerAddress.class, address.getId() ); + assertThat( address ).isNotNull(); + assertThat( address.getOwner() ).isNotNull(); + assertThat( address.getOwner().getId() ).isEqualTo( address.getId() ); + + session.flush(); + session.clear(); + + CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); CriteriaQuery criteria = criteriaBuilder.createQuery( Owner.class ); Root root = criteria.from( Owner.class ); - criteria.where( criteriaBuilder.equal( root.get("id"), owner.getId() ) ); - owner = s.createQuery( criteria ).uniqueResult(); + criteria.where( criteriaBuilder.equal( root.get( "id" ), owner.getId() ) ); + owner = session.createQuery( criteria ).uniqueResult(); // owner = (Owner) s.createCriteria( Owner.class ) // .add( Restrictions.idEq( owner.getId() ) ) // .uniqueResult(); - assertNotNull( owner ); - assertNotNull( owner.getAddress() ); - assertEquals( owner.getId(), owner.getAddress().getId() ); - s.flush(); - s.clear(); + assertThat( owner ).isNotNull(); + assertThat( owner.getAddress() ).isNotNull(); + assertThat( owner.getAddress().getId() ).isEqualTo( owner.getId() ); + session.flush(); + session.clear(); CriteriaQuery criteriaQuery = criteriaBuilder.createQuery( OwnerAddress.class ); Root ownerAddressRoot = criteriaQuery.from( OwnerAddress.class ); criteriaQuery.where( criteriaBuilder.equal( ownerAddressRoot.get( "id" ), address.getId() ) ); - address = s.createQuery( criteriaQuery ).uniqueResult(); + address = session.createQuery( criteriaQuery ).uniqueResult(); // address = (OwnerAddress) s.createCriteria( OwnerAddress.class ) // .add( Restrictions.idEq( address.getId() ) ) // .uniqueResult(); - address = s.get( OwnerAddress.class, address.getId() ); - assertNotNull( address ); - assertNotNull( address.getOwner() ); - assertEquals( address.getId(), address.getOwner().getId() ); + address = session.find( OwnerAddress.class, address.getId() ); + assertThat( address ).isNotNull(); + assertThat( address.getOwner() ).isNotNull(); + assertThat( address.getOwner().getId() ).isEqualTo( address.getId() ); - s.flush(); - s.clear(); + session.flush(); + session.clear(); } ); } @Test @JiraKey(value = "HHH-5757") - public void testHqlQuery() { + public void testHqlQuery(SessionFactoryScope scope) { //test a default one to one and a mappedBy in the other side - final Passport passport = TransactionUtil.doInHibernate( this::sessionFactory, session -> { + final Passport passport = scope.fromTransaction( session -> { Customer c = new Customer(); c.setName( "Hibernatus" ); Passport p = new Passport(); @@ -374,25 +386,27 @@ public void testHqlQuery() { return p; } ); - final Customer customer = TransactionUtil.doInHibernate( this::sessionFactory, session -> { - final Customer c = (Customer) session.createQuery( "from Customer c where c.passport = :passport " ) - .setParameter( "passport", passport ).getSingleResult(); + final Customer customer = scope.fromTransaction( session -> { + final Customer c = session.createQuery( "from Customer c where c.passport = :passport ", Customer.class ) + .setParameter( "passport", passport ) + .getSingleResult(); - assertThat( c, is( notNullValue() ) ); + assertThat( c ).isNotNull(); return c; } ); - TransactionUtil.doInHibernate( this::sessionFactory, session -> { - final Passport p = (Passport) session.createQuery( "from Passport p where p.owner = :owner " ) - .setParameter( "owner", customer ).getSingleResult(); + scope.inTransaction( session -> { + final Passport p = session.createQuery( "from Passport p where p.owner = :owner ", Passport.class ) + .setParameter( "owner", customer ) + .getSingleResult(); - assertThat( p, is( notNullValue() ) ); + assertThat( p ).isNotNull(); } ); } @Test - public void testDereferenceOneToOne() { - TransactionUtil.doInHibernate( this::sessionFactory, session -> { + public void testDereferenceOneToOne(SessionFactoryScope scope) { + scope.inTransaction( session -> { Client c1 = new Client(); c1.setName( "C1" ); Client c2 = new Client(); @@ -408,38 +422,15 @@ public void testDereferenceOneToOne() { session.persist( c3 ); } ); - TransactionUtil.doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { HibernateCriteriaBuilder cb = session.getCriteriaBuilder(); JpaCriteriaQuery query = cb.createQuery( Client.class ); JpaRoot root = query.from( Client.class ); query.where( root.get( "address" ).get( "city" ).isNull() ); List resultList = session.createQuery( query ).getResultList(); - assertEquals( 1, resultList.size() ); - assertEquals( "C3", resultList.get( 0 ).getName() ); + assertThat( resultList.size() ).isEqualTo( 1 ); + assertThat( resultList.get( 0 ).getName() ).isEqualTo( "C3" ); } ); } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - PartyAffiliate.class, - Party.class, - Trousers.class, - TrousersZip.class, - Customer.class, - Ticket.class, - Discount.class, - Passport.class, - Client.class, - Address.class, - Computer.class, - SerialNumber.class, - Body.class, - Heart.class, - Owner.class, - OwnerAddress.class - }; - } - } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OptionalOneToOneMappedByTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OptionalOneToOneMappedByTest.java index a7f2dde58485..417e2970b43f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OptionalOneToOneMappedByTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OptionalOneToOneMappedByTest.java @@ -4,91 +4,91 @@ */ package org.hibernate.orm.test.annotations.onetoone; -import java.util.concurrent.atomic.AtomicReference; -import jakarta.persistence.PersistenceException; import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Root; - import org.hibernate.id.IdentifierGenerationException; - +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.hibernate.testing.junit4.ExtraAssertions.assertTyping; -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.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import java.util.concurrent.atomic.AtomicReference; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Fail.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * @author Emmanuel Bernard * @author Gail Badner */ -public class OptionalOneToOneMappedByTest extends BaseCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + Party.class, + PartyAffiliate.class, + Owner.class, + OwnerAddress.class, + Person.class, + PersonAddress.class + } +) +@SessionFactory +public class OptionalOneToOneMappedByTest { // @OneToOne(mappedBy="address") with foreign generator @Test - public void testBidirForeignIdGenerator() { - try { - doInHibernate( this::sessionFactory, session -> { - OwnerAddress address = new OwnerAddress(); - address.setOwner( null ); - - session.persist( address ); - session.flush(); - fail( "should have failed with IdentifierGenerationException" ); - } ); - } - catch (PersistenceException ex) { - assertTyping( IdentifierGenerationException.class, ex ); - // expected - } + public void testBidirForeignIdGenerator(SessionFactoryScope scope) { + assertThrows( IdentifierGenerationException.class, () -> scope.inTransaction( session -> { + OwnerAddress address = new OwnerAddress(); + address.setOwner( null ); + + session.persist( address ); + session.flush(); + fail( "should have failed with IdentifierGenerationException" ); + } ) ); } @Test - public void testBidirAssignedId() { - doInHibernate( this::sessionFactory, session -> { + public void testBidirAssignedId(SessionFactoryScope scope) { + scope.inTransaction( session -> { PartyAffiliate affiliate = new PartyAffiliate(); affiliate.partyId = "id"; session.persist( affiliate ); } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); CriteriaQuery criteria = criteriaBuilder.createQuery( PartyAffiliate.class ); Root root = criteria.from( PartyAffiliate.class ); - criteria.where( criteriaBuilder.equal( root.get("partyId"), "id" ) ); + criteria.where( criteriaBuilder.equal( root.get( "partyId" ), "id" ) ); PartyAffiliate affiliate = session.createQuery( criteria ).uniqueResult(); // PartyAffiliate affiliate = (PartyAffiliate) session.createCriteria( // PartyAffiliate.class ) // .add( Restrictions.idEq( "id" ) ) // .uniqueResult(); - assertNotNull( affiliate ); - assertEquals( "id", affiliate.partyId ); - assertNull( affiliate.party ); + assertThat( affiliate ).isNotNull(); + assertThat( affiliate.partyId ).isEqualTo( "id" ); + assertThat( affiliate.party ).isNull(); } ); - doInHibernate( this::sessionFactory, session -> { - PartyAffiliate affiliate = session.get( + scope.inTransaction( session -> { + PartyAffiliate affiliate = session.find( PartyAffiliate.class, "id" ); - assertNull( affiliate.party ); + assertThat( affiliate.party ).isNull(); session.remove( affiliate ); } ); } @Test - public void testBidirDefaultIdGenerator() { - PersonAddress _personAddress = doInHibernate( - this::sessionFactory, + public void testBidirDefaultIdGenerator(SessionFactoryScope scope) { + PersonAddress _personAddress = scope.fromTransaction( session -> { PersonAddress personAddress = new PersonAddress(); personAddress.setPerson( null ); @@ -99,26 +99,26 @@ public void testBidirDefaultIdGenerator() { } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); CriteriaQuery criteria = criteriaBuilder.createQuery( PersonAddress.class ); Root root = criteria.from( PersonAddress.class ); - criteria.where( criteriaBuilder.equal( root.get("id"), _personAddress.getId()) ); + criteria.where( criteriaBuilder.equal( root.get( "id" ), _personAddress.getId() ) ); PersonAddress personAddress = session.createQuery( criteria ).uniqueResult(); // PersonAddress personAddress = (PersonAddress) session.createCriteria( // PersonAddress.class ) // .add( Restrictions.idEq( _personAddress.getId() ) ) // .uniqueResult(); - assertNotNull( personAddress ); - assertNull( personAddress.getPerson() ); + assertThat( personAddress ).isNotNull(); + assertThat( personAddress.getPerson() ).isNull(); } ); - doInHibernate( this::sessionFactory, session -> { - PersonAddress personAddress = session.get( + scope.inTransaction( session -> { + PersonAddress personAddress = session.find( PersonAddress.class, _personAddress.getId() ); - assertNull( personAddress.getPerson() ); + assertThat( personAddress.getPerson() ).isNull(); session.remove( personAddress ); } ); @@ -126,13 +126,11 @@ public void testBidirDefaultIdGenerator() { @Test @JiraKey(value = "HHH-5757") - public void testBidirQueryEntityProperty() { + public void testBidirQueryEntityProperty(SessionFactoryScope scope) { AtomicReference personHolder = new AtomicReference<>(); - PersonAddress _personAddress = doInHibernate( - this::sessionFactory, - session -> { + PersonAddress _personAddress = scope.fromTransaction( session -> { PersonAddress personAddress = new PersonAddress(); Person person = new Person(); personAddress.setPerson( person ); @@ -147,32 +145,32 @@ public void testBidirQueryEntityProperty() { } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); CriteriaQuery criteria = criteriaBuilder.createQuery( PersonAddress.class ); Root root = criteria.from( PersonAddress.class ); - criteria.where( criteriaBuilder.equal( root.get("id"), _personAddress.getId()) ); + criteria.where( criteriaBuilder.equal( root.get( "id" ), _personAddress.getId() ) ); PersonAddress personAddress = session.createQuery( criteria ).uniqueResult(); // PersonAddress personAddress = (PersonAddress) session.createCriteria( // PersonAddress.class ) // .add( Restrictions.idEq( _personAddress.getId() ) ) // .uniqueResult(); - assertNotNull( personAddress ); - assertNotNull( personAddress.getPerson() ); + assertThat( personAddress ).isNotNull(); + assertThat( personAddress.getPerson() ).isNotNull(); } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); Person person = personHolder.get(); // this call throws GenericJDBCException PersonAddress personAddress = session.createQuery( - "select pa from PersonAddress pa where pa.person = :person", PersonAddress.class ) + "select pa from PersonAddress pa where pa.person = :person", PersonAddress.class ) .setParameter( "person", person ) .getSingleResult(); CriteriaQuery criteria = criteriaBuilder.createQuery( Person.class ); Root root = criteria.from( Person.class ); - criteria.where( criteriaBuilder.equal( root.get("personAddress"), personAddress ) ); + criteria.where( criteriaBuilder.equal( root.get( "personAddress" ), personAddress ) ); session.createQuery( criteria ).uniqueResult(); // the other way should also work @@ -181,20 +179,8 @@ public void testBidirQueryEntityProperty() { // .uniqueResult(); session.remove( personAddress ); - assertNotSame( person, personAddress.getPerson() ); + assertThat( personAddress.getPerson() ).isNotSameAs( person ); personAddress.getPerson().setPersonAddress( null ); } ); } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Party.class, - PartyAffiliate.class, - Owner.class, - OwnerAddress.class, - Person.class, - PersonAddress.class - }; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OptionalOneToOneMapsIdQueryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OptionalOneToOneMapsIdQueryTest.java index f8a00c03f553..5c2e2e4f1f87 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OptionalOneToOneMapsIdQueryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OptionalOneToOneMapsIdQueryTest.java @@ -10,234 +10,222 @@ import jakarta.persistence.MapsId; import jakarta.persistence.OneToOne; import jakarta.persistence.Table; - import org.hibernate.annotations.NotFound; import org.hibernate.annotations.NotFoundAction; - +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -@JiraKey( value = "HHH-13875") -public class OptionalOneToOneMapsIdQueryTest extends BaseNonConfigCoreFunctionalTestCase { +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.assertj.core.api.Assertions.assertThat; + +@JiraKey(value = "HHH-13875") +@DomainModel( + annotatedClasses = { + OptionalOneToOneMapsIdQueryTest.FooHasBarWithIdNamedId.class, + OptionalOneToOneMapsIdQueryTest.BarWithIdNamedId.class, + OptionalOneToOneMapsIdQueryTest.FooHasBarWithNoIdOrPropNamedId.class, + OptionalOneToOneMapsIdQueryTest.BarWithNoIdOrPropNamedId.class, + OptionalOneToOneMapsIdQueryTest.FooHasBarWithNonIdPropNamedId.class, + OptionalOneToOneMapsIdQueryTest.BarWithNonIdPropNamedId.class + } +) +@SessionFactory +public class OptionalOneToOneMapsIdQueryTest { @Test - public void testOneToOneWithIdNamedId() { + public void testOneToOneWithIdNamedId(SessionFactoryScope scope) { // Test with associated entity having ID named "id" - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { BarWithIdNamedId bar = new BarWithIdNamedId(); bar.id = 1L; bar.longValue = 2L; FooHasBarWithIdNamedId foo = new FooHasBarWithIdNamedId(); - foo.id = 1L; + foo.id = 1L; foo.bar = bar; session.persist( bar ); session.persist( foo ); - }); + } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithIdNamedId foo = session.createQuery( - "from FooHasBarWithIdNamedId where bar.id = ?1", - FooHasBarWithIdNamedId.class - ).setParameter( 1, 1L ) + "from FooHasBarWithIdNamedId where bar.id = ?1", + FooHasBarWithIdNamedId.class + ).setParameter( 1, 1L ) .uniqueResult(); - assertNotNull( foo ); - assertNotNull( foo.bar ); - }); + assertThat( foo ).isNotNull(); + assertThat( foo.bar ).isNotNull(); + } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithIdNamedId foo = session.get( FooHasBarWithIdNamedId.class, 1L ); session.remove( foo.bar ); foo.bar = null; - }); + } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithIdNamedId foo = session.createQuery( - "from FooHasBarWithIdNamedId where bar.id = ?1", - FooHasBarWithIdNamedId.class - ).setParameter( 1, 1L ) + "from FooHasBarWithIdNamedId where bar.id = ?1", + FooHasBarWithIdNamedId.class + ).setParameter( 1, 1L ) .uniqueResult(); - assertNull( foo ); - }); + assertThat( foo ).isNull(); + } ); } @Test - public void testOneToOneWithNoIdOrPropNamedId() { + public void testOneToOneWithNoIdOrPropNamedId(SessionFactoryScope scope) { // Test with associated entity having ID not named "id", and with no property named "id" - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { BarWithNoIdOrPropNamedId bar = new BarWithNoIdOrPropNamedId(); bar.barId = 1L; bar.longValue = 2L; FooHasBarWithNoIdOrPropNamedId foo = new FooHasBarWithNoIdOrPropNamedId(); - foo.id = 1L; + foo.id = 1L; foo.bar = bar; session.persist( bar ); session.persist( foo ); - }); + } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithNoIdOrPropNamedId foo = session.createQuery( - "from FooHasBarWithNoIdOrPropNamedId where bar.barId = ?1", - FooHasBarWithNoIdOrPropNamedId.class - ).setParameter( 1, 1L ) + "from FooHasBarWithNoIdOrPropNamedId where bar.barId = ?1", + FooHasBarWithNoIdOrPropNamedId.class + ).setParameter( 1, 1L ) .uniqueResult(); - assertNotNull( foo ); - assertNotNull( foo.bar ); - }); + assertThat( foo ).isNotNull(); + assertThat( foo.bar ).isNotNull(); + } ); // Querying by the generic "id" should work the same as "barId". - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithNoIdOrPropNamedId foo = session.createQuery( - "from FooHasBarWithNoIdOrPropNamedId where bar.id = ?1", - FooHasBarWithNoIdOrPropNamedId.class - ).setParameter( 1, 1L ) + "from FooHasBarWithNoIdOrPropNamedId where bar.id = ?1", + FooHasBarWithNoIdOrPropNamedId.class + ).setParameter( 1, 1L ) .uniqueResult(); - assertNotNull( foo ); - assertNotNull( foo.bar ); - }); + assertThat( foo ).isNotNull(); + assertThat( foo.bar ).isNotNull(); + } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithNoIdOrPropNamedId foo = session.get( FooHasBarWithNoIdOrPropNamedId.class, 1L ); session.remove( foo.bar ); foo.bar = null; - }); + } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithNoIdOrPropNamedId foo = session.createQuery( - "from FooHasBarWithNoIdOrPropNamedId where bar.barId = ?1", - FooHasBarWithNoIdOrPropNamedId.class - ).setParameter( 1, 1L ) + "from FooHasBarWithNoIdOrPropNamedId where bar.barId = ?1", + FooHasBarWithNoIdOrPropNamedId.class + ).setParameter( 1, 1L ) .uniqueResult(); - assertNull( foo ); - }); + assertThat( foo ).isNull(); + } ); // Querying by the generic "id" should work the same as "barId". - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithNoIdOrPropNamedId foo = session.createQuery( - "from FooHasBarWithNoIdOrPropNamedId where bar.id = ?1", - FooHasBarWithNoIdOrPropNamedId.class - ).setParameter( 1, 1L ) + "from FooHasBarWithNoIdOrPropNamedId where bar.id = ?1", + FooHasBarWithNoIdOrPropNamedId.class + ).setParameter( 1, 1L ) .uniqueResult(); - assertNull( foo ); - }); + assertThat( foo ).isNull(); + } ); } @Test - public void testOneToOneWithNonIdPropNamedId() { + public void testOneToOneWithNonIdPropNamedId(SessionFactoryScope scope) { // Test with associated entity having a non-ID property named "id" - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { BarWithNonIdPropNamedId bar = new BarWithNonIdPropNamedId(); bar.barId = 1L; bar.id = 2L; FooHasBarWithNonIdPropNamedId foo = new FooHasBarWithNonIdPropNamedId(); - foo.id = 1L; + foo.id = 1L; foo.bar = bar; session.persist( bar ); session.persist( foo ); - }); + } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithNonIdPropNamedId foo = session.createQuery( - "from FooHasBarWithNonIdPropNamedId where bar.barId = ?1", - FooHasBarWithNonIdPropNamedId.class - ).setParameter( 1, 1L ) + "from FooHasBarWithNonIdPropNamedId where bar.barId = ?1", + FooHasBarWithNonIdPropNamedId.class + ).setParameter( 1, 1L ) .uniqueResult(); - assertNotNull( foo ); - assertNotNull( foo.bar ); - }); + assertThat( foo ).isNotNull(); + assertThat( foo.bar ).isNotNull(); + } ); // bar.id is a non-ID property. - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithNonIdPropNamedId foo = session.createQuery( - "from FooHasBarWithNonIdPropNamedId where bar.id = ?1", - FooHasBarWithNonIdPropNamedId.class - ).setParameter( 1, 2L ) + "from FooHasBarWithNonIdPropNamedId where bar.id = ?1", + FooHasBarWithNonIdPropNamedId.class + ).setParameter( 1, 2L ) .uniqueResult(); - assertNotNull( foo ); - assertNotNull( foo.bar ); - }); + assertThat( foo ).isNotNull(); + assertThat( foo.bar ).isNotNull(); + } ); // bar.id is a non-ID property. - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithNonIdPropNamedId foo = session.createQuery( - "from FooHasBarWithNonIdPropNamedId where bar.id = ?1", - FooHasBarWithNonIdPropNamedId.class - ).setParameter( 1, 1L ) + "from FooHasBarWithNonIdPropNamedId where bar.id = ?1", + FooHasBarWithNonIdPropNamedId.class + ).setParameter( 1, 1L ) .uniqueResult(); - assertNull( foo ); - }); + assertThat( foo ).isNull(); + } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithNonIdPropNamedId foo = session.get( FooHasBarWithNonIdPropNamedId.class, 1L ); session.remove( foo.bar ); foo.bar = null; - }); + } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithNonIdPropNamedId foo = session.createQuery( - "from FooHasBarWithNonIdPropNamedId where bar.barId = ?1", - FooHasBarWithNonIdPropNamedId.class - ).setParameter( 1, 1L ) + "from FooHasBarWithNonIdPropNamedId where bar.barId = ?1", + FooHasBarWithNonIdPropNamedId.class + ).setParameter( 1, 1L ) .uniqueResult(); - assertNull( foo ); - }); + assertThat( foo ).isNull(); + } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithNonIdPropNamedId foo = session.createQuery( - "from FooHasBarWithNonIdPropNamedId where bar.id = ?1", - FooHasBarWithNonIdPropNamedId.class - ).setParameter( 1, 1L ) + "from FooHasBarWithNonIdPropNamedId where bar.id = ?1", + FooHasBarWithNonIdPropNamedId.class + ).setParameter( 1, 1L ) .uniqueResult(); - assertNull( foo ); - }); + assertThat( foo ).isNull(); + } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithNonIdPropNamedId foo = session.createQuery( - "from FooHasBarWithNonIdPropNamedId where bar.id = ?1", - FooHasBarWithNonIdPropNamedId.class - ).setParameter( 1, 2L ) + "from FooHasBarWithNonIdPropNamedId where bar.id = ?1", + FooHasBarWithNonIdPropNamedId.class + ).setParameter( 1, 2L ) .uniqueResult(); - assertNull( foo ); - }); - } - - @After - public void cleanupData() { - doInHibernate( this::sessionFactory, session -> { - session.createQuery( "delete from FooHasBarWithIdNamedId" ).executeUpdate(); - session.createQuery( "delete from FooHasBarWithNoIdOrPropNamedId" ).executeUpdate(); - session.createQuery( "delete from FooHasBarWithNonIdPropNamedId" ).executeUpdate(); - session.createQuery( "delete from BarWithIdNamedId" ).executeUpdate(); - session.createQuery( "delete from BarWithNoIdOrPropNamedId" ).executeUpdate(); - session.createQuery( "delete from BarWithNoIdOrPropNamedId" ).executeUpdate(); - }); + assertThat( foo ).isNull(); + } ); } - @Override - protected Class[] getAnnotatedClasses() - { - return new Class[] { - FooHasBarWithIdNamedId.class, - BarWithIdNamedId.class, - FooHasBarWithNoIdOrPropNamedId.class, - BarWithNoIdOrPropNamedId.class, - FooHasBarWithNonIdPropNamedId.class, - BarWithNonIdPropNamedId.class - }; + @AfterEach + public void cleanupData(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Entity(name = "FooHasBarWithIdNamedId") - public static class FooHasBarWithIdNamedId - { + public static class FooHasBarWithIdNamedId { @Id private Long id; - @OneToOne(optional = true) + @OneToOne @MapsId @JoinColumn(name = "id") @NotFound(action = NotFoundAction.IGNORE) @@ -253,12 +241,11 @@ public static class BarWithIdNamedId { @Entity(name = "FooHasBarWithNoIdOrPropNamedId") @Table(name = "FooHasBarNoIdOrPropNamedId") - public static class FooHasBarWithNoIdOrPropNamedId - { + public static class FooHasBarWithNoIdOrPropNamedId { @Id private Long id; - @OneToOne(optional = true) + @OneToOne @MapsId @JoinColumn(name = "id") @NotFound(action = NotFoundAction.IGNORE) @@ -274,12 +261,11 @@ public static class BarWithNoIdOrPropNamedId { @Entity(name = "FooHasBarWithNonIdPropNamedId") @Table(name = "FooHasBarNonIdPropNamedId") - public static class FooHasBarWithNonIdPropNamedId - { + public static class FooHasBarWithNonIdPropNamedId { @Id private Long id; - @OneToOne(optional = true) + @OneToOne @MapsId @JoinColumn(name = "id") @NotFound(action = NotFoundAction.IGNORE) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OptionalOneToOnePKJCQueryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OptionalOneToOnePKJCQueryTest.java index f438ef91628d..53f0ec0212c6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OptionalOneToOnePKJCQueryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OptionalOneToOnePKJCQueryTest.java @@ -11,231 +11,220 @@ import jakarta.persistence.OneToOne; import jakarta.persistence.PrimaryKeyJoinColumn; import jakarta.persistence.Table; - +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -@JiraKey( value = "HHH-13875") -public class OptionalOneToOnePKJCQueryTest extends BaseNonConfigCoreFunctionalTestCase { +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.assertj.core.api.Assertions.assertThat; + +@JiraKey(value = "HHH-13875") +@DomainModel( + annotatedClasses = { + OptionalOneToOnePKJCQueryTest.FooHasBarWithIdNamedId.class, + OptionalOneToOnePKJCQueryTest.BarWithIdNamedId.class, + OptionalOneToOnePKJCQueryTest.FooHasBarWithNoIdOrPropNamedId.class, + OptionalOneToOnePKJCQueryTest.BarWithNoIdOrPropNamedId.class, + OptionalOneToOnePKJCQueryTest.FooHasBarWithNonIdPropNamedId.class, + OptionalOneToOnePKJCQueryTest.BarWithNonIdPropNamedId.class + } +) +@SessionFactory +public class OptionalOneToOnePKJCQueryTest { @Test - public void testOneToOneWithIdNamedId() { + public void testOneToOneWithIdNamedId(SessionFactoryScope scope) { // Test with associated entity having ID named "id" - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { BarWithIdNamedId bar = new BarWithIdNamedId(); bar.id = 1L; bar.longValue = 2L; FooHasBarWithIdNamedId foo = new FooHasBarWithIdNamedId(); - foo.id = 1L; + foo.id = 1L; foo.bar = bar; session.persist( bar ); session.persist( foo ); - }); + } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithIdNamedId foo = session.createQuery( - "from FooHasBarWithIdNamedId where bar.id = ?1", - FooHasBarWithIdNamedId.class - ).setParameter( 1, 1L ) + "from FooHasBarWithIdNamedId where bar.id = ?1", + FooHasBarWithIdNamedId.class + ).setParameter( 1, 1L ) .uniqueResult(); - assertNotNull( foo ); - assertNotNull( foo.bar ); - }); + assertThat( foo ).isNotNull(); + assertThat( foo.bar ).isNotNull(); + } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithIdNamedId foo = session.get( FooHasBarWithIdNamedId.class, 1L ); session.remove( foo.bar ); foo.bar = null; - }); + } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithIdNamedId foo = session.createQuery( - "from FooHasBarWithIdNamedId where bar.id = ?1", - FooHasBarWithIdNamedId.class - ).setParameter( 1, 1L ) + "from FooHasBarWithIdNamedId where bar.id = ?1", + FooHasBarWithIdNamedId.class + ).setParameter( 1, 1L ) .uniqueResult(); - assertNull( foo ); - }); + assertThat( foo ).isNull(); + } ); } @Test - public void testOneToOneWithNoIdOrPropNamedId() { + public void testOneToOneWithNoIdOrPropNamedId(SessionFactoryScope scope) { // Test with associated entity having ID not named "id", and with no property named "id" - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { BarWithNoIdOrPropNamedId bar = new BarWithNoIdOrPropNamedId(); bar.barId = 1L; bar.longValue = 2L; FooHasBarWithNoIdOrPropNamedId foo = new FooHasBarWithNoIdOrPropNamedId(); - foo.id = 1L; + foo.id = 1L; foo.bar = bar; session.persist( bar ); session.persist( foo ); - }); + } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithNoIdOrPropNamedId foo = session.createQuery( - "from FooHasBarWithNoIdOrPropNamedId where bar.barId = ?1", - FooHasBarWithNoIdOrPropNamedId.class - ).setParameter( 1, 1L ) + "from FooHasBarWithNoIdOrPropNamedId where bar.barId = ?1", + FooHasBarWithNoIdOrPropNamedId.class + ).setParameter( 1, 1L ) .uniqueResult(); - assertNotNull( foo ); - assertNotNull( foo.bar ); - }); + assertThat( foo ).isNotNull(); + assertThat( foo.bar ).isNotNull(); + } ); // Querying by the generic "id" should work the same as "barId". - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithNoIdOrPropNamedId foo = session.createQuery( - "from FooHasBarWithNoIdOrPropNamedId where bar.id = ?1", - FooHasBarWithNoIdOrPropNamedId.class - ).setParameter( 1, 1L ) + "from FooHasBarWithNoIdOrPropNamedId where bar.id = ?1", + FooHasBarWithNoIdOrPropNamedId.class + ).setParameter( 1, 1L ) .uniqueResult(); - assertNotNull( foo ); - assertNotNull( foo.bar ); - }); + assertThat( foo ).isNotNull(); + assertThat( foo.bar ).isNotNull(); + } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithNoIdOrPropNamedId foo = session.get( FooHasBarWithNoIdOrPropNamedId.class, 1L ); session.remove( foo.bar ); foo.bar = null; - }); + } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithNoIdOrPropNamedId foo = session.createQuery( - "from FooHasBarWithNoIdOrPropNamedId where bar.barId = ?1", - FooHasBarWithNoIdOrPropNamedId.class - ).setParameter( 1, 1L ) + "from FooHasBarWithNoIdOrPropNamedId where bar.barId = ?1", + FooHasBarWithNoIdOrPropNamedId.class + ).setParameter( 1, 1L ) .uniqueResult(); - assertNull( foo ); - }); + assertThat( foo ).isNull(); + } ); // Querying by the generic "id" should work the same as "barId". - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithNoIdOrPropNamedId foo = session.createQuery( - "from FooHasBarWithNoIdOrPropNamedId where bar.id = ?1", - FooHasBarWithNoIdOrPropNamedId.class - ).setParameter( 1, 1L ) + "from FooHasBarWithNoIdOrPropNamedId where bar.id = ?1", + FooHasBarWithNoIdOrPropNamedId.class + ).setParameter( 1, 1L ) .uniqueResult(); - assertNull( foo ); - }); + assertThat( foo ).isNull(); + } ); } @Test - public void testOneToOneWithNonIdPropNamedId() { + public void testOneToOneWithNonIdPropNamedId(SessionFactoryScope scope) { // Test with associated entity having a non-ID property named "id" - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { BarWithNonIdPropNamedId bar = new BarWithNonIdPropNamedId(); bar.barId = 1L; bar.id = 2L; FooHasBarWithNonIdPropNamedId foo = new FooHasBarWithNonIdPropNamedId(); - foo.id = 1L; + foo.id = 1L; foo.bar = bar; session.persist( bar ); session.persist( foo ); - }); + } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithNonIdPropNamedId foo = session.createQuery( - "from FooHasBarWithNonIdPropNamedId where bar.barId = ?1", - FooHasBarWithNonIdPropNamedId.class - ).setParameter( 1, 1L ) + "from FooHasBarWithNonIdPropNamedId where bar.barId = ?1", + FooHasBarWithNonIdPropNamedId.class + ).setParameter( 1, 1L ) .uniqueResult(); - assertNotNull( foo ); - assertNotNull( foo.bar ); - }); + assertThat( foo ).isNotNull(); + assertThat( foo.bar ).isNotNull(); + } ); // bar.id is a non-ID property. - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithNonIdPropNamedId foo = session.createQuery( - "from FooHasBarWithNonIdPropNamedId where bar.id = ?1", - FooHasBarWithNonIdPropNamedId.class - ).setParameter( 1, 2L ) + "from FooHasBarWithNonIdPropNamedId where bar.id = ?1", + FooHasBarWithNonIdPropNamedId.class + ).setParameter( 1, 2L ) .uniqueResult(); - assertNotNull( foo ); - assertNotNull( foo.bar ); - }); + assertThat( foo ).isNotNull(); + assertThat( foo.bar ).isNotNull(); + } ); // bar.id is a non-ID property. - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithNonIdPropNamedId foo = session.createQuery( - "from FooHasBarWithNonIdPropNamedId where bar.id = ?1", - FooHasBarWithNonIdPropNamedId.class - ).setParameter( 1, 1L ) + "from FooHasBarWithNonIdPropNamedId where bar.id = ?1", + FooHasBarWithNonIdPropNamedId.class + ).setParameter( 1, 1L ) .uniqueResult(); - assertNull( foo ); - }); + assertThat( foo ).isNull(); + } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithNonIdPropNamedId foo = session.get( FooHasBarWithNonIdPropNamedId.class, 1L ); session.remove( foo.bar ); foo.bar = null; - }); + } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithNonIdPropNamedId foo = session.createQuery( - "from FooHasBarWithNonIdPropNamedId where bar.barId = ?1", - FooHasBarWithNonIdPropNamedId.class - ).setParameter( 1, 1L ) + "from FooHasBarWithNonIdPropNamedId where bar.barId = ?1", + FooHasBarWithNonIdPropNamedId.class + ).setParameter( 1, 1L ) .uniqueResult(); - assertNull( foo ); - }); + assertThat( foo ).isNull(); + } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithNonIdPropNamedId foo = session.createQuery( - "from FooHasBarWithNonIdPropNamedId where bar.id = ?1", - FooHasBarWithNonIdPropNamedId.class - ).setParameter( 1, 1L ) + "from FooHasBarWithNonIdPropNamedId where bar.id = ?1", + FooHasBarWithNonIdPropNamedId.class + ).setParameter( 1, 1L ) .uniqueResult(); - assertNull( foo ); - }); + assertThat( foo ).isNull(); + } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final FooHasBarWithNonIdPropNamedId foo = session.createQuery( - "from FooHasBarWithNonIdPropNamedId where bar.id = ?1", - FooHasBarWithNonIdPropNamedId.class - ).setParameter( 1, 2L ) + "from FooHasBarWithNonIdPropNamedId where bar.id = ?1", + FooHasBarWithNonIdPropNamedId.class + ).setParameter( 1, 2L ) .uniqueResult(); - assertNull( foo ); - }); - } - - @After - public void cleanupData() { - doInHibernate( this::sessionFactory, session -> { - session.createQuery( "delete from FooHasBarWithIdNamedId" ).executeUpdate(); - session.createQuery( "delete from FooHasBarWithNoIdOrPropNamedId" ).executeUpdate(); - session.createQuery( "delete from FooHasBarWithNonIdPropNamedId" ).executeUpdate(); - session.createQuery( "delete from BarWithIdNamedId" ).executeUpdate(); - session.createQuery( "delete from BarWithNoIdOrPropNamedId" ).executeUpdate(); - session.createQuery( "delete from BarWithNoIdOrPropNamedId" ).executeUpdate(); - }); + assertThat( foo ).isNull(); + } ); } - @Override - protected Class[] getAnnotatedClasses() - { - return new Class[] { - FooHasBarWithIdNamedId.class, - BarWithIdNamedId.class, - FooHasBarWithNoIdOrPropNamedId.class, - BarWithNoIdOrPropNamedId.class, - FooHasBarWithNonIdPropNamedId.class, - BarWithNonIdPropNamedId.class - }; + @AfterEach + public void cleanupData(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Entity(name = "FooHasBarWithIdNamedId") - public static class FooHasBarWithIdNamedId - { + public static class FooHasBarWithIdNamedId { @Id private long id; - @OneToOne(optional = true) + @OneToOne @PrimaryKeyJoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) private BarWithIdNamedId bar; } @@ -249,12 +238,11 @@ public static class BarWithIdNamedId { @Entity(name = "FooHasBarWithNoIdOrPropNamedId") @Table(name = "FooHasBarNoIdOrPropNamedId") - public static class FooHasBarWithNoIdOrPropNamedId - { + public static class FooHasBarWithNoIdOrPropNamedId { @Id private long id; - @OneToOne(optional = true) + @OneToOne @PrimaryKeyJoinColumn() private BarWithNoIdOrPropNamedId bar; } @@ -268,12 +256,11 @@ public static class BarWithNoIdOrPropNamedId { @Entity(name = "FooHasBarWithNonIdPropNamedId") @Table(name = "FooHasBarNonIdPropNamedId") - public static class FooHasBarWithNonIdPropNamedId - { + public static class FooHasBarWithNonIdPropNamedId { @Id private long id; - @OneToOne(optional = true) + @OneToOne @PrimaryKeyJoinColumn() private BarWithNonIdPropNamedId bar; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OptionalOneToOnePKJCTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OptionalOneToOnePKJCTest.java index 7e8dc4a43b3c..68f357f0a744 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OptionalOneToOnePKJCTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OptionalOneToOnePKJCTest.java @@ -4,167 +4,141 @@ */ package org.hibernate.orm.test.annotations.onetoone; -import jakarta.persistence.PersistenceException; import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Root; - -import org.hibernate.Session; -import org.hibernate.Transaction; import org.hibernate.id.IdentifierGenerationException; - +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.hibernate.testing.junit4.ExtraAssertions.assertTyping; -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 static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Fail.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * @author Emmanuel Bernard * @author Gail Badner */ -public class OptionalOneToOnePKJCTest extends BaseCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + Party.class, + PartyAffiliate.class, + Owner.class, + OwnerAddress.class, + Person.class, + PersonAddress.class + }, + xmlMappings = "org/hibernate/orm/test/annotations/onetoone/orm.xml" +) +@SessionFactory +public class OptionalOneToOnePKJCTest { @Test - @JiraKey( value = "HHH-4982") - public void testNullBidirForeignIdGenerator() { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Person person = new Person(); - person.setPersonAddress( null ); - try { - s.persist( person ); - s.flush(); - fail( "should have thrown IdentifierGenerationException."); - } - catch (PersistenceException ex) { - assertTyping(IdentifierGenerationException.class, ex); - // expected - } - finally { - tx.rollback(); - s.close(); - } + @JiraKey(value = "HHH-4982") + public void testNullBidirForeignIdGenerator(SessionFactoryScope scope) { + assertThrows( IdentifierGenerationException.class, () -> scope.inTransaction( + session -> { + Person person = new Person(); + person.setPersonAddress( null ); + session.persist( person ); + session.flush(); + fail( "should have thrown IdentifierGenerationException." ); + } + ) ); } @Test - @JiraKey( value = "HHH-4982") - public void testNotFoundBidirForeignIdGenerator() { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Person person = new Person(); - person.setPersonAddress( null ); - person.setId( 1 ); - try { - // Hibernate resets the ID to null before executing the foreign generator - s.persist( person ); - s.flush(); - fail( "should have thrown IdentifierGenerationException."); - } - catch (PersistenceException ex) { - assertTyping(IdentifierGenerationException.class, ex); - // expected - } - finally { - tx.rollback(); - s.close(); - } + @JiraKey(value = "HHH-4982") + public void testNotFoundBidirForeignIdGenerator(SessionFactoryScope scope) { + assertThrows( IdentifierGenerationException.class, () -> scope.inTransaction( + session -> { + Person person = new Person(); + person.setPersonAddress( null ); + person.setId( 1 ); + // Hibernate resets the ID to null before executing the foreign generator + session.persist( person ); + session.flush(); + fail( "should have thrown IdentifierGenerationException." ); + } + ) ); } // @PrimaryKeyJoinColumn @OneToOne(optional=true) non-foreign generator @Test - @JiraKey( value = "HHH-4982") - public void testNotFoundBidirDefaultIdGenerator() { - Session s = openSession(); - s.getTransaction().begin(); - Owner owner = new Owner(); - owner.setAddress( null ); - s.persist( owner ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.getTransaction().begin(); - owner = ( Owner ) s.get( Owner.class, owner.getId() ); - assertNotNull( owner ); - assertNull( owner.getAddress() ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.getTransaction().begin(); - CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); - CriteriaQuery criteria = criteriaBuilder.createQuery( Owner.class ); - Root root = criteria.from( Owner.class ); - criteria.where( criteriaBuilder.equal( root.get( "id" ), owner.getId() ) ); - - owner = s.createQuery( criteria ).uniqueResult(); + @JiraKey(value = "HHH-4982") + public void testNotFoundBidirDefaultIdGenerator(SessionFactoryScope scope) { + Owner o = new Owner(); + scope.inTransaction( + session -> { + o.setAddress( null ); + session.persist( o ); + } + ); + + scope.inTransaction( + session -> { + Owner owner = session.find( Owner.class, o.getId() ); + assertThat( owner ).isNotNull(); + assertThat( owner.getAddress() ).isNull(); + } + ); + + scope.inTransaction( + session -> { + CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); + CriteriaQuery criteria = criteriaBuilder.createQuery( Owner.class ); + Root root = criteria.from( Owner.class ); + criteria.where( criteriaBuilder.equal( root.get( "id" ), o.getId() ) ); + + Owner owner = session.createQuery( criteria ).uniqueResult(); // owner = ( Owner ) s.createCriteria( Owner.class ) // .add( Restrictions.idEq( owner.getId() ) ) // .uniqueResult(); - assertNotNull( owner ); - assertNull( owner.getAddress() ); - s.remove( owner ); - s.getTransaction().commit(); - s.close(); + assertThat( owner ).isNotNull(); + assertThat( owner.getAddress() ).isNull(); + session.remove( owner ); + } + ); } @Test - public void testNotFoundBidirAssignedId() throws Exception { - Session s = openSession(); - s.getTransaction().begin(); - Party party = new Party(); - party.partyId = "id"; - party.partyAffiliate = null; - s.persist( party ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.getTransaction().begin(); - party = ( Party ) s.get( Party.class, "id" ); - assertNull( party.partyAffiliate ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.getTransaction().begin(); - - CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); - CriteriaQuery criteria = criteriaBuilder.createQuery( Party.class ); - Root root = criteria.from( Party.class ); - criteria.where( criteriaBuilder.equal( root.get( "partyId" ), "id" ) ); - - party = s.createQuery( criteria ).uniqueResult(); + public void testNotFoundBidirAssignedId(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Party party = new Party(); + party.partyId = "id"; + party.partyAffiliate = null; + session.persist( party ); + } + ); + + scope.inTransaction( + session -> { + Party party = session.find( Party.class, "id" ); + assertThat( party.partyAffiliate ).isNull(); + } + ); + + scope.inTransaction( + session -> { + CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); + CriteriaQuery criteria = criteriaBuilder.createQuery( Party.class ); + Root root = criteria.from( Party.class ); + criteria.where( criteriaBuilder.equal( root.get( "partyId" ), "id" ) ); + + Party party = session.createQuery( criteria ).uniqueResult(); // party = ( Party ) s.createCriteria( Party.class ) // .add( Restrictions.idEq( "id" ) ) // .uniqueResult(); - assertNotNull( party ); - assertEquals( "id", party.partyId ); - assertNull( party.partyAffiliate ); - s.remove( party ); - s.getTransaction().commit(); - s.close(); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Party.class, - PartyAffiliate.class, - Owner.class, - OwnerAddress.class, - Person.class, - PersonAddress.class - }; + assertThat( party ).isNotNull(); + assertThat( party.partyId ).isEqualTo( "id" ); + assertThat( party.partyAffiliate ).isNull(); + session.remove( party ); + } + ); } - @Override - protected String[] getOrmXmlFiles() { - return new String[] { "org/hibernate/orm/test/annotations/onetoone/orm.xml" }; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Owner.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Owner.java index 8273a07eb3f7..722abe86d036 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Owner.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Owner.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.onetoone; + import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OwnerAddress.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OwnerAddress.java index eefb1d2cc933..ffbac8220179 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OwnerAddress.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OwnerAddress.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.onetoone; + import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Party.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Party.java index 461afee83337..ef56327af76a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Party.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Party.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.onetoone; + import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; import jakarta.persistence.Id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/PartyAffiliate.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/PartyAffiliate.java index e571b526f5f4..2d979fa10e59 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/PartyAffiliate.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/PartyAffiliate.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.onetoone; + import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.OneToOne; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/SerialNumber.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/SerialNumber.java index 5dec39cec049..ed410d2b3f88 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/SerialNumber.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/SerialNumber.java @@ -18,13 +18,9 @@ public class SerialNumber { public boolean equals(Object o) { if ( this == o ) return true; - if ( !( o instanceof SerialNumber ) ) return false; + if ( !(o instanceof SerialNumber serialNumber) ) return false; - final SerialNumber serialNumber = (SerialNumber) o; - - if ( !id.equals( serialNumber.id ) ) return false; - - return true; + return id.equals( serialNumber.id ); } public int hashCode() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Trousers.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Trousers.java index 4b00c22ce3d5..693fbe037365 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Trousers.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Trousers.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.onetoone; + import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/TrousersZip.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/TrousersZip.java index 11d9e1019277..aac24dd376c8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/TrousersZip.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/TrousersZip.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.onetoone; + import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.OneToOne; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/override/mappedsuperclass/MappedSuperClassIdPropertyBasicAttributeOverrideTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/override/mappedsuperclass/MappedSuperClassIdPropertyBasicAttributeOverrideTest.java index d2205313ab34..02b635256747 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/override/mappedsuperclass/MappedSuperClassIdPropertyBasicAttributeOverrideTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/override/mappedsuperclass/MappedSuperClassIdPropertyBasicAttributeOverrideTest.java @@ -5,6 +5,7 @@ package org.hibernate.orm.test.annotations.override.mappedsuperclass; import org.hibernate.MappingException; +import org.hibernate.SessionFactory; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.spi.MetadataImplementor; @@ -31,8 +32,9 @@ public void test() { metadataSources.addAnnotatedClasses( SubclassWithUuidAsId.class ); MetadataImplementor metadata = (MetadataImplementor) metadataSources.buildMetadata(); - metadata.buildSessionFactory(); - fail( "Should throw exception!" ); + try(SessionFactory sf = metadata.buildSessionFactory()){ + fail( "Should throw exception!" ); + } } catch (MappingException expected) { // expected diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/quote/resultsetmappings/ExplicitSqlResultSetMappingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/quote/resultsetmappings/ExplicitSqlResultSetMappingTest.java index 70e04f6edf74..bb1fd0a3fe9c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/quote/resultsetmappings/ExplicitSqlResultSetMappingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/quote/resultsetmappings/ExplicitSqlResultSetMappingTest.java @@ -4,57 +4,61 @@ */ package org.hibernate.orm.test.annotations.quote.resultsetmappings; -import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; +import org.hibernate.dialect.Dialect; +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.Test; /** * @author Steve Ebersole */ -public class ExplicitSqlResultSetMappingTest extends BaseCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + MyEntity.class + } +) +@SessionFactory +@ServiceRegistry( + settings = @Setting(name = Environment.GLOBALLY_QUOTED_IDENTIFIERS, value = "true") +) +public class ExplicitSqlResultSetMappingTest { private String queryString = null; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { MyEntity.class }; - } - - @Override - protected void configure(Configuration cfg) { - cfg.setProperty( Environment.GLOBALLY_QUOTED_IDENTIFIERS, true ); - } - private void prepareTestData() { - char open = getDialect().openQuote(); - char close = getDialect().closeQuote(); - queryString="select t."+open+"NAME"+close+" as "+open+"QuotEd_nAMe"+close+" from "+open+"MY_ENTITY_TABLE"+close+" t"; - inTransaction( + @BeforeEach + public void prepareTestData(SessionFactoryScope scope) { + Dialect dialect = scope.getSessionFactory().getJdbcServices().getDialect(); + char open = dialect.openQuote(); + char close = dialect.closeQuote(); + queryString = "select t." + open + "NAME" + close + " as " + open + "QuotEd_nAMe" + close + " from " + open + "MY_ENTITY_TABLE" + close + " t"; + scope.inTransaction( s -> s.persist( new MyEntity( "mine" ) ) ); } - @Override - protected boolean isCleanupTestDataRequired() { - return true; + @AfterEach + public void cleanup(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Test - public void testCompleteScalarAutoDiscovery() { - prepareTestData(); - - inTransaction( + public void testCompleteScalarAutoDiscovery(SessionFactoryScope scope) { + scope.inTransaction( s -> s.createNativeQuery( queryString ).list() ); } @Test - public void testPartialScalarAutoDiscovery() { - prepareTestData(); - - inTransaction( + public void testPartialScalarAutoDiscovery(SessionFactoryScope scope) { + scope.inTransaction( s -> s.createNativeQuery( queryString, "explicitScalarResultSetMapping" ).list() ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Bag.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Bag.java index 0ae2ebf429a9..50c156ce5364 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Bag.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Bag.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.referencedcolumnname; + import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Clothes.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Clothes.java index 1f29e0c2a233..35b96e259b21 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Clothes.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Clothes.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.referencedcolumnname; + import jakarta.persistence.Entity; import jakarta.persistence.Column; import jakarta.persistence.GeneratedValue; @@ -54,14 +55,10 @@ public void setFlavor(String flavor) { public boolean equals(Object o) { if ( this == o ) return true; - if ( !( o instanceof Clothes ) ) return false; - - final Clothes clothes = (Clothes) o; + if ( !(o instanceof Clothes clothes) ) return false; if ( !flavor.equals( clothes.flavor ) ) return false; - if ( !type.equals( clothes.type ) ) return false; - - return true; + return type.equals( clothes.type ); } public int hashCode() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/House.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/House.java index f5c94f5465a8..866537d3225a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/House.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/House.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.referencedcolumnname; + import java.io.Serializable; import java.util.HashSet; import java.util.Set; @@ -23,7 +24,7 @@ public class House implements Serializable { private Integer id; private String address; private Postman postman; - private Set hasInhabitants = new HashSet(); + private Set hasInhabitants = new HashSet<>(); @ManyToOne @JoinColumn(referencedColumnName = "name") @@ -67,13 +68,9 @@ public void setHasInhabitants(Set hasInhabitants) { public boolean equals(Object o) { if ( this == o ) return true; - if ( !( o instanceof House ) ) return false; - - final House house = (House) o; - - if ( address != null ? !address.equals( house.address ) : house.address != null ) return false; + if ( !(o instanceof House house) ) return false; - return true; + return address != null ? address.equals( house.address ) : house.address == null; } public int hashCode() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Inhabitant.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Inhabitant.java index 0c326ee391d6..55ecb2e90c02 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Inhabitant.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Inhabitant.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.referencedcolumnname; + import java.io.Serializable; import java.util.HashSet; import java.util.Set; @@ -18,7 +19,7 @@ public class Inhabitant implements Serializable { private Integer id; private String name; - private Set livesIn = new HashSet(); + private Set livesIn = new HashSet<>(); @Id @GeneratedValue @@ -49,13 +50,9 @@ public void setLivesIn(Set livesIn) { public boolean equals(Object o) { if ( this == o ) return true; - if ( !( o instanceof Inhabitant ) ) return false; - - final Inhabitant inhabitant = (Inhabitant) o; - - if ( name != null ? !name.equals( inhabitant.name ) : inhabitant.name != null ) return false; + if ( !(o instanceof Inhabitant inhabitant) ) return false; - return true; + return name != null ? name.equals( inhabitant.name ) : inhabitant.name == null; } public int hashCode() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Item.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Item.java index c025b94baa9c..854b769b0dd2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Item.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Item.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.referencedcolumnname; + import jakarta.persistence.Entity; import jakarta.persistence.Id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/ItemCost.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/ItemCost.java index 6df8de62e483..f60a5055942b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/ItemCost.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/ItemCost.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.referencedcolumnname; + import java.io.Serializable; import java.math.BigDecimal; import jakarta.persistence.Entity; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Luggage.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Luggage.java index 4eed646fad83..280666c3af30 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Luggage.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Luggage.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.referencedcolumnname; + import java.io.Serializable; import java.util.HashSet; import java.util.Set; @@ -23,7 +24,7 @@ public class Luggage implements Serializable { private String owner; @Column(name = "`type`") private String type; - private Set hasInside = new HashSet(); + private Set hasInside = new HashSet<>(); public Luggage() { } @@ -72,14 +73,10 @@ public void setHasInside(Set hasInside) { public boolean equals(Object o) { if ( this == o ) return true; - if ( !( o instanceof Luggage ) ) return false; - - final Luggage luggage = (Luggage) o; + if ( !(o instanceof Luggage luggage) ) return false; if ( !owner.equals( luggage.owner ) ) return false; - if ( !type.equals( luggage.type ) ) return false; - - return true; + return type.equals( luggage.type ); } public int hashCode() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Postman.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Postman.java index d244f263af99..bd5167f06b71 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Postman.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Postman.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.referencedcolumnname; + import java.io.Serializable; import jakarta.persistence.Entity; import jakarta.persistence.Id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Rambler.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Rambler.java index 8b6b2e734cc7..2ac37d824c34 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Rambler.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Rambler.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.referencedcolumnname; + import java.io.Serializable; import java.util.HashSet; import java.util.Set; @@ -20,7 +21,7 @@ public class Rambler implements Serializable { private Integer id; private String name; - private Set bags = new HashSet(); + private Set bags = new HashSet<>(); public Rambler() { } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/ReferencedColumnNameTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/ReferencedColumnNameTest.java index 93b7433cf6f3..f1119afd4828 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/ReferencedColumnNameTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/ReferencedColumnNameTest.java @@ -4,46 +4,78 @@ */ package org.hibernate.orm.test.annotations.referencedcolumnname; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl; -import org.hibernate.cfg.Configuration; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; - -import java.math.BigDecimal; -import java.util.Iterator; - import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Join; import jakarta.persistence.criteria.Root; +import org.hibernate.boot.model.naming.ImplicitNamingStrategy; +import org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl; +import org.hibernate.cfg.AvailableSettings; +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.SettingProvider; +import org.junit.jupiter.api.Test; + +import java.math.BigDecimal; + +import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; /** * @author Emmanuel Bernard */ -public class ReferencedColumnNameTest extends BaseCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + House.class, + Postman.class, + Bag.class, + Rambler.class, + Luggage.class, + Clothes.class, + Inhabitant.class, + Item.class, + ItemCost.class, + Vendor.class, + WarehouseItem.class, + Place.class, + HousePlaces.class + } +) +@SessionFactory +@ServiceRegistry( + settingProviders = @SettingProvider( + settingName = AvailableSettings.IMPLICIT_NAMING_STRATEGY, + provider = ReferencedColumnNameTest.NamingStrategyProvider.class + ) +) +public class ReferencedColumnNameTest { + public static class NamingStrategyProvider implements SettingProvider.Provider { + @Override + public ImplicitNamingStrategy getSetting() { + return ImplicitNamingStrategyLegacyJpaImpl.INSTANCE; + } + } + @Test - public void testManyToOne() { + public void testManyToOne(SessionFactoryScope scope) { Postman postman = new Postman( "Bob", "A01" ); House house = new House(); house.setPostman( postman ); house.setAddress( "Rue des pres" ); - inTransaction( + scope.inTransaction( s -> { s.persist( postman ); s.persist( house ); } ); - inTransaction( + scope.inTransaction( s -> { - House h = s.get( House.class, house.getId() ); - assertNotNull( h.getPostman() ); - assertEquals( "Bob", h.getPostman().getName() ); + House h = s.find( House.class, house.getId() ); + assertThat( h.getPostman() ).isNotNull(); + assertThat( h.getPostman().getName() ).isEqualTo( "Bob" ); Postman pm = h.getPostman(); s.remove( h ); s.remove( pm ); @@ -52,8 +84,8 @@ public void testManyToOne() { } @Test - public void testOneToMany() { - inTransaction( + public void testOneToMany(SessionFactoryScope scope) { + scope.inTransaction( s -> { Rambler rambler = new Rambler( "Emmanuel" ); Bag bag = new Bag( "0001", rambler ); @@ -62,16 +94,18 @@ public void testOneToMany() { } ); - inTransaction( + scope.inTransaction( s -> { - Bag bag = (Bag) s.createQuery( "select b from Bag b left join fetch b.owner" ).uniqueResult(); - assertNotNull( bag ); - assertNotNull( bag.getOwner() ); - - Rambler rambler = (Rambler) s.createQuery( "select r from Rambler r left join fetch r.bags" ).uniqueResult(); - assertNotNull( rambler ); - assertNotNull( rambler.getBags() ); - assertEquals( 1, rambler.getBags().size() ); + Bag bag = s.createQuery( "select b from Bag b left join fetch b.owner", Bag.class ) + .uniqueResult(); + assertThat( bag ).isNotNull(); + assertThat( bag.getOwner() ).isNotNull(); + + Rambler rambler = s.createQuery( "select r from Rambler r left join fetch r.bags", Rambler.class ) + .uniqueResult(); + assertThat( rambler ).isNotNull(); + assertThat( rambler.getBags() ).isNotNull(); + assertThat( rambler.getBags().size() ).isEqualTo( 1 ); s.remove( rambler.getBags().iterator().next() ); s.remove( rambler ); } @@ -79,8 +113,8 @@ public void testOneToMany() { } @Test - public void testUnidirectionalOneToMany() { - inTransaction( + public void testUnidirectionalOneToMany(SessionFactoryScope scope) { + scope.inTransaction( s -> { Clothes clothes = new Clothes( "underwear", "interesting" ); Luggage luggage = new Luggage( "Emmanuel", "Cabin Luggage" ); @@ -89,13 +123,13 @@ public void testUnidirectionalOneToMany() { } ); - inTransaction( + scope.inTransaction( s -> { - Luggage luggage = (Luggage) s.createQuery( "select l from Luggage l left join fetch l.hasInside" ) + Luggage luggage = s.createQuery( "select l from Luggage l left join fetch l.hasInside", Luggage.class ) .uniqueResult(); - assertNotNull( luggage ); - assertNotNull( luggage.getHasInside() ); - assertEquals( 1, luggage.getHasInside().size() ); + assertThat( luggage ).isNotNull(); + assertThat( luggage.getHasInside() ).isNotNull(); + assertThat( luggage.getHasInside().size() ).isEqualTo( 1 ); s.remove( luggage.getHasInside().iterator().next() ); s.remove( luggage ); @@ -105,60 +139,58 @@ public void testUnidirectionalOneToMany() { } @Test - public void testManyToMany(){ - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - - House whiteHouse = new House(); - whiteHouse.setAddress( "1600 Pennsylvania Avenue, Washington" ); - Inhabitant bill = new Inhabitant(); - bill.setName( "Bill Clinton" ); - Inhabitant george = new Inhabitant(); - george.setName( "George W Bush" ); - s.persist( george ); - s.persist( bill ); - whiteHouse.getHasInhabitants().add( bill ); - whiteHouse.getHasInhabitants().add( george ); - //bill.getLivesIn().add( whiteHouse ); - //george.getLivesIn().add( whiteHouse ); - - s.persist( whiteHouse ); - tx.commit(); - s = openSession(); - tx = s.beginTransaction(); - - whiteHouse = s.get( House.class, whiteHouse.getId() ); - assertNotNull( whiteHouse ); - assertEquals( 2, whiteHouse.getHasInhabitants().size() ); - - tx.commit(); - s.clear(); - tx = s.beginTransaction(); - bill = s.get( Inhabitant.class, bill.getId() ); - assertNotNull( bill ); - assertEquals( 1, bill.getLivesIn().size() ); - assertEquals( whiteHouse.getAddress(), bill.getLivesIn().iterator().next().getAddress() ); - - whiteHouse = bill.getLivesIn().iterator().next(); - s.remove( whiteHouse ); - Iterator it = whiteHouse.getHasInhabitants().iterator(); - while ( it.hasNext() ) { - s.remove( it.next() ); - } - tx.commit(); - s.close(); + public void testManyToMany(SessionFactoryScope scope) { + House wh = new House(); + Inhabitant b = new Inhabitant(); + scope.inTransaction( + session -> { + wh.setAddress( "1600 Pennsylvania Avenue, Washington" ); + b.setName( "Bill Clinton" ); + Inhabitant george = new Inhabitant(); + george.setName( "George W Bush" ); + session.persist( george ); + session.persist( b ); + wh.getHasInhabitants().add( b ); + wh.getHasInhabitants().add( george ); + //bill.getLivesIn().add( whiteHouse ); + //george.getLivesIn().add( whiteHouse ); + + session.persist( wh ); + } + ); + + scope.inTransaction( + session -> { + House whiteHouse = session.find( House.class, wh.getId() ); + assertThat( whiteHouse ).isNotNull(); + assertThat( whiteHouse.getHasInhabitants().size() ).isEqualTo( 2 ); + } + ); + + scope.inTransaction( + session -> { + Inhabitant bill = session.find( Inhabitant.class, b.getId() ); + assertThat( bill ).isNotNull(); + assertThat( bill.getLivesIn().size() ).isEqualTo( 1 ); + assertThat( bill.getLivesIn().iterator().next().getAddress() ).isEqualTo( wh.getAddress() ); + + House whiteHouse = bill.getLivesIn().iterator().next(); + session.remove( whiteHouse ); + for ( Inhabitant inhabitant : whiteHouse.getHasInhabitants() ) { + session.remove( inhabitant ); + } + } + ); } @Test - public void testManyToOneReferenceManyToOne() { + public void testManyToOneReferenceManyToOne(SessionFactoryScope scope) { Item item = new Item(); item.setId( 1 ); Vendor vendor = new Vendor(); vendor.setId( 1 ); ItemCost cost = new ItemCost(); - cost.setCost( new BigDecimal(1) ); + cost.setCost( new BigDecimal( 1 ) ); cost.setId( 1 ); cost.setItem( item ); cost.setVendor( vendor ); @@ -166,9 +198,9 @@ public void testManyToOneReferenceManyToOne() { wItem.setDefaultCost( cost ); wItem.setId( 1 ); wItem.setItem( item ); - wItem.setQtyInStock( new BigDecimal(1) ); + wItem.setQtyInStock( new BigDecimal( 1 ) ); wItem.setVendor( vendor ); - inTransaction( + scope.inTransaction( s -> { s.persist( item ); s.persist( vendor ); @@ -176,14 +208,14 @@ public void testManyToOneReferenceManyToOne() { s.persist( wItem ); s.flush(); s.clear(); - WarehouseItem warehouseItem = s.get(WarehouseItem.class, wItem.getId() ); - assertNotNull( warehouseItem.getDefaultCost().getItem() ); + WarehouseItem warehouseItem = s.find( WarehouseItem.class, wItem.getId() ); + assertThat( warehouseItem.getDefaultCost().getItem() ).isNotNull(); } ); } @Test - public void testManyToOneInsideComponentReferencedColumn() { + public void testManyToOneInsideComponentReferencedColumn(SessionFactoryScope scope) { HousePlaces house = new HousePlaces(); house.places = new Places(); @@ -202,25 +234,27 @@ public void testManyToOneInsideComponentReferencedColumn() { house.neighbourPlaces.kitchen = new Place(); house.neighbourPlaces.kitchen.name = "His Kitchen"; - inTransaction( + scope.inTransaction( s -> { s.persist( house ); s.flush(); - HousePlaces get = s.get( HousePlaces.class, house.id ); - assertEquals( house.id, get.id ); + HousePlaces housePlaces = s.find( HousePlaces.class, house.id ); + assertThat( housePlaces.id ).isEqualTo( house.id ); - HousePlaces uniqueResult = (HousePlaces) s.createQuery( "from HousePlaces h where h.places.livingRoom.name='First'" ) + HousePlaces uniqueResult = s.createQuery( + "from HousePlaces h where h.places.livingRoom.name='First'", HousePlaces.class ) .uniqueResult(); - assertNotNull( uniqueResult ); - assertEquals( uniqueResult.places.livingRoom.name, "First" ); - assertEquals( uniqueResult.places.livingRoom.owner, "mine" ); + assertThat( uniqueResult ).isNotNull(); + assertThat( uniqueResult.places.livingRoom.name ).isEqualTo( "First" ); + assertThat( uniqueResult.places.livingRoom.owner ).isEqualTo( "mine" ); - uniqueResult = (HousePlaces) s.createQuery( "from HousePlaces h where h.places.livingRoom.owner=:owner" ) + uniqueResult = s.createQuery( + "from HousePlaces h where h.places.livingRoom.owner=:owner", HousePlaces.class ) .setParameter( "owner", "mine" ).uniqueResult(); - assertNotNull( uniqueResult ); - assertEquals( uniqueResult.places.livingRoom.name, "First" ); - assertEquals( uniqueResult.places.livingRoom.owner, "mine" ); + assertThat( uniqueResult ).isNotNull(); + assertThat( uniqueResult.places.livingRoom.name ).isEqualTo( "First" ); + assertThat( uniqueResult.places.livingRoom.owner ).isEqualTo( "mine" ); CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); CriteriaQuery criteria = criteriaBuilder.createQuery( HousePlaces.class ); @@ -228,30 +262,32 @@ public void testManyToOneInsideComponentReferencedColumn() { Join join = root.join( "places" ).join( "livingRoom" ); criteria.where( criteriaBuilder.equal( join.get( "owner" ), "mine" ) ); - assertNotNull(s.createQuery( criteria ).uniqueResult()); + assertThat( s.createQuery( criteria ).uniqueResult() ).isNotNull(); // assertNotNull( s.createCriteria( HousePlaces.class ).add( Restrictions.eq( "places.livingRoom.owner", "mine" ) ) // .uniqueResult() ); // override - uniqueResult = (HousePlaces) s.createQuery( "from HousePlaces h where h.neighbourPlaces.livingRoom.owner='his'" ) + uniqueResult = s.createQuery( + "from HousePlaces h where h.neighbourPlaces.livingRoom.owner='his'", HousePlaces.class ) .uniqueResult(); - assertNotNull( uniqueResult ); - assertEquals( uniqueResult.neighbourPlaces.livingRoom.name, "Neighbour" ); - assertEquals( uniqueResult.neighbourPlaces.livingRoom.owner, "his" ); + assertThat( uniqueResult ).isNotNull(); + assertThat( uniqueResult.neighbourPlaces.livingRoom.name ).isEqualTo( "Neighbour" ); + assertThat( uniqueResult.neighbourPlaces.livingRoom.owner ).isEqualTo( "his" ); - uniqueResult = (HousePlaces) s.createQuery( "from HousePlaces h where h.neighbourPlaces.livingRoom.name=:name" ) + uniqueResult = s.createQuery( + "from HousePlaces h where h.neighbourPlaces.livingRoom.name=:name", HousePlaces.class ) .setParameter( "name", "Neighbour" ).uniqueResult(); - assertNotNull( uniqueResult ); - assertEquals( uniqueResult.neighbourPlaces.livingRoom.name, "Neighbour" ); - assertEquals( uniqueResult.neighbourPlaces.livingRoom.owner, "his" ); + assertThat( uniqueResult ).isNotNull(); + assertThat( uniqueResult.neighbourPlaces.livingRoom.name ).isEqualTo( "Neighbour" ); + assertThat( uniqueResult.neighbourPlaces.livingRoom.owner ).isEqualTo( "his" ); criteria = criteriaBuilder.createQuery( HousePlaces.class ); root = criteria.from( HousePlaces.class ); join = root.join( "neighbourPlaces" ).join( "livingRoom" ); criteria.where( criteriaBuilder.equal( join.get( "owner" ), "his" ) ); - assertNotNull(s.createQuery( criteria ).uniqueResult()); + assertThat( s.createQuery( criteria ).uniqueResult() ).isNotNull(); // assertNotNull( s.createCriteria( HousePlaces.class ) // .add( Restrictions.eq( "neighbourPlaces.livingRoom.owner", "his" ) ).uniqueResult() ); @@ -261,28 +297,4 @@ public void testManyToOneInsideComponentReferencedColumn() { ); } - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - configuration.setImplicitNamingStrategy( ImplicitNamingStrategyLegacyJpaImpl.INSTANCE ); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - House.class, - Postman.class, - Bag.class, - Rambler.class, - Luggage.class, - Clothes.class, - Inhabitant.class, - Item.class, - ItemCost.class, - Vendor.class, - WarehouseItem.class, - Place.class, - HousePlaces.class - }; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Vendor.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Vendor.java index 6d6373acedc0..ab733396b094 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Vendor.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/Vendor.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.referencedcolumnname; + import jakarta.persistence.Entity; import jakarta.persistence.Id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/WarehouseItem.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/WarehouseItem.java index 731b9522d152..69b49464643e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/WarehouseItem.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/WarehouseItem.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.referencedcolumnname; + import java.math.BigDecimal; import jakarta.persistence.Entity; import jakarta.persistence.Id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/Administration.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/Administration.java index 80bd3657a165..a8a082df02b3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/Administration.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/Administration.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.reflection; + import jakarta.persistence.Basic; import jakarta.persistence.Entity; import jakarta.persistence.Id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/BusTrip.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/BusTrip.java index 6f9d86be2a7b..61aa2097d51c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/BusTrip.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/BusTrip.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.reflection; + import java.util.Date; import java.util.List; import java.util.Map; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/ElementCollectionConverterTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/ElementCollectionConverterTest.java index aafb59cb29df..4ded182e5912 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/ElementCollectionConverterTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/ElementCollectionConverterTest.java @@ -4,43 +4,31 @@ */ package org.hibernate.orm.test.annotations.reflection; -import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; - +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.JiraKeyGroup; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; - -@JiraKeyGroup( value = { - @JiraKey( value = "HHH-11924" ), - @JiraKey( value = "HHH-14529" ) -} ) -public class ElementCollectionConverterTest extends BaseCoreFunctionalTestCase { - - @Override - protected void prepareBootstrapRegistryBuilder(BootstrapServiceRegistryBuilder builder) { - super.prepareBootstrapRegistryBuilder( builder ); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Company.class, - }; - } - - @Override - protected String[] getOrmXmlFiles() { - return new String[] { "org/hibernate/orm/test/annotations/reflection/element-collection-converter-orm.xml" }; - } - +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +@JiraKeyGroup(value = { + @JiraKey(value = "HHH-11924"), + @JiraKey(value = "HHH-14529") +}) +@DomainModel( + annotatedClasses = { + Company.class + }, + xmlMappings = "org/hibernate/orm/test/annotations/reflection/element-collection-converter-orm.xml" +) +@SessionFactory +public class ElementCollectionConverterTest { @Test - public void testConverterIsAppliedToElementCollection() { - doInHibernate( this::sessionFactory, session -> { + public void testConverterIsAppliedToElementCollection(SessionFactoryScope scope) { + scope.inTransaction( session -> { Company company = new Company(); company.setId( 1L ); @@ -52,16 +40,16 @@ public void testConverterIsAppliedToElementCollection() { session.persist( company ); } ); - doInHibernate( this::sessionFactory, session -> { - String organizationId = (String) session - .createNativeQuery( "select organizations from Company_organizations" ) + scope.inTransaction( session -> { + String organizationId = session + .createNativeQuery( "select organizations from Company_organizations", String.class ) .getSingleResult(); - assertEquals( "ORG-ACME", organizationId ); + assertThat( organizationId ).isEqualTo( "ORG-ACME" ); Company company = session.find( Company.class, 1L ); - assertEquals( 1, company.getOrganizations().size() ); - assertEquals( "ACME" , company.getOrganizations().get( 0 ).getOrganizationId()); + assertThat( company.getOrganizations().size() ).isEqualTo( 1 ); + assertThat( company.getOrganizations().get( 0 ).getOrganizationId() ).isEqualTo( "ACME" ); } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/Match.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/Match.java index 265d1016f1ca..59d217174844 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/Match.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/Match.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.reflection; + import jakarta.persistence.Entity; import jakarta.persistence.Inheritance; import jakarta.persistence.InheritanceType; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/SocialSecurityMoralAccount.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/SocialSecurityMoralAccount.java index 5afbbf896d72..e24af0d340ea 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/SocialSecurityMoralAccount.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/SocialSecurityMoralAccount.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.reflection; + import jakarta.persistence.DiscriminatorValue; import jakarta.persistence.Entity; import jakarta.persistence.IdClass; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/SocialSecurityNumber.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/SocialSecurityNumber.java index 2b8522d70153..ddbf1cf1cdd3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/SocialSecurityNumber.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/SocialSecurityNumber.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.reflection; + import java.io.Serializable; import jakarta.persistence.Embeddable; @@ -21,9 +22,7 @@ public boolean equals(Object o) { final SocialSecurityNumber that = (SocialSecurityNumber) o; if ( !countryCode.equals( that.countryCode ) ) return false; - if ( !number.equals( that.number ) ) return false; - - return true; + return number.equals( that.number ); } public int hashCode() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/SocialSecurityPhysicalAccount.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/SocialSecurityPhysicalAccount.java index e7677cc4a89d..9778bc990b1a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/SocialSecurityPhysicalAccount.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/SocialSecurityPhysicalAccount.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.reflection; + import jakarta.persistence.Entity; /** diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/TennisMatch.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/TennisMatch.java index 7bd9e017b387..5bcaba301db5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/TennisMatch.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/TennisMatch.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.reflection; + import jakarta.persistence.AttributeOverride; import jakarta.persistence.AttributeOverrides; import jakarta.persistence.Column; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/secondarytable/SecondaryTableSchemaTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/secondarytable/SecondaryTableSchemaTest.java index b72018d0a2c5..c3fe529de582 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/secondarytable/SecondaryTableSchemaTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/secondarytable/SecondaryTableSchemaTest.java @@ -4,68 +4,64 @@ */ package org.hibernate.orm.test.annotations.secondarytable; -import java.io.Serializable; -import java.util.List; -import java.util.Map; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.PrimaryKeyJoinColumn; import jakarta.persistence.SecondaryTable; import jakarta.persistence.Table; - import org.hibernate.annotations.DynamicUpdate; import org.hibernate.annotations.OptimisticLockType; import org.hibernate.annotations.OptimisticLocking; import org.hibernate.annotations.SecondaryRow; import org.hibernate.cfg.AvailableSettings; import org.hibernate.dialect.H2Dialect; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryBasedFunctionalTest; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; -import org.hibernate.testing.RequiresDialect; -import org.junit.Test; +import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertTrue; /** * @author Vlad Mihalcea */ @RequiresDialect(value = H2Dialect.class) -public class SecondaryTableSchemaTest - extends BaseEntityManagerFunctionalTestCase { +public class SecondaryTableSchemaTest extends EntityManagerFactoryBasedFunctionalTest { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { - Cluster.class, - }; + return new Class[] {Cluster.class}; } protected void addConfigOptions(Map options) { options.put( - AvailableSettings.URL, - options.get( AvailableSettings.URL ) + ";INIT=CREATE SCHEMA IF NOT EXISTS schema1\\;CREATE SCHEMA IF NOT EXISTS schema2;" + AvailableSettings.URL, + options.get( AvailableSettings.URL ) + + ";INIT=CREATE SCHEMA IF NOT EXISTS schema1\\;CREATE SCHEMA IF NOT EXISTS schema2;" ); } @Test public void test() { - doInJPA( this::entityManagerFactory, entityManager -> { - List clusters = entityManager.createQuery( "select c from Cluster c" ).getResultList(); + inTransaction( entityManager -> { + List clusters = entityManager.createQuery( "select c from Cluster c", Cluster.class ) + .getResultList(); - assertTrue(clusters.isEmpty()); + assertThat( clusters.isEmpty() ).isTrue(); } ); } @Entity(name = "Cluster") @Table(name = "cluster", schema = "schema1") - @SecondaryTable(name = "Cluster", schema="schema2", pkJoinColumns = { @PrimaryKeyJoinColumn(name = "clusterid") }) + @SecondaryTable(name = "Cluster", schema = "schema2", pkJoinColumns = {@PrimaryKeyJoinColumn(name = "clusterid")}) @SecondaryRow(table = "Cluster", optional = false) @OptimisticLocking(type = OptimisticLockType.DIRTY) @DynamicUpdate - public static class Cluster implements Serializable { - private static final long serialVersionUID = 3965099001305947412L; + public static class Cluster { @Id @Column(name = "objid") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/strategy/Storm.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/strategy/Storm.java index 533071ff3524..1c4af93e71ab 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/strategy/Storm.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/strategy/Storm.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.strategy; + import jakarta.persistence.Column; import jakarta.persistence.Embedded; import jakarta.persistence.Entity; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/strategy/StrategyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/strategy/StrategyTest.java index 870749cb2e69..219a53f2aa93 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/strategy/StrategyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/strategy/StrategyTest.java @@ -4,45 +4,57 @@ */ package org.hibernate.orm.test.annotations.strategy; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.boot.MetadataBuilder; +import org.hibernate.boot.model.naming.ImplicitNamingStrategy; import org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl; - -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.cfg.AvailableSettings; +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.SettingProvider; +import org.junit.jupiter.api.Test; /** * @author Emmanuel Bernard */ -public class StrategyTest extends BaseNonConfigCoreFunctionalTestCase { - @Test - public void testComponentSafeStrategy() throws Exception { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Location start = new Location(); - start.setCity( "Paris" ); - start.setCountry( "France" ); - Location end = new Location(); - end.setCity( "London" ); - end.setCountry( "UK" ); - Storm storm = new Storm(); - storm.setEnd( end ); - storm.setStart( start ); - s.persist( storm ); - s.flush(); - tx.rollback(); - s.close(); - } +@DomainModel( + annotatedClasses = { + Storm.class + } +) +@SessionFactory +@ServiceRegistry( + settingProviders = @SettingProvider( + settingName = AvailableSettings.IMPLICIT_NAMING_STRATEGY, + provider = StrategyTest.ImplicitNamyStrategyProvider.class + ) +) +public class StrategyTest { - @Override - protected void configureMetadataBuilder(MetadataBuilder metadataBuilder) { - super.configureMetadataBuilder( metadataBuilder ); - metadataBuilder.applyImplicitNamingStrategy( ImplicitNamingStrategyComponentPathImpl.INSTANCE ); + public static class ImplicitNamyStrategyProvider implements SettingProvider.Provider { + @Override + public ImplicitNamingStrategy getSetting() { + return ImplicitNamingStrategyComponentPathImpl.INSTANCE; + } } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Storm.class }; + + @Test + public void testComponentSafeStrategy(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Location start = new Location(); + start.setCity( "Paris" ); + start.setCountry( "France" ); + Location end = new Location(); + end.setCity( "London" ); + end.setCountry( "UK" ); + Storm storm = new Storm(); + storm.setEnd( end ); + storm.setStart( start ); + session.persist( storm ); + session.flush(); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/subselect/Bid.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/subselect/Bid.java index c1293d7f33e0..75d265773f80 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/subselect/Bid.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/subselect/Bid.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.subselect; + import jakarta.persistence.Entity; import jakarta.persistence.Id; @@ -21,18 +22,23 @@ public class Bid { public int getId() { return id; } + public void setId(int id) { this.id = id; } + public long getItemId() { return itemId; } + public void setItemId(long itemId) { this.itemId = itemId; } + public double getAmount() { return amount; } + public void setAmount(double val) { this.amount = val; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/subselect/HighestBid.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/subselect/HighestBid.java index 105225fd0ed7..2f2cf1b7376a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/subselect/HighestBid.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/subselect/HighestBid.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.subselect; + import jakarta.persistence.Entity; import jakarta.persistence.Id; @@ -25,12 +26,15 @@ public class HighestBid { public String getName() { return name; } + public void setName(String val) { this.name = val; } + public double getAmount() { return amount; } + public void setAmount(double amount) { this.amount = amount; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/subselect/Item.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/subselect/Item.java index 0476a2bd4e86..1794903094ee 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/subselect/Item.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/subselect/Item.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.subselect; + import jakarta.persistence.Entity; import jakarta.persistence.Id; @@ -19,12 +20,15 @@ public class Item { public long getId() { return id; } + public void setId(long id) { this.id = id; } + public String getName() { return name; } + public void setName(String name) { this.name = name; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/subselect/SubselectTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/subselect/SubselectTest.java index 863bc5afde39..79369f1dfb23 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/subselect/SubselectTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/subselect/SubselectTest.java @@ -4,62 +4,60 @@ */ package org.hibernate.orm.test.annotations.subselect; -import org.junit.Assert; -import org.junit.Test; - -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.type.StandardBasicTypes; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Sharath Reddy */ -public class SubselectTest extends BaseCoreFunctionalTestCase { - @Test - public void testSubselectWithSynchronize() { - - Session s = openSession(); - Transaction tx = s.beginTransaction(); - - //We don't use auto-generated ids because these seem to cause the session to flush. - //We want to test that the session flushes because of the 'synchronize' annotation - long itemId = 1; - Item item = new Item(); - item.setName("widget"); - item.setId(itemId); - s.persist(item); - - Bid bid1 = new Bid(); - bid1.setAmount(100.0); - bid1.setItemId(itemId); - bid1.setId(1); - s.persist(bid1); - - Bid bid2 = new Bid(); - bid2.setAmount(200.0); - bid2.setItemId(itemId); - bid2.setId(2); - s.persist(bid2); - - //Because we use 'synchronize' annotation, this query should trigger session flush - var query = s.createQuery("from HighestBid b where b.name = :name", HighestBid.class); - query.setParameter( "name", "widget", StandardBasicTypes.STRING ); - HighestBid highestBid = query.list().iterator().next(); - - Assert.assertEquals( 200.0, highestBid.getAmount(), 0.01 ); - tx.rollback(); - s.close(); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ +@DomainModel( + annotatedClasses = { Item.class, Bid.class, HighestBid.class - }; + } +) +@SessionFactory +public class SubselectTest { + + @Test + public void testSubselectWithSynchronize(SessionFactoryScope scope) { + //We don't use auto-generated ids because these seem to cause the session to flush. + //We want to test that the session flushes because of the 'synchronize' annotation + scope.inTransaction( + session -> { + long itemId = 1; + Item item = new Item(); + item.setName( "widget" ); + item.setId( itemId ); + session.persist( item ); + + Bid bid1 = new Bid(); + bid1.setAmount( 100.0 ); + bid1.setItemId( itemId ); + bid1.setId( 1 ); + session.persist( bid1 ); + + Bid bid2 = new Bid(); + bid2.setAmount( 200.0 ); + bid2.setItemId( itemId ); + bid2.setId( 2 ); + session.persist( bid2 ); + + //Because we use 'synchronize' annotation, this query should trigger session flush + var query = session.createQuery( "from HighestBid b where b.name = :name", HighestBid.class ); + query.setParameter( "name", "widget", StandardBasicTypes.STRING ); + HighestBid highestBid = query.list().iterator().next(); + + assertEquals( 200.0, highestBid.getAmount(), 0.01 ); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/target/Brand.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/target/Brand.java index 0085384e4597..a5c590ffade0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/target/Brand.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/target/Brand.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.target; + import java.util.HashMap; import java.util.Map; import jakarta.persistence.ElementCollection; @@ -24,12 +25,12 @@ public class Brand { @ManyToMany(targetEntity = LuggageImpl.class) @MapKeyClass(SizeImpl.class) - private Map luggagesBySize = new HashMap(); + private Map luggagesBySize = new HashMap<>(); @ElementCollection(targetClass = SizeImpl.class) @MapKeyClass(LuggageImpl.class) @MapKeyJoinColumn - private Map sizePerLuggage = new HashMap(); + private Map sizePerLuggage = new HashMap<>(); public Long getId() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/target/LuggageImpl.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/target/LuggageImpl.java index 2e94e106a53c..e2fce48d8007 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/target/LuggageImpl.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/target/LuggageImpl.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.target; + import jakarta.persistence.Embedded; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/target/Owner.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/target/Owner.java index 67d5ca060b64..aa7df316a423 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/target/Owner.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/target/Owner.java @@ -4,8 +4,6 @@ */ package org.hibernate.orm.test.annotations.target; - - /** * @author Emmanuel Bernard */ diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/target/OwnerImpl.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/target/OwnerImpl.java index dda5c0ef6df7..f1145ede2e0d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/target/OwnerImpl.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/target/OwnerImpl.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.target; + import jakarta.persistence.Embeddable; /** diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/target/SizeImpl.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/target/SizeImpl.java index 5247267fe374..6000b49cb6f1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/target/SizeImpl.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/target/SizeImpl.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.target; + import jakarta.persistence.Column; import jakarta.persistence.Embeddable; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/target/TargetTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/target/TargetTest.java index 55fdaafb1f67..ba2f2dac7f6b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/target/TargetTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/target/TargetTest.java @@ -4,86 +4,97 @@ */ package org.hibernate.orm.test.annotations.target; -import org.junit.Test; -import org.hibernate.Session; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +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 static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Emmanuel Bernard */ -public class TargetTest extends BaseCoreFunctionalTestCase { - @Test - public void testTargetOnEmbedded() throws Exception { - Session s = openSession(); - s.getTransaction().begin(); - Luggage l = new LuggageImpl(); - l.setHeight( 12 ); - l.setWidth( 12 ); - Owner o = new OwnerImpl(); - o.setName( "Emmanuel" ); - l.setOwner( o ); - s.persist( l ); - s.flush(); - s.clear(); - l = (Luggage) s.get(LuggageImpl.class, ( (LuggageImpl) l).getId() ); - assertEquals( "Emmanuel", l.getOwner().getName() ); - s.getTransaction().rollback(); - s.close(); +@DomainModel( + annotatedClasses = { + LuggageImpl.class, + Brand.class + } +) +@SessionFactory +public class TargetTest { + + @AfterEach + public void afterEach(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Test - public void testTargetOnMapKey() throws Exception { - Session s = openSession(); - s.getTransaction().begin(); - Luggage l = new LuggageImpl(); - l.setHeight( 12 ); - l.setWidth( 12 ); - Size size = new SizeImpl(); - size.setName( "S" ); - Owner o = new OwnerImpl(); - o.setName( "Emmanuel" ); - l.setOwner( o ); - s.persist( l ); - Brand b = new Brand(); - s.persist( b ); - b.getLuggagesBySize().put( size, l ); - s.flush(); - s.clear(); - b = (Brand) s.get(Brand.class, b.getId() ); - assertEquals( "S", b.getLuggagesBySize().keySet().iterator().next().getName() ); - s.getTransaction().rollback(); - s.close(); + public void testTargetOnEmbedded(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + LuggageImpl l = new LuggageImpl(); + l.setHeight( 12 ); + l.setWidth( 12 ); + Owner o = new OwnerImpl(); + o.setName( "Emmanuel" ); + l.setOwner( o ); + session.persist( l ); + session.flush(); + session.clear(); + l = session.find( LuggageImpl.class, l.getId() ); + assertEquals( "Emmanuel", l.getOwner().getName() ); + } + ); } @Test - public void testTargetOnMapKeyManyToMany() throws Exception { - Session s = openSession(); - s.getTransaction().begin(); - Luggage l = new LuggageImpl(); - l.setHeight( 12 ); - l.setWidth( 12 ); - Size size = new SizeImpl(); - size.setName( "S" ); - Owner o = new OwnerImpl(); - o.setName( "Emmanuel" ); - l.setOwner( o ); - s.persist( l ); - Brand b = new Brand(); - s.persist( b ); - b.getSizePerLuggage().put( l, size ); - s.flush(); - s.clear(); - b = (Brand) s.get(Brand.class, b.getId() ); - assertEquals( 12d, b.getSizePerLuggage().keySet().iterator().next().getWidth(), 0.01 ); - s.getTransaction().rollback(); - s.close(); + public void testTargetOnMapKey(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Luggage l = new LuggageImpl(); + l.setHeight( 12 ); + l.setWidth( 12 ); + Size size = new SizeImpl(); + size.setName( "S" ); + Owner o = new OwnerImpl(); + o.setName( "Emmanuel" ); + l.setOwner( o ); + session.persist( l ); + Brand b = new Brand(); + session.persist( b ); + b.getLuggagesBySize().put( size, l ); + session.flush(); + session.clear(); + b = session.find( Brand.class, b.getId() ); + assertEquals( "S", b.getLuggagesBySize().keySet().iterator().next().getName() ); + } + ); } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { LuggageImpl.class, Brand.class }; + @Test + public void testTargetOnMapKeyManyToMany(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Luggage l = new LuggageImpl(); + l.setHeight( 12 ); + l.setWidth( 12 ); + Size size = new SizeImpl(); + size.setName( "S" ); + Owner o = new OwnerImpl(); + o.setName( "Emmanuel" ); + l.setOwner( o ); + session.persist( l ); + Brand b = new Brand(); + session.persist( b ); + b.getSizePerLuggage().put( l, size ); + session.flush(); + session.clear(); + b = session.find( Brand.class, b.getId() ); + assertEquals( 12d, b.getSizePerLuggage().keySet().iterator().next().getWidth(), 0.01 ); + } + ); } + } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/type/Dvd.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/type/Dvd.java index 9d97315285a3..028b15238c81 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/type/Dvd.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/type/Dvd.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.type; + import jakarta.persistence.AttributeOverride; import jakarta.persistence.Column; import jakarta.persistence.EmbeddedId; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/type/TypeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/type/TypeTest.java index 64b4846388c7..cb421249694c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/type/TypeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/type/TypeTest.java @@ -4,35 +4,35 @@ */ package org.hibernate.orm.test.annotations.type; -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.Test; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertNotNull; /** * @author Emmanuel Bernard */ -public class TypeTest extends BaseCoreFunctionalTestCase { - @Test - public void testIdWithMulticolumns() { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - Dvd lesOiseaux = new Dvd(); - lesOiseaux.setTitle( "Les oiseaux" ); - s.persist( lesOiseaux ); - s.flush(); - assertNotNull( lesOiseaux.getId() ); - tx.rollback(); - s.close(); - } +@DomainModel( + annotatedClasses = { + Dvd.class + } +) +@SessionFactory +public class TypeTest { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ Dvd.class }; + @Test + public void testIdWithMulticolumns(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Dvd lesOiseaux = new Dvd(); + lesOiseaux.setTitle( "Les oiseaux" ); + session.persist( lesOiseaux ); + session.flush(); + assertThat( lesOiseaux.getId() ).isNotNull(); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/UniqueConstraintBatchingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/UniqueConstraintBatchingTest.java index 82c08cc30449..1c550ed653d5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/UniqueConstraintBatchingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/UniqueConstraintBatchingTest.java @@ -60,7 +60,7 @@ public void testBatching(EntityManagerFactoryScope scope) throws Exception { scope.inTransaction( entityManager -> { - livingRoom.setId( 1l ); + livingRoom.setId( 1L ); livingRoom.setName( "livingRoom" ); entityManager.persist( livingRoom ); } ); @@ -68,9 +68,9 @@ public void testBatching(EntityManagerFactoryScope scope) throws Exception { scope.inTransaction( entityManager -> { House house = new House(); - house.setId( 1l ); + house.setId( 1L ); house.setCost( 100 ); - house.setHeight( 1000l ); + house.setHeight( 1000L ); house.setRoom( livingRoom ); entityManager.persist( house ); } ); @@ -79,9 +79,9 @@ public void testBatching(EntityManagerFactoryScope scope) throws Exception { scope.inTransaction( entityManager -> { House house2 = new House(); - house2.setId( 2l ); + house2.setId( 2L ); house2.setCost( 100 ); - house2.setHeight( 1001l ); + house2.setHeight( 1001L ); house2.setRoom( livingRoom ); entityManager.persist( house2 ); } ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/UniqueConstraintThrowsConstraintViolationExceptionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/UniqueConstraintThrowsConstraintViolationExceptionTest.java index a42c3c04ebf5..3f07a342f62f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/UniqueConstraintThrowsConstraintViolationExceptionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/UniqueConstraintThrowsConstraintViolationExceptionTest.java @@ -10,56 +10,43 @@ import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; -import jakarta.persistence.PersistenceException; import jakarta.persistence.Table; - import org.hibernate.exception.ConstraintViolationException; - +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.assertThrows; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; /** * @author Vlad Mihalcea */ @JiraKey(value = "HHH-11236") -public class UniqueConstraintThrowsConstraintViolationExceptionTest extends BaseCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + UniqueConstraintThrowsConstraintViolationExceptionTest.Customer.class + } +) +@SessionFactory +public class UniqueConstraintThrowsConstraintViolationExceptionTest { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Customer.class }; - } @Test - public void testUniqueConstraintWithEmptyColumnName() { - doInHibernate( this::sessionFactory, session -> { + public void testUniqueConstraintWithEmptyColumnName(SessionFactoryScope scope) { + scope.inTransaction( session -> { Customer customer1 = new Customer(); customer1.customerId = "123"; session.persist( customer1 ); } ); - try { - doInHibernate( this::sessionFactory, session -> { - Customer customer1 = new Customer(); - customer1.customerId = "123"; - session.persist( customer1 ); - } ); - fail( "Should throw" ); - } - catch ( PersistenceException e ) { - assertEquals( - ConstraintViolationException.class, - e.getClass() - ); - } - } - @Override - protected boolean isCleanupTestDataRequired() { - return true; + assertThrows( ConstraintViolationException.class, () -> scope.inTransaction( session -> { + Customer customer1 = new Customer(); + customer1.customerId = "123"; + session.persist( customer1 ); + } ) ); } @Entity(name = "Customer") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/UniqueConstraintUnitTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/UniqueConstraintUnitTests.java index 2d8f4ec77349..02c46ed5024d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/UniqueConstraintUnitTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/UniqueConstraintUnitTests.java @@ -4,8 +4,6 @@ */ package org.hibernate.orm.test.annotations.uniqueconstraint; -import java.util.HashSet; -import java.util.Set; import jakarta.persistence.CollectionTable; import jakarta.persistence.Column; import jakarta.persistence.ElementCollection; @@ -16,29 +14,31 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.Table; import jakarta.persistence.UniqueConstraint; - import org.hibernate.AnnotationException; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; - +import org.hibernate.testing.orm.junit.BaseUnitTest; 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; + +import java.util.HashSet; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Fail.fail; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Steve Ebersole */ -public class UniqueConstraintUnitTests extends BaseUnitTestCase { +@BaseUnitTest +public class UniqueConstraintUnitTests { @Test - @JiraKey( value = "HHH-8026" ) + @JiraKey(value = "HHH-8026") public void testUnNamedConstraints() { StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry(); @@ -59,12 +59,11 @@ else if ( table.getName().equals( "UniqueNoNameB" ) ) { } } - assertTrue( "Could not find the expected tables.", tableA != null && tableB != null ); - assertFalse( - tableA.getUniqueKeys().values().iterator().next().getName().equals( - tableB.getUniqueKeys().values().iterator().next().getName() - ) - ); + assertThat( tableA != null && tableB != null ) + .describedAs( "Could not find the expected tables." ) + .isTrue(); + assertThat( tableA.getUniqueKeys().values().iterator().next().getName() ) + .isNotEqualTo( tableB.getUniqueKeys().values().iterator().next().getName() ); } finally { StandardServiceRegistryBuilder.destroy( ssr ); @@ -72,12 +71,12 @@ else if ( table.getName().equals( "UniqueNoNameB" ) ) { } @Test - @JiraKey( value = "HHH-8537" ) + @JiraKey(value = "HHH-8537") public void testNonExistentColumn() { StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry(); try { - final Metadata metadata = new MetadataSources( ssr ) + new MetadataSources( ssr ) .addAnnotatedClass( UniqueNoNameA.class ) .addAnnotatedClass( UniqueNoNameB.class ) .buildMetadata(); @@ -94,8 +93,8 @@ public void testNonExistentColumn() { } @Entity - @Table( name = "UniqueNoNameA", - uniqueConstraints = {@UniqueConstraint(columnNames={"name"})}) + @Table(name = "UniqueNoNameA", + uniqueConstraints = {@UniqueConstraint(columnNames = {"name"})}) public static class UniqueNoNameA { @Id @GeneratedValue @@ -105,8 +104,8 @@ public static class UniqueNoNameA { } @Entity - @Table( name = "UniqueNoNameB", - uniqueConstraints = {@UniqueConstraint(columnNames={"name"})}) + @Table(name = "UniqueNoNameB", + uniqueConstraints = {@UniqueConstraint(columnNames = {"name"})}) public static class UniqueNoNameB { @Id @GeneratedValue @@ -125,9 +124,9 @@ public static class UniqueColumnDoesNotExist { name = "tbl_strings", joinColumns = @JoinColumn(name = "fk", nullable = false), // the failure required at least 1 columnName to be correct -- all incorrect wouldn't reproduce - uniqueConstraints = @UniqueConstraint(columnNames = { "fk", "doesnotexist" }) + uniqueConstraints = @UniqueConstraint(columnNames = {"fk", "doesnotexist"}) ) @Column(name = "string", nullable = false) - public Set strings = new HashSet(); + public Set strings = new HashSet<>(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/UniqueConstraintValidationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/UniqueConstraintValidationTest.java index a40115bc631c..c998a1c8be49 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/UniqueConstraintValidationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/UniqueConstraintValidationTest.java @@ -4,37 +4,43 @@ */ package org.hibernate.orm.test.annotations.uniqueconstraint; -import java.io.Serializable; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; import jakarta.persistence.UniqueConstraint; - import org.hibernate.AnnotationException; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; - +import org.hibernate.testing.orm.junit.BaseUnitTest; 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; + +import java.io.Serializable; + +import static org.junit.jupiter.api.Assertions.assertThrows; /** * @author Nikolay Shestakov * */ -public class UniqueConstraintValidationTest extends BaseUnitTestCase { +@BaseUnitTest +public class UniqueConstraintValidationTest { - @Test(expected = AnnotationException.class) + @Test @JiraKey(value = "HHH-4084") public void testUniqueConstraintWithEmptyColumnName() { - buildSessionFactory(EmptyColumnNameEntity.class); + assertThrows( AnnotationException.class, () -> + buildSessionFactory( EmptyColumnNameEntity.class ) + ); } - @Test(expected = AnnotationException.class) + @Test public void testUniqueConstraintWithEmptyColumnNameList() { - buildSessionFactory(EmptyColumnNameListEntity.class); + assertThrows( AnnotationException.class, () -> + buildSessionFactory( EmptyColumnNameListEntity.class ) + ); } @Test diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/Conductor.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/Conductor.java index 6bfa5f72728b..1ae64062efdf 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/Conductor.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/Conductor.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.various; + import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/DBTimestamped.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/DBTimestamped.java index 853d07ee602b..36acae97dd1e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/DBTimestamped.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/DBTimestamped.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.various; + import java.util.Date; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/GeneratedTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/GeneratedTest.java index 77dce664311d..549d9982c603 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/GeneratedTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/GeneratedTest.java @@ -25,7 +25,7 @@ public void testGenerated(SessionFactoryScope scope) { scope.inTransaction( session -> { Antenna antenna = new Antenna(); - antenna.id = new Integer( 1 ); + antenna.id = 1; session.persist( antenna ); assertNull( antenna.latitude ); assertNull( antenna.longitude ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/OneOneGeneratedValueTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/OneOneGeneratedValueTest.java index 7a1732207b19..91d98bb24527 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/OneOneGeneratedValueTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/OneOneGeneratedValueTest.java @@ -34,17 +34,17 @@ public class OneOneGeneratedValueTest { public void testIt(SessionFactoryScope scope) { scope.inTransaction( session -> { - EntityA entityA = new EntityA( 1l ); + EntityA entityA = new EntityA( 1L ); session.persist( entityA ); } ); scope.inTransaction( session -> { - EntityA entityA = session.get( EntityA.class, 1l ); + EntityA entityA = session.get( EntityA.class, 1L ); assertThat( entityA ).isNotNull(); EntityB entityB = entityA.getB(); assertThat( entityB ).isNotNull(); - assertThat( entityB.getB() ).isEqualTo( 5l ); + assertThat( entityB.getB() ).isEqualTo( 5L ); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/OneToOneOptimisticLockTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/OneToOneOptimisticLockTest.java index fa0726ee51ba..e0ad0c2745f9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/OneToOneOptimisticLockTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/OneToOneOptimisticLockTest.java @@ -43,7 +43,7 @@ public void setUp(SessionFactoryScope scope) { public void testUpdateChildDoesNotIncrementParentVersion(SessionFactoryScope scope) { Integer version = scope.fromTransaction( session -> { - Parent parent = session.get( Parent.class, PARENT_ID ); + Parent parent = session.find( Parent.class, PARENT_ID ); Integer vers = parent.getVersion(); Child child = new Child( 2 ); @@ -56,7 +56,7 @@ public void testUpdateChildDoesNotIncrementParentVersion(SessionFactoryScope sco scope.inTransaction( session -> { - Parent parent = session.get( Parent.class, PARENT_ID ); + Parent parent = session.find( Parent.class, PARENT_ID ); assertThat( parent.getVersion() ).isEqualTo( version ); } ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/OptimisticLockAnnotationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/OptimisticLockAnnotationTest.java index 4e1cca6e7a23..8366f20b6c65 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/OptimisticLockAnnotationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/OptimisticLockAnnotationTest.java @@ -25,8 +25,6 @@ public class OptimisticLockAnnotationTest { @Test public void testOptimisticLockExcludeOnNameProperty(SessionFactoryScope scope) { - - scope.inTransaction( session -> { Conductor c = new Conductor(); @@ -36,14 +34,14 @@ public void testOptimisticLockExcludeOnNameProperty(SessionFactoryScope scope) { session.clear(); - c = session.get( Conductor.class, c.getId() ); + c = session.find( Conductor.class, c.getId() ); Long version = c.getVersion(); c.setName( "Don" ); session.flush(); session.clear(); - c = session.get( Conductor.class, c.getId() ); + c = session.find( Conductor.class, c.getId() ); assertEquals( version, c.getVersion() ); } ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/TimestampTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/TimestampTest.java index 9e5a57903f23..efa56c34d3c8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/TimestampTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/TimestampTest.java @@ -10,29 +10,28 @@ import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Property; +import org.hibernate.testing.orm.junit.BaseUnitTest; +import org.hibernate.testing.util.ServiceRegistryUtil; import org.hibernate.type.BasicType; import org.hibernate.type.BasicTypeReference; import org.hibernate.type.StandardBasicTypes; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.AfterClassOnce; -import org.hibernate.testing.BeforeClassOnce; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Test for the @Timestamp annotation. * * @author Hardy Ferentschik */ -public class TimestampTest extends BaseUnitTestCase { +@BaseUnitTest +public class TimestampTest { private StandardServiceRegistry ssr; private MetadataImplementor metadata; - @BeforeClassOnce + @BeforeAll public void setUp() { ssr = ServiceRegistryUtil.serviceRegistry(); metadata = (MetadataImplementor) new MetadataSources( ssr ) @@ -42,7 +41,7 @@ public void setUp() { .build(); } - @AfterClassOnce + @AfterAll public void tearDown() { if ( ssr != null ) { StandardServiceRegistryBuilder.destroy( ssr ); @@ -65,9 +64,11 @@ private void assertTimestampSource(Class clazz, BasicTypeReference typeRef private void assertTimestampSource(Class clazz, BasicType basicType) throws Exception { PersistentClass persistentClass = metadata.getEntityBinding( clazz.getName() ); - assertNotNull( persistentClass ); + assertThat( persistentClass ).isNotNull(); Property versionProperty = persistentClass.getVersion(); - assertNotNull( versionProperty ); - assertEquals( "Wrong timestamp type", basicType, versionProperty.getType() ); + assertThat( versionProperty ).isNotNull(); + assertThat( versionProperty.getType() ) + .describedAs( "Wrong timestamp type" ) + .isEqualTo( basicType ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/Truck.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/Truck.java index 40d1fa90d993..e057458c7b8a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/Truck.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/Truck.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.various; + import jakarta.persistence.Entity; import jakarta.persistence.Index; import jakarta.persistence.JoinColumn; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/Vehicule.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/Vehicule.java index 22c3364de426..77e3f5b498d5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/Vehicule.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/Vehicule.java @@ -40,7 +40,7 @@ public class Vehicule { private Conductor currentConductor; @Column(name = "`year`") private Integer year; - @ManyToOne(optional = true) + @ManyToOne private Conductor previousConductor; public String getId() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/CarModel.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/CarModel.java index f22ac8c54ed9..1e7938fb6bc4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/CarModel.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/CarModel.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.xml.ejb3; + import jakarta.persistence.Column; import java.util.Date; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Company.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Company.java index 0d06f8c6a331..c01c60c37baf 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Company.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Company.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.xml.ejb3; + import java.util.HashMap; import java.util.Map; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Ejb3XmlElementCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Ejb3XmlElementCollectionTest.java index 11f453b14919..3e67269b3258 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Ejb3XmlElementCollectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Ejb3XmlElementCollectionTest.java @@ -8,7 +8,6 @@ import org.hibernate.models.spi.MemberDetails; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; import jakarta.persistence.Access; import jakarta.persistence.AccessType; @@ -37,12 +36,14 @@ import jakarta.persistence.Temporal; import jakarta.persistence.TemporalType; import jakarta.persistence.UniqueConstraint; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("deprecation") @JiraKey("HHH-14529") public class Ejb3XmlElementCollectionTest extends Ejb3XmlTestCase { + @Test public void testNoChildren() { final MemberDetails memberDetails = getAttributeMember( Entity2.class, "field1", "element-collection.orm1.xml" ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Ejb3XmlManyToOneTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Ejb3XmlManyToOneTest.java index 3f8dcd1dcb5a..1fe0fd48fd9e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Ejb3XmlManyToOneTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Ejb3XmlManyToOneTest.java @@ -13,7 +13,6 @@ import org.hibernate.models.spi.MemberDetails; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; import jakarta.persistence.Access; import jakarta.persistence.AccessType; @@ -25,11 +24,13 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.MapsId; import jakarta.persistence.UniqueConstraint; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @JiraKey("HHH-14529") public class Ejb3XmlManyToOneTest extends Ejb3XmlTestCase { + @Test public void testNoJoins() { final MemberDetails memberDetails = getAttributeMember( Entity1.class, "field1", "many-to-one.orm1.xml" ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Ejb3XmlOneToOneTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Ejb3XmlOneToOneTest.java index 684794711c51..9103d7989ae7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Ejb3XmlOneToOneTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Ejb3XmlOneToOneTest.java @@ -12,7 +12,6 @@ import org.hibernate.models.spi.MemberDetails; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; import jakarta.persistence.Access; import jakarta.persistence.AccessType; @@ -26,11 +25,13 @@ import jakarta.persistence.PrimaryKeyJoinColumn; import jakarta.persistence.PrimaryKeyJoinColumns; import jakarta.persistence.UniqueConstraint; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @JiraKey("HHH-14529") public class Ejb3XmlOneToOneTest extends Ejb3XmlTestCase { + @Test public void testNoChildren() { final MemberDetails memberDetails = getAttributeMember( Entity1.class, "field1", "one-to-one.orm1.xml" ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Ejb3XmlTestCase.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Ejb3XmlTestCase.java index 6e39a12c0fbf..38f91a7a8652 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Ejb3XmlTestCase.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Ejb3XmlTestCase.java @@ -26,11 +26,11 @@ import org.hibernate.models.spi.ModelsContext; import org.hibernate.testing.boot.BootstrapContextImpl; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.junit.After; -import org.junit.Before; +import org.hibernate.testing.orm.junit.BaseUnitTest; import jakarta.persistence.Transient; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import static org.hibernate.models.internal.SimpleClassLoading.SIMPLE_CLASS_LOADING; @@ -39,18 +39,19 @@ * XML to JPA annotations. The configuration is built within each test, and no * database is used. Thus, no schema generation or cleanup will be performed. */ -public abstract class Ejb3XmlTestCase extends BaseUnitTestCase { +@BaseUnitTest +public abstract class Ejb3XmlTestCase { private BootstrapContextImpl bootstrapContext; protected Ejb3XmlTestCase() { } - @Before + @BeforeEach public void init() { bootstrapContext = new BootstrapContextImpl(); } - @After + @AfterEach public void destroy() { bootstrapContext.close(); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Entity2.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Entity2.java index ec1aa9a2701e..780fe48f44cd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Entity2.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Entity2.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.xml.ejb3; + import java.util.List; public class Entity2 { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Entity3.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Entity3.java index ea5dafa2fba8..7209da60ae8f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Entity3.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Entity3.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.annotations.xml.ejb3; + import java.util.Map; public class Entity3 { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Manufacturer.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Manufacturer.java index 303c0e50f7f3..e82a79e6684f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Manufacturer.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Manufacturer.java @@ -20,7 +20,7 @@ @TableGenerator(name = "generator", table = "this is a broken name with select from and other SQL keywords") public class Manufacturer { private Integer id; - private Set models = new HashSet(); + private Set models = new HashSet<>(); @Id public Integer getId() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/NonExistentOrmVersionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/NonExistentOrmVersionTest.java index b9de74a43f85..7601b06e7214 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/NonExistentOrmVersionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/NonExistentOrmVersionTest.java @@ -8,28 +8,29 @@ import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.BootstrapServiceRegistry; import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; - +import org.hibernate.testing.orm.junit.BaseUnitTest; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.orm.junit.JiraKeyGroup; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.Assert.fail; -@JiraKeyGroup( value = { - @JiraKey( value = "HHH-6271" ), - @JiraKey( value = "HHH-14529" ) -} ) -public class NonExistentOrmVersionTest extends BaseUnitTestCase { +@JiraKeyGroup(value = { + @JiraKey(value = "HHH-6271"), + @JiraKey(value = "HHH-14529") +}) +@BaseUnitTest +public class NonExistentOrmVersionTest { + @Test public void testNonExistentOrmVersion() { try (BootstrapServiceRegistry serviceRegistry = new BootstrapServiceRegistryBuilder().build()) { - new MetadataSources( serviceRegistry ) - .addResource( "org/hibernate/orm/test/annotations/xml/ejb3/orm5.xml" ) - .buildMetadata(); - fail( "Expecting failure due to unsupported xsd version" ); - } - catch ( InvalidMappingException expected ) { + assertThrows( InvalidMappingException.class, () -> new MetadataSources( serviceRegistry ) + .addResource( "org/hibernate/orm/test/annotations/xml/ejb3/orm5.xml" ) + .buildMetadata() + , "Expecting failure due to unsupported xsd version" + ); } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/OrmVersion1SupportedTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/OrmVersion1SupportedTest.java index a1f633282596..1707e01790f6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/OrmVersion1SupportedTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/OrmVersion1SupportedTest.java @@ -4,44 +4,37 @@ */ package org.hibernate.orm.test.annotations.xml.ejb3; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.orm.junit.JiraKeyGroup; -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.assertj.core.api.Assertions.assertThat; -@JiraKeyGroup( value = { - @JiraKey( value = "HHH-6271" ), - @JiraKey( value = "HHH-14529" ) -} ) -public class OrmVersion1SupportedTest extends BaseCoreFunctionalTestCase { - - @Override - protected void prepareBootstrapRegistryBuilder(BootstrapServiceRegistryBuilder builder) { - super.prepareBootstrapRegistryBuilder( builder ); - } +@JiraKeyGroup(value = { + @JiraKey(value = "HHH-6271"), + @JiraKey(value = "HHH-14529") +}) +@DomainModel( + xmlMappings = "org/hibernate/orm/test/annotations/xml/ejb3/orm2.xml" +) +@SessionFactory +public class OrmVersion1SupportedTest { @Test - public void testOrm1Support() { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Light light = new Light(); - light.name = "the light at the end of the tunnel"; - s.persist( light ); - s.flush(); - s.clear(); - - assertEquals( 1, s.getNamedQuery( "find.the.light" ).list().size() ); - tx.rollback(); - s.close(); - } + public void testOrm1Support(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Light light = new Light(); + light.name = "the light at the end of the tunnel"; + session.persist( light ); + session.flush(); + session.clear(); - @Override - protected String[] getOrmXmlFiles() { - return new String[] { "org/hibernate/orm/test/annotations/xml/ejb3/orm2.xml" }; + assertThat( session.getNamedQuery( "find.the.light" ).list().size() ).isEqualTo( 1 ); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/PreParsedOrmXmlTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/PreParsedOrmXmlTest.java index 7837cc580d9f..12490ea0902a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/PreParsedOrmXmlTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/PreParsedOrmXmlTest.java @@ -4,55 +4,36 @@ */ package org.hibernate.orm.test.annotations.xml.ejb3; -import java.io.IOException; -import java.io.InputStream; -import java.io.UncheckedIOException; - -import org.hibernate.boot.jaxb.internal.InputStreamXmlSource; -import org.hibernate.boot.jaxb.spi.Binding; -import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; -import org.hibernate.cfg.Configuration; - -import org.hibernate.testing.DialectChecks; -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.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import org.hibernate.testing.orm.junit.JiraKeyGroup; -import org.junit.Test; +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.assertj.core.api.Assertions.assertThat; -@JiraKeyGroup( value = { - @JiraKey( value = "HHH-14530" ), - @JiraKey( value = "HHH-14529" ) -} ) -@RequiresDialectFeature(DialectChecks.SupportsIdentityColumns.class) -public class PreParsedOrmXmlTest extends BaseCoreFunctionalTestCase { - - @Override - protected void prepareBootstrapRegistryBuilder(BootstrapServiceRegistryBuilder builder) { - super.prepareBootstrapRegistryBuilder( builder ); - } - - @Override - protected void addMappings(Configuration configuration) { - super.addMappings( configuration ); - try (InputStream xmlStream = Thread.currentThread().getContextClassLoader() - .getResourceAsStream( "org/hibernate/orm/test/annotations/xml/ejb3/pre-parsed-orm.xml" )) { - Binding parsed = InputStreamXmlSource.fromStream( xmlStream, configuration.getXmlMappingBinderAccess().getMappingBinder() ); - configuration.addXmlMapping( parsed ); - } - catch (IOException e) { - throw new UncheckedIOException( e ); - } - } +@JiraKeyGroup(value = { + @JiraKey(value = "HHH-14530"), + @JiraKey(value = "HHH-14529") +}) +@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsIdentityColumns.class) +@DomainModel( + xmlMappings = "org/hibernate/orm/test/annotations/xml/ejb3/pre-parsed-orm.xml" +) +@SessionFactory +public class PreParsedOrmXmlTest { @Test - public void testPreParsedOrmXml() { + public void testPreParsedOrmXml(SessionFactoryScope scope) { // Just check that the entity can be persisted, which means the mapping file was taken into account NonAnnotatedEntity persistedEntity = new NonAnnotatedEntity( "someName" ); - inTransaction( s -> s.persist( persistedEntity ) ); - inTransaction( s -> { + + scope.inTransaction( s -> s.persist( persistedEntity ) ); + + scope.inTransaction( s -> { NonAnnotatedEntity retrievedEntity = s.find( NonAnnotatedEntity.class, persistedEntity.getId() ); assertThat( retrievedEntity ).extracting( NonAnnotatedEntity::getName ) .isEqualTo( persistedEntity.getName() ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/array/DateArrayTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/array/DateArrayTest.java index 418421b72305..74f33c6e0e29 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/array/DateArrayTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/array/DateArrayTest.java @@ -4,36 +4,38 @@ */ package org.hibernate.orm.test.array; -import java.util.Date; - -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; - import jakarta.persistence.Column; import jakarta.persistence.ElementCollection; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.OrderColumn; +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; -public class DateArrayTest extends BaseCoreFunctionalTestCase { +import java.util.Date; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { DateArrayEntity.class }; - } +@DomainModel( + annotatedClasses = { + DateArrayTest.DateArrayEntity.class + } +) +@SessionFactory +public class DateArrayTest { @Test - public void run() throws InterruptedException { - inTransaction( session -> { + public void run(SessionFactoryScope scope) { + scope.inTransaction( session -> { DateArrayEntity entity = new DateArrayEntity(); - entity.setDates( new Date[] { new Date() } ); + entity.setDates( new Date[] {new Date()} ); session.persist( entity ); } ); } @Entity(name = "DateArrayEntity") - public class DateArrayEntity { + public static class DateArrayEntity { @Id @GeneratedValue diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/BidirectionalTwoOneToManyMapsIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/BidirectionalTwoOneToManyMapsIdTest.java index 48d388e12684..9780fef96f79 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/BidirectionalTwoOneToManyMapsIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/BidirectionalTwoOneToManyMapsIdTest.java @@ -4,11 +4,6 @@ */ package org.hibernate.orm.test.associations; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Objects; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Embeddable; @@ -19,52 +14,54 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.MapsId; import jakarta.persistence.OneToMany; - import org.hibernate.annotations.NaturalId; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Objects; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; /** * @author Vlad Mihalcea */ -public class BidirectionalTwoOneToManyMapsIdTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Address.class, - PersonAddress.class - }; - } +@Jpa( + annotatedClasses = { + BidirectionalTwoOneToManyMapsIdTest.Person.class, + BidirectionalTwoOneToManyMapsIdTest.Address.class, + BidirectionalTwoOneToManyMapsIdTest.PersonAddress.class + } +) +public class BidirectionalTwoOneToManyMapsIdTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { - Person person1 = new Person("ABC-123"); - Person person2 = new Person("DEF-456"); + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Person person1 = new Person( "ABC-123" ); + Person person2 = new Person( "DEF-456" ); - Address address1 = new Address("12th Avenue", "12A", "4005A"); - Address address2 = new Address("18th Avenue", "18B", "4007B"); + Address address1 = new Address( "12th Avenue", "12A", "4005A" ); + Address address2 = new Address( "18th Avenue", "18B", "4007B" ); - entityManager.persist(person1); - entityManager.persist(person2); + entityManager.persist( person1 ); + entityManager.persist( person2 ); - entityManager.persist(address1); - entityManager.persist(address2); + entityManager.persist( address1 ); + entityManager.persist( address2 ); - person1.addAddress(address1); - person1.addAddress(address2); + person1.addAddress( address1 ); + person1.addAddress( address2 ); - person2.addAddress(address1); + person2.addAddress( address1 ); entityManager.flush(); - person1.removeAddress(address1); - }); + person1.removeAddress( address1 ); + } ); } @Entity(name = "Person") @@ -96,39 +93,39 @@ public List getAddresses() { } public void addAddress(Address address) { - PersonAddress personAddress = new PersonAddress(this, address); - addresses.add(personAddress); - address.getOwners().add(personAddress); + PersonAddress personAddress = new PersonAddress( this, address ); + addresses.add( personAddress ); + address.getOwners().add( personAddress ); } public void removeAddress(Address address) { - for (Iterator iterator = addresses.iterator(); iterator.hasNext();) { + for ( Iterator iterator = addresses.iterator(); iterator.hasNext(); ) { PersonAddress personAddress = iterator.next(); - if(personAddress.getPerson().equals(this) && - personAddress.getAddress().equals(address)) { + if ( personAddress.getPerson().equals( this ) && + personAddress.getAddress().equals( address ) ) { iterator.remove(); - personAddress.getAddress().getOwners().remove(personAddress); - personAddress.setPerson(null); - personAddress.setAddress(null); + personAddress.getAddress().getOwners().remove( personAddress ); + personAddress.setPerson( null ); + personAddress.setAddress( null ); } } } @Override public boolean equals(Object o) { - if (this == o) { + if ( this == o ) { return true; } - if (o == null || getClass() != o.getClass()) { + if ( o == null || getClass() != o.getClass() ) { return false; } Person person = (Person) o; - return Objects.equals(registrationNumber, person.registrationNumber); + return Objects.equals( registrationNumber, person.registrationNumber ); } @Override public int hashCode() { - return Objects.hash(registrationNumber); + return Objects.hash( registrationNumber ); } } @@ -157,20 +154,20 @@ public Long getAddressId() { @Override public boolean equals(Object o) { - if (this == o) { + if ( this == o ) { return true; } - if (o == null || getClass() != o.getClass()) { + if ( o == null || getClass() != o.getClass() ) { return false; } PersonAddressId that = (PersonAddressId) o; - return Objects.equals(personId, that.personId) && - Objects.equals(addressId, that.addressId); + return Objects.equals( personId, that.personId ) && + Objects.equals( addressId, that.addressId ); } @Override public int hashCode() { - return Objects.hash(personId, addressId); + return Objects.hash( personId, addressId ); } } @@ -194,7 +191,7 @@ public PersonAddress() { public PersonAddress(Person person, Address address) { this.person = person; this.address = address; - this.id = new PersonAddressId(person.getId(), address.getId()); + this.id = new PersonAddressId( person.getId(), address.getId() ); } public PersonAddressId getId() { @@ -219,20 +216,20 @@ public void setAddress(Address address) { @Override public boolean equals(Object o) { - if (this == o) { + if ( this == o ) { return true; } - if (o == null || getClass() != o.getClass()) { + if ( o == null || getClass() != o.getClass() ) { return false; } PersonAddress that = (PersonAddress) o; - return Objects.equals(person, that.person) && - Objects.equals(address, that.address); + return Objects.equals( person, that.person ) && + Objects.equals( address, that.address ); } @Override public int hashCode() { - return Objects.hash(person, address); + return Objects.hash( person, address ); } } @@ -284,21 +281,21 @@ public List getOwners() { @Override public boolean equals(Object o) { - if (this == o) { + if ( this == o ) { return true; } - if (o == null || getClass() != o.getClass()) { + if ( o == null || getClass() != o.getClass() ) { return false; } Address address = (Address) o; - return Objects.equals(street, address.street) && - Objects.equals(number, address.number) && - Objects.equals(postalCode, address.postalCode); + return Objects.equals( street, address.street ) && + Objects.equals( number, address.number ) && + Objects.equals( postalCode, address.postalCode ); } @Override public int hashCode() { - return Objects.hash(street, number, postalCode); + return Objects.hash( street, number, postalCode ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/CompositeIdAssociationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/CompositeIdAssociationTest.java index c772a57d6c2a..2a10e613f4c3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/CompositeIdAssociationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/CompositeIdAssociationTest.java @@ -4,65 +4,62 @@ */ package org.hibernate.orm.test.associations; -import java.io.Serializable; -import java.util.Objects; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.ManyToOne; - import org.hibernate.annotations.NaturalId; import org.hibernate.annotations.processing.Exclude; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import java.io.Serializable; +import java.util.Objects; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; /** * @author Vlad Mihalcea */ @Exclude -public class CompositeIdAssociationTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Address.class, - PersonAddress.class - }; - } +@Jpa( + annotatedClasses = { + CompositeIdAssociationTest.Person.class, + CompositeIdAssociationTest.Address.class, + CompositeIdAssociationTest.PersonAddress.class + } +) +public class CompositeIdAssociationTest { @Test - public void testLifecycle() { - PersonAddress _personAddress = doInJPA(this::entityManagerFactory, entityManager -> { - Person person1 = new Person("ABC-123"); - Person person2 = new Person("DEF-456"); + public void testLifecycle(EntityManagerFactoryScope scope) { + PersonAddress _personAddress = scope.fromTransaction( entityManager -> { + Person person1 = new Person( "ABC-123" ); + Person person2 = new Person( "DEF-456" ); - Address address1 = new Address("12th Avenue", "12A", "4005A"); - Address address2 = new Address("18th Avenue", "18B", "4007B"); + Address address1 = new Address( "12th Avenue", "12A", "4005A" ); + Address address2 = new Address( "18th Avenue", "18B", "4007B" ); - entityManager.persist(person1); - entityManager.persist(person2); + entityManager.persist( person1 ); + entityManager.persist( person2 ); - entityManager.persist(address1); - entityManager.persist(address2); + entityManager.persist( address1 ); + entityManager.persist( address2 ); - PersonAddress personAddress = new PersonAddress(person1, address1); - entityManager.persist(personAddress); + PersonAddress personAddress = new PersonAddress( person1, address1 ); + entityManager.persist( personAddress ); return personAddress; - }); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { - Address address = entityManager.createQuery("from Address", Address.class).getResultList().get(0); - Person person = entityManager.createQuery("from Person", Person.class).getResultList().get(0); + scope.inTransaction( entityManager -> { + Address address = entityManager.createQuery( "from Address", Address.class ).getResultList().get( 0 ); + Person person = entityManager.createQuery( "from Person", Person.class ).getResultList().get( 0 ); PersonAddress personAddress = entityManager.find( PersonAddress.class, - new PersonAddress(person, address) + new PersonAddress( person, address ) ); - }); + } ); } @Entity(name = "PersonAddress") @@ -102,20 +99,20 @@ public void setAddress(Address address) { @Override public boolean equals(Object o) { - if (this == o) { + if ( this == o ) { return true; } - if (o == null || getClass() != o.getClass()) { + if ( o == null || getClass() != o.getClass() ) { return false; } PersonAddress that = (PersonAddress) o; - return Objects.equals(person, that.person) && - Objects.equals(address, that.address); + return Objects.equals( person, that.person ) && + Objects.equals( address, that.address ); } @Override public int hashCode() { - return Objects.hash(person, address); + return Objects.hash( person, address ); } } @@ -142,19 +139,19 @@ public Long getId() { @Override public boolean equals(Object o) { - if (this == o) { + if ( this == o ) { return true; } - if (o == null || getClass() != o.getClass()) { + if ( o == null || getClass() != o.getClass() ) { return false; } Person person = (Person) o; - return Objects.equals(registrationNumber, person.registrationNumber); + return Objects.equals( registrationNumber, person.registrationNumber ); } @Override public int hashCode() { - return Objects.hash(registrationNumber); + return Objects.hash( registrationNumber ); } } @@ -199,21 +196,21 @@ public String getPostalCode() { @Override public boolean equals(Object o) { - if (this == o) { + if ( this == o ) { return true; } - if (o == null || getClass() != o.getClass()) { + if ( o == null || getClass() != o.getClass() ) { return false; } Address address = (Address) o; - return Objects.equals(street, address.street) && - Objects.equals(number, address.number) && - Objects.equals(postalCode, address.postalCode); + return Objects.equals( street, address.street ) && + Objects.equals( number, address.number ) && + Objects.equals( postalCode, address.postalCode ); } @Override public int hashCode() { - return Objects.hash(street, number, postalCode); + return Objects.hash( street, number, postalCode ); } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/DerivedIdentifierPrimaryKeyJoinColumnTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/DerivedIdentifierPrimaryKeyJoinColumnTest.java index ce12ff095247..becc79d0e2f9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/DerivedIdentifierPrimaryKeyJoinColumnTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/DerivedIdentifierPrimaryKeyJoinColumnTest.java @@ -9,45 +9,42 @@ import jakarta.persistence.Id; import jakarta.persistence.ManyToOne; import jakarta.persistence.PrimaryKeyJoinColumn; - import org.hibernate.annotations.NaturalId; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import org.junit.Assert; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; /** * @author Vlad Mihalcea */ -public class DerivedIdentifierPrimaryKeyJoinColumnTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - PersonDetails.class - }; - } +@Jpa( + annotatedClasses = { + DerivedIdentifierPrimaryKeyJoinColumnTest.Person.class, + DerivedIdentifierPrimaryKeyJoinColumnTest.PersonDetails.class + } +) +public class DerivedIdentifierPrimaryKeyJoinColumnTest { @Test - public void testLifecycle() { - Long personId = doInJPA(this::entityManagerFactory, entityManager -> { - Person person = new Person("ABC-123"); - entityManager.persist(person); + public void testLifecycle(EntityManagerFactoryScope scope) { + Long personId = scope.fromTransaction( entityManager -> { + Person person = new Person( "ABC-123" ); + entityManager.persist( person ); PersonDetails details = new PersonDetails(); - details.setPerson(person); + details.setPerson( person ); - entityManager.persist(details); + entityManager.persist( details ); return person.getId(); - }); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { - PersonDetails details = entityManager.find(PersonDetails.class, personId); - Assert.assertNotNull(details); - }); + scope.inTransaction( entityManager -> { + PersonDetails details = entityManager.find( PersonDetails.class, personId ); + assertThat( details ).isNotNull(); + } ); } @Entity(name = "Person") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/DerivedIdentifierTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/DerivedIdentifierTest.java index c8304bff98ab..36ba7e1f95bc 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/DerivedIdentifierTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/DerivedIdentifierTest.java @@ -9,46 +9,43 @@ import jakarta.persistence.Id; import jakarta.persistence.ManyToOne; import jakarta.persistence.MapsId; - import org.hibernate.annotations.NaturalId; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import org.junit.Assert; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; /** * @author Vlad Mihalcea */ -public class DerivedIdentifierTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - PersonDetails.class - }; - } +@Jpa( + annotatedClasses = { + DerivedIdentifierTest.Person.class, + DerivedIdentifierTest.PersonDetails.class + } +) +public class DerivedIdentifierTest { @Test - public void testLifecycle() { - Long personId = doInJPA(this::entityManagerFactory, entityManager -> { - Person person = new Person("ABC-123"); + public void testLifecycle(EntityManagerFactoryScope scope) { + Long personId = scope.fromTransaction( entityManager -> { + Person person = new Person( "ABC-123" ); PersonDetails details = new PersonDetails(); - details.setPerson(person); + details.setPerson( person ); - entityManager.persist(person); - entityManager.persist(details); + entityManager.persist( person ); + entityManager.persist( details ); return person.getId(); - }); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { - PersonDetails details = entityManager.find(PersonDetails.class, personId); - Assert.assertNotNull(details); - }); + scope.inTransaction( entityManager -> { + PersonDetails details = entityManager.find( PersonDetails.class, personId ); + assertThat( details ).isNotNull(); + } ); } @Entity(name = "Person") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/JoinColumnOrFormulaTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/JoinColumnOrFormulaTest.java index 9eebabee247a..7181cc1a22b6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/JoinColumnOrFormulaTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/JoinColumnOrFormulaTest.java @@ -4,85 +4,80 @@ */ package org.hibernate.orm.test.associations; -import java.io.Serializable; -import java.util.Objects; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; - import org.hibernate.annotations.JoinColumnOrFormula; import org.hibernate.annotations.JoinFormula; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import java.io.Serializable; +import java.util.Objects; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Vlad Mihalcea */ -public class JoinColumnOrFormulaTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Country.class, - User.class - }; - } +@Jpa( + annotatedClasses = { + JoinColumnOrFormulaTest.Country.class, + JoinColumnOrFormulaTest.User.class + } +) +public class JoinColumnOrFormulaTest { @Test - public void testLifecycle() { + public void testLifecycle(EntityManagerFactoryScope scope) { //tag::associations-JoinColumnOrFormula-persistence-example[] Country US = new Country(); - US.setId(1); - US.setDefault(true); - US.setPrimaryLanguage("English"); - US.setName("United States"); + US.setId( 1 ); + US.setDefault( true ); + US.setPrimaryLanguage( "English" ); + US.setName( "United States" ); Country Romania = new Country(); - Romania.setId(40); - Romania.setDefault(true); - Romania.setName("Romania"); - Romania.setPrimaryLanguage("Romanian"); + Romania.setId( 40 ); + Romania.setDefault( true ); + Romania.setName( "Romania" ); + Romania.setPrimaryLanguage( "Romanian" ); - doInJPA(this::entityManagerFactory, entityManager -> { - entityManager.persist(US); - entityManager.persist(Romania); - }); + scope.inTransaction( entityManager -> { + entityManager.persist( US ); + entityManager.persist( Romania ); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { User user1 = new User(); - user1.setId(1L); - user1.setFirstName("John"); - user1.setLastName("Doe"); - user1.setLanguage("English"); - entityManager.persist(user1); + user1.setId( 1L ); + user1.setFirstName( "John" ); + user1.setLastName( "Doe" ); + user1.setLanguage( "English" ); + entityManager.persist( user1 ); User user2 = new User(); - user2.setId(2L); - user2.setFirstName("Vlad"); - user2.setLastName("Mihalcea"); - user2.setLanguage("Romanian"); - entityManager.persist(user2); + user2.setId( 2L ); + user2.setFirstName( "Vlad" ); + user2.setLastName( "Mihalcea" ); + user2.setLanguage( "Romanian" ); + entityManager.persist( user2 ); - }); + } ); //end::associations-JoinColumnOrFormula-persistence-example[] //tag::associations-JoinColumnOrFormula-fetching-example[] - doInJPA(this::entityManagerFactory, entityManager -> { - log.info("Fetch User entities"); + scope.inTransaction( entityManager -> { + User john = entityManager.find( User.class, 1L ); + assertThat( john.getCountry() ).isEqualTo( US ); - User john = entityManager.find(User.class, 1L); - assertEquals(US, john.getCountry()); - - User vlad = entityManager.find(User.class, 2L); - assertEquals(Romania, vlad.getCountry()); - }); + User vlad = entityManager.find( User.class, 2L ); + assertThat( vlad.getCountry() ).isEqualTo( Romania ); + } ); //end::associations-JoinColumnOrFormula-fetching-example[] } @@ -102,24 +97,24 @@ public static class User { @ManyToOne @JoinColumnOrFormula(column = - @JoinColumn( + @JoinColumn( name = "language", referencedColumnName = "primaryLanguage", insertable = false, updatable = false - ) + ) ) @JoinColumnOrFormula(formula = - @JoinFormula( + @JoinFormula( value = "true", referencedColumnName = "is_default" - ) + ) ) private Country country; //Getters and setters omitted for brevity - //end::associations-JoinColumnOrFormula-example[] + //end::associations-JoinColumnOrFormula-example[] public Long getId() { return id; } @@ -160,7 +155,7 @@ public void setCountry(Country country) { this.country = country; } - //tag::associations-JoinColumnOrFormula-example[] + //tag::associations-JoinColumnOrFormula-example[] } //end::associations-JoinColumnOrFormula-example[] @@ -182,7 +177,7 @@ public static class Country implements Serializable { //Getters and setters, equals and hashCode methods omitted for brevity - //end::associations-JoinColumnOrFormula-example[] + //end::associations-JoinColumnOrFormula-example[] public int getId() { return id; @@ -218,21 +213,21 @@ public void setDefault(boolean _default) { @Override public boolean equals(Object o) { - if (this == o) { + if ( this == o ) { return true; } - if (!(o instanceof Country)) { + if ( !(o instanceof Country) ) { return false; } Country country = (Country) o; - return Objects.equals(getId(), country.getId()); + return Objects.equals( getId(), country.getId() ); } @Override public int hashCode() { - return Objects.hash(getId()); + return Objects.hash( getId() ); } - //tag::associations-JoinColumnOrFormula-example[] + //tag::associations-JoinColumnOrFormula-example[] } //end::associations-JoinColumnOrFormula-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/JoinFormulaTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/JoinFormulaTest.java index 6e041ba98a19..6d226e29e011 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/JoinFormulaTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/JoinFormulaTest.java @@ -4,79 +4,74 @@ */ package org.hibernate.orm.test.associations; -import java.util.Objects; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; - import org.hibernate.annotations.JoinFormula; import org.hibernate.dialect.PostgreSQLDialect; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.RequiresDialect; -import org.junit.Test; +import java.util.Objects; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Vlad Mihalcea */ @RequiresDialect(PostgreSQLDialect.class) -public class JoinFormulaTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Country.class, - User.class - }; - } +@Jpa( + annotatedClasses = { + JoinFormulaTest.Country.class, + JoinFormulaTest.User.class + } +) +public class JoinFormulaTest { @Test - public void testLifecycle() { + public void testLifecycle(EntityManagerFactoryScope scope) { //tag::associations-JoinFormula-persistence-example[] Country US = new Country(); - US.setId(1); - US.setName("United States"); + US.setId( 1 ); + US.setName( "United States" ); Country Romania = new Country(); - Romania.setId(40); - Romania.setName("Romania"); + Romania.setId( 40 ); + Romania.setName( "Romania" ); - doInJPA(this::entityManagerFactory, entityManager -> { - entityManager.persist(US); - entityManager.persist(Romania); - }); + scope.inTransaction( entityManager -> { + entityManager.persist( US ); + entityManager.persist( Romania ); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { User user1 = new User(); - user1.setId(1L); - user1.setFirstName("John"); - user1.setLastName("Doe"); - user1.setPhoneNumber("+1-234-5678"); - entityManager.persist(user1); + user1.setId( 1L ); + user1.setFirstName( "John" ); + user1.setLastName( "Doe" ); + user1.setPhoneNumber( "+1-234-5678" ); + entityManager.persist( user1 ); User user2 = new User(); - user2.setId(2L); - user2.setFirstName("Vlad"); - user2.setLastName("Mihalcea"); - user2.setPhoneNumber("+40-123-4567"); - entityManager.persist(user2); - }); + user2.setId( 2L ); + user2.setFirstName( "Vlad" ); + user2.setLastName( "Mihalcea" ); + user2.setPhoneNumber( "+40-123-4567" ); + entityManager.persist( user2 ); + } ); //end::associations-JoinFormula-persistence-example[] //tag::associations-JoinFormula-fetching-example[] - doInJPA(this::entityManagerFactory, entityManager -> { - log.info("Fetch User entities"); + scope.inTransaction( entityManager -> { + User john = entityManager.find( User.class, 1L ); + assertThat( john.getCountry() ).isEqualTo( US ); - User john = entityManager.find(User.class, 1L); - assertEquals(US, john.getCountry()); - - User vlad = entityManager.find(User.class, 2L); - assertEquals(Romania, vlad.getCountry()); - }); + User vlad = entityManager.find( User.class, 2L ); + assertThat( vlad.getCountry() ).isEqualTo( Romania ); + } ); //end::associations-JoinFormula-fetching-example[] } @@ -100,7 +95,7 @@ public static class User { //Getters and setters omitted for brevity - //end::associations-JoinFormula-example[] + //end::associations-JoinFormula-example[] public Long getId() { return id; } @@ -137,7 +132,7 @@ public Country getCountry() { return country; } - //tag::associations-JoinFormula-example[] + //tag::associations-JoinFormula-example[] } //end::associations-JoinFormula-example[] @@ -154,7 +149,7 @@ public static class Country { //Getters and setters, equals and hashCode methods omitted for brevity - //end::associations-JoinFormula-example[] + //end::associations-JoinFormula-example[] public int getId() { return id; @@ -174,21 +169,21 @@ public void setName(String name) { @Override public boolean equals(Object o) { - if (this == o) { + if ( this == o ) { return true; } - if (!(o instanceof Country)) { + if ( !(o instanceof Country) ) { return false; } Country country = (Country) o; - return Objects.equals(getId(), country.getId()); + return Objects.equals( getId(), country.getId() ); } @Override public int hashCode() { - return Objects.hash(getId()); + return Objects.hash( getId() ); } - //tag::associations-JoinFormula-example[] + //tag::associations-JoinFormula-example[] } //end::associations-JoinFormula-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/ManyToManyBidirectionalTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/ManyToManyBidirectionalTest.java index a1821c077e1f..4d3a63c6e7ab 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/ManyToManyBidirectionalTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/ManyToManyBidirectionalTest.java @@ -6,7 +6,6 @@ import java.util.ArrayList; import java.util.List; -import java.util.Map; import java.util.Objects; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; @@ -17,35 +16,38 @@ import org.hibernate.annotations.NaturalId; import org.hibernate.metamodel.CollectionClassification; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.SettingProvider; +import org.junit.jupiter.api.Test; import static org.hibernate.cfg.AvailableSettings.DEFAULT_LIST_SEMANTICS; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; /** * @author Vlad Mihalcea */ -public class ManyToManyBidirectionalTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Address.class, - }; - } - - @Override - protected void addConfigOptions(Map options) { - super.addConfigOptions( options ); - options.put( DEFAULT_LIST_SEMANTICS, CollectionClassification.BAG.name() ); +@Jpa( + annotatedClasses = { + ManyToManyBidirectionalTest.Person.class, + ManyToManyBidirectionalTest.Address.class, + }, + settingProviders = @SettingProvider( + settingName = DEFAULT_LIST_SEMANTICS, + provider = ManyToManyBidirectionalTest.CollectionClassificationProvider.class + ) +) +public class ManyToManyBidirectionalTest { + + public static class CollectionClassificationProvider implements SettingProvider.Provider { + @Override + public CollectionClassification getSetting() { + return CollectionClassification.BAG; + } } @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::associations-many-to-many-bidirectional-lifecycle-example[] Person person1 = new Person("ABC-123"); Person person2 = new Person("DEF-456"); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/ManyToManyBidirectionalWithLinkEntityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/ManyToManyBidirectionalWithLinkEntityTest.java index 0e7c25214c1c..3d5046ad0b49 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/ManyToManyBidirectionalWithLinkEntityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/ManyToManyBidirectionalWithLinkEntityTest.java @@ -4,10 +4,6 @@ */ package org.hibernate.orm.test.associations; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -15,55 +11,54 @@ import jakarta.persistence.Id; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; - import org.hibernate.annotations.NaturalId; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; /** * @author Vlad Mihalcea */ -public class ManyToManyBidirectionalWithLinkEntityTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Address.class, - PersonAddress.class - }; - } +@Jpa( + annotatedClasses = { + ManyToManyBidirectionalWithLinkEntityTest.Person.class, + ManyToManyBidirectionalWithLinkEntityTest.Address.class, + ManyToManyBidirectionalWithLinkEntityTest.PersonAddress.class + } +) +public class ManyToManyBidirectionalWithLinkEntityTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::associations-many-to-many-bidirectional-with-link-entity-lifecycle-example[] - Person person1 = new Person("ABC-123"); - Person person2 = new Person("DEF-456"); + Person person1 = new Person( "ABC-123" ); + Person person2 = new Person( "DEF-456" ); - Address address1 = new Address("12th Avenue", "12A", "4005A"); - Address address2 = new Address("18th Avenue", "18B", "4007B"); + Address address1 = new Address( "12th Avenue", "12A", "4005A" ); + Address address2 = new Address( "18th Avenue", "18B", "4007B" ); - entityManager.persist(person1); - entityManager.persist(person2); + entityManager.persist( person1 ); + entityManager.persist( person2 ); - entityManager.persist(address1); - entityManager.persist(address2); + entityManager.persist( address1 ); + entityManager.persist( address2 ); - person1.addAddress(address1); - person1.addAddress(address2); + person1.addAddress( address1 ); + person1.addAddress( address2 ); - person2.addAddress(address1); + person2.addAddress( address1 ); entityManager.flush(); - log.info("Removing address"); - person1.removeAddress(address1); + person1.removeAddress( address1 ); //end::associations-many-to-many-bidirectional-with-link-entity-lifecycle-example[] - }); + } ); } //tag::associations-many-to-many-bidirectional-with-link-entity-example[] @@ -78,15 +73,15 @@ public static class Person implements Serializable { private String registrationNumber; @OneToMany( - mappedBy = "person", - cascade = CascadeType.ALL, - orphanRemoval = true + mappedBy = "person", + cascade = CascadeType.ALL, + orphanRemoval = true ) private List addresses = new ArrayList<>(); //Getters and setters are omitted for brevity - //end::associations-many-to-many-bidirectional-with-link-entity-example[] + //end::associations-many-to-many-bidirectional-with-link-entity-example[] public Person() { } @@ -103,36 +98,36 @@ public List getAddresses() { return addresses; } - //tag::associations-many-to-many-bidirectional-with-link-entity-example[] + //tag::associations-many-to-many-bidirectional-with-link-entity-example[] public void addAddress(Address address) { - PersonAddress personAddress = new PersonAddress(this, address); - addresses.add(personAddress); - address.getOwners().add(personAddress); + PersonAddress personAddress = new PersonAddress( this, address ); + addresses.add( personAddress ); + address.getOwners().add( personAddress ); } public void removeAddress(Address address) { - PersonAddress personAddress = new PersonAddress(this, address); - address.getOwners().remove(personAddress); - addresses.remove(personAddress); - personAddress.setPerson(null); - personAddress.setAddress(null); + PersonAddress personAddress = new PersonAddress( this, address ); + address.getOwners().remove( personAddress ); + addresses.remove( personAddress ); + personAddress.setPerson( null ); + personAddress.setAddress( null ); } @Override public boolean equals(Object o) { - if (this == o) { + if ( this == o ) { return true; } - if (o == null || getClass() != o.getClass()) { + if ( o == null || getClass() != o.getClass() ) { return false; } Person person = (Person) o; - return Objects.equals(registrationNumber, person.registrationNumber); + return Objects.equals( registrationNumber, person.registrationNumber ); } @Override public int hashCode() { - return Objects.hash(registrationNumber); + return Objects.hash( registrationNumber ); } } @@ -149,7 +144,7 @@ public static class PersonAddress implements Serializable { //Getters and setters are omitted for brevity - //end::associations-many-to-many-bidirectional-with-link-entity-example[] + //end::associations-many-to-many-bidirectional-with-link-entity-example[] public PersonAddress() { } @@ -175,23 +170,23 @@ public void setAddress(Address address) { this.address = address; } - //tag::associations-many-to-many-bidirectional-with-link-entity-example[] + //tag::associations-many-to-many-bidirectional-with-link-entity-example[] @Override public boolean equals(Object o) { - if (this == o) { + if ( this == o ) { return true; } - if (o == null || getClass() != o.getClass()) { + if ( o == null || getClass() != o.getClass() ) { return false; } PersonAddress that = (PersonAddress) o; - return Objects.equals(person, that.person) && - Objects.equals(address, that.address); + return Objects.equals( person, that.person ) && + Objects.equals( address, that.address ); } @Override public int hashCode() { - return Objects.hash(person, address); + return Objects.hash( person, address ); } } @@ -210,15 +205,15 @@ public static class Address implements Serializable { private String postalCode; @OneToMany( - mappedBy = "address", - cascade = CascadeType.ALL, - orphanRemoval = true + mappedBy = "address", + cascade = CascadeType.ALL, + orphanRemoval = true ) private List owners = new ArrayList<>(); //Getters and setters are omitted for brevity - //end::associations-many-to-many-bidirectional-with-link-entity-example[] + //end::associations-many-to-many-bidirectional-with-link-entity-example[] public Address() { } @@ -249,24 +244,24 @@ public List getOwners() { return owners; } - //tag::associations-many-to-many-bidirectional-with-link-entity-example[] + //tag::associations-many-to-many-bidirectional-with-link-entity-example[] @Override public boolean equals(Object o) { - if (this == o) { + if ( this == o ) { return true; } - if (o == null || getClass() != o.getClass()) { + if ( o == null || getClass() != o.getClass() ) { return false; } Address address = (Address) o; - return Objects.equals(street, address.street) && - Objects.equals(number, address.number) && - Objects.equals(postalCode, address.postalCode); + return Objects.equals( street, address.street ) && + Objects.equals( number, address.number ) && + Objects.equals( postalCode, address.postalCode ); } @Override public int hashCode() { - return Objects.hash(street, number, postalCode); + return Objects.hash( street, number, postalCode ); } } //end::associations-many-to-many-bidirectional-with-link-entity-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/ManyToManyUnidirectionalTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/ManyToManyUnidirectionalTest.java index 36d3e127ca2a..2c26ae44f03b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/ManyToManyUnidirectionalTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/ManyToManyUnidirectionalTest.java @@ -4,85 +4,80 @@ */ package org.hibernate.orm.test.associations; -import java.util.ArrayList; -import java.util.List; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.ManyToMany; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import java.util.ArrayList; +import java.util.List; /** * @author Vlad Mihalcea */ -public class ManyToManyUnidirectionalTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Address.class, - }; - } +@Jpa( + annotatedClasses = { + ManyToManyUnidirectionalTest.Person.class, + ManyToManyUnidirectionalTest.Address.class, + } +) +public class ManyToManyUnidirectionalTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::associations-many-to-many-unidirectional-lifecycle-example[] Person person1 = new Person(); Person person2 = new Person(); - Address address1 = new Address("12th Avenue", "12A"); - Address address2 = new Address("18th Avenue", "18B"); + Address address1 = new Address( "12th Avenue", "12A" ); + Address address2 = new Address( "18th Avenue", "18B" ); - person1.getAddresses().add(address1); - person1.getAddresses().add(address2); + person1.getAddresses().add( address1 ); + person1.getAddresses().add( address2 ); - person2.getAddresses().add(address1); + person2.getAddresses().add( address1 ); - entityManager.persist(person1); - entityManager.persist(person2); + entityManager.persist( person1 ); + entityManager.persist( person2 ); entityManager.flush(); - person1.getAddresses().remove(address1); + person1.getAddresses().remove( address1 ); //end::associations-many-to-many-unidirectional-lifecycle-example[] - }); + } ); } @Test - public void testRemove() { - final Long personId = doInJPA(this::entityManagerFactory, entityManager -> { + public void testRemove(EntityManagerFactoryScope scope) { + final Long personId = scope.fromTransaction( entityManager -> { Person person1 = new Person(); Person person2 = new Person(); - Address address1 = new Address("12th Avenue", "12A"); - Address address2 = new Address("18th Avenue", "18B"); + Address address1 = new Address( "12th Avenue", "12A" ); + Address address2 = new Address( "18th Avenue", "18B" ); - person1.getAddresses().add(address1); - person1.getAddresses().add(address2); + person1.getAddresses().add( address1 ); + person1.getAddresses().add( address2 ); - person2.getAddresses().add(address1); + person2.getAddresses().add( address1 ); - entityManager.persist(person1); - entityManager.persist(person2); + entityManager.persist( person1 ); + entityManager.persist( person2 ); return person1.id; - }); - doInJPA(this::entityManagerFactory, entityManager -> { - log.info("Remove"); + } ); + scope.inTransaction( entityManager -> { //tag::associations-many-to-many-unidirectional-remove-example[] - Person person1 = entityManager.find(Person.class, personId); - entityManager.remove(person1); + Person person1 = entityManager.find( Person.class, personId ); + entityManager.remove( person1 ); //end::associations-many-to-many-unidirectional-remove-example[] - }); + } ); } //tag::associations-many-to-many-unidirectional-example[] @@ -98,7 +93,7 @@ public static class Person { //Getters and setters are omitted for brevity - //end::associations-many-to-many-unidirectional-example[] + //end::associations-many-to-many-unidirectional-example[] public Person() { } @@ -106,7 +101,7 @@ public Person() { public List
getAddresses() { return addresses; } - //tag::associations-many-to-many-unidirectional-example[] + //tag::associations-many-to-many-unidirectional-example[] } @Entity(name = "Address") @@ -123,7 +118,7 @@ public static class Address { //Getters and setters are omitted for brevity - //end::associations-many-to-many-unidirectional-example[] + //end::associations-many-to-many-unidirectional-example[] public Address() { } @@ -144,7 +139,7 @@ public String getStreet() { public String getNumber() { return number; } - //tag::associations-many-to-many-unidirectional-example[] + //tag::associations-many-to-many-unidirectional-example[] } //end::associations-many-to-many-unidirectional-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/ManyToOneTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/ManyToOneTest.java index 4c0779253966..148404b46b64 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/ManyToOneTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/ManyToOneTest.java @@ -11,41 +11,37 @@ import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; /** * @author Vlad Mihalcea */ -public class ManyToOneTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class, - }; - } +@Jpa( + annotatedClasses = { + ManyToOneTest.Person.class, + ManyToOneTest.Phone.class, + } +) +public class ManyToOneTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::associations-many-to-one-lifecycle-example[] Person person = new Person(); - entityManager.persist(person); + entityManager.persist( person ); - Phone phone = new Phone("123-456-7890"); - phone.setPerson(person); - entityManager.persist(phone); + Phone phone = new Phone( "123-456-7890" ); + phone.setPerson( person ); + entityManager.persist( phone ); entityManager.flush(); - phone.setPerson(null); + phone.setPerson( null ); //end::associations-many-to-one-lifecycle-example[] - }); + } ); } //tag::associations-many-to-one-example[] @@ -78,7 +74,7 @@ public static class Phone { //Getters and setters are omitted for brevity - //end::associations-many-to-one-example[] + //end::associations-many-to-one-example[] public Phone() { } @@ -102,7 +98,7 @@ public Person getPerson() { public void setPerson(Person person) { this.person = person; } - //tag::associations-many-to-one-example[] + //tag::associations-many-to-one-example[] } //end::associations-many-to-one-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToManyBidirectionalTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToManyBidirectionalTest.java index f3f8810ff6f5..fb09bc7655ba 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToManyBidirectionalTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToManyBidirectionalTest.java @@ -4,9 +4,6 @@ */ package org.hibernate.orm.test.associations; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -14,43 +11,42 @@ import jakarta.persistence.Id; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; - import org.hibernate.annotations.NaturalId; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; /** * @author Vlad Mihalcea */ -public class OneToManyBidirectionalTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class, - }; - } +@Jpa( + annotatedClasses = { + OneToManyBidirectionalTest.Person.class, + OneToManyBidirectionalTest.Phone.class, + } +) +public class OneToManyBidirectionalTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::associations-one-to-many-bidirectional-lifecycle-example[] Person person = new Person(); - Phone phone1 = new Phone("123-456-7890"); - Phone phone2 = new Phone("321-654-0987"); + Phone phone1 = new Phone( "123-456-7890" ); + Phone phone2 = new Phone( "321-654-0987" ); - person.addPhone(phone1); - person.addPhone(phone2); - entityManager.persist(person); + person.addPhone( phone1 ); + person.addPhone( phone2 ); + entityManager.persist( person ); entityManager.flush(); - person.removePhone(phone1); + person.removePhone( phone1 ); //end::associations-one-to-many-bidirectional-lifecycle-example[] - }); + } ); } //tag::associations-one-to-many-bidirectional-example[] @@ -66,7 +62,7 @@ public static class Person { //Getters and setters are omitted for brevity - //end::associations-one-to-many-bidirectional-example[] + //end::associations-one-to-many-bidirectional-example[] public Person() { } @@ -79,15 +75,15 @@ public List getPhones() { return phones; } - //tag::associations-one-to-many-bidirectional-example[] + //tag::associations-one-to-many-bidirectional-example[] public void addPhone(Phone phone) { - phones.add(phone); - phone.setPerson(this); + phones.add( phone ); + phone.setPerson( this ); } public void removePhone(Phone phone) { - phones.remove(phone); - phone.setPerson(null); + phones.remove( phone ); + phone.setPerson( null ); } } @@ -107,7 +103,7 @@ public static class Phone { //Getters and setters are omitted for brevity - //end::associations-one-to-many-bidirectional-example[] + //end::associations-one-to-many-bidirectional-example[] public Phone() { } @@ -132,22 +128,22 @@ public void setPerson(Person person) { this.person = person; } - //tag::associations-one-to-many-bidirectional-example[] + //tag::associations-one-to-many-bidirectional-example[] @Override public boolean equals(Object o) { - if (this == o) { + if ( this == o ) { return true; } - if (o == null || getClass() != o.getClass()) { + if ( o == null || getClass() != o.getClass() ) { return false; } Phone phone = (Phone) o; - return Objects.equals(number, phone.number); + return Objects.equals( number, phone.number ); } @Override public int hashCode() { - return Objects.hash(number); + return Objects.hash( number ); } } //end::associations-one-to-many-bidirectional-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToManyUnidirectionalTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToManyUnidirectionalTest.java index 5a2cf06120a6..08c03f6400d3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToManyUnidirectionalTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToManyUnidirectionalTest.java @@ -4,50 +4,46 @@ */ package org.hibernate.orm.test.associations; -import java.util.ArrayList; -import java.util.List; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.OneToMany; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import java.util.ArrayList; +import java.util.List; /** * @author Vlad Mihalcea */ -public class OneToManyUnidirectionalTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class, - }; - } +@Jpa( + annotatedClasses = { + OneToManyUnidirectionalTest.Person.class, + OneToManyUnidirectionalTest.Phone.class, + } +) +public class OneToManyUnidirectionalTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::associations-one-to-many-unidirectional-lifecycle-example[] Person person = new Person(); - Phone phone1 = new Phone("123-456-7890"); - Phone phone2 = new Phone("321-654-0987"); + Phone phone1 = new Phone( "123-456-7890" ); + Phone phone2 = new Phone( "321-654-0987" ); - person.getPhones().add(phone1); - person.getPhones().add(phone2); - entityManager.persist(person); + person.getPhones().add( phone1 ); + person.getPhones().add( phone2 ); + entityManager.persist( person ); entityManager.flush(); - person.getPhones().remove(phone1); + person.getPhones().remove( phone1 ); //end::associations-one-to-many-unidirectional-lifecycle-example[] - }); + } ); } //tag::associations-one-to-many-unidirectional-example[] @@ -63,7 +59,7 @@ public static class Person { //Getters and setters are omitted for brevity - //end::associations-one-to-many-unidirectional-example[] + //end::associations-one-to-many-unidirectional-example[] public Person() { } @@ -72,7 +68,7 @@ public List getPhones() { return phones; } - //tag::associations-one-to-many-unidirectional-example[] + //tag::associations-one-to-many-unidirectional-example[] } @Entity(name = "Phone") @@ -87,7 +83,7 @@ public static class Phone { //Getters and setters are omitted for brevity - //end::associations-one-to-many-unidirectional-example[] + //end::associations-one-to-many-unidirectional-example[] public Phone() { } @@ -103,7 +99,7 @@ public Long getId() { public String getNumber() { return number; } - //tag::associations-one-to-many-unidirectional-example[] + //tag::associations-one-to-many-unidirectional-example[] } //end::associations-one-to-many-unidirectional-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToOneBidirectionalLazyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToOneBidirectionalLazyTest.java index 695512cf6de8..8a507084217c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToOneBidirectionalLazyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToOneBidirectionalLazyTest.java @@ -12,27 +12,26 @@ import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.OneToOne; - -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class OneToOneBidirectionalLazyTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Phone.class, - PhoneDetails.class, - }; - } +@Jpa( + annotatedClasses = { + OneToOneBidirectionalLazyTest.Phone.class, + OneToOneBidirectionalLazyTest.PhoneDetails.class, + } +) +public class OneToOneBidirectionalLazyTest { @Test - public void testLifecycle() { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + } ); } //tag::associations-one-to-one-bidirectional-lazy-example[] @@ -47,16 +46,16 @@ public static class Phone { private String number; @OneToOne( - mappedBy = "phone", - cascade = CascadeType.ALL, - orphanRemoval = true, - fetch = FetchType.LAZY + mappedBy = "phone", + cascade = CascadeType.ALL, + orphanRemoval = true, + fetch = FetchType.LAZY ) private PhoneDetails details; //Getters and setters are omitted for brevity - //end::associations-one-to-one-bidirectional-lazy-example[] + //end::associations-one-to-one-bidirectional-lazy-example[] public Phone() { } @@ -77,15 +76,15 @@ public PhoneDetails getDetails() { return details; } - //tag::associations-one-to-one-bidirectional-lazy-example[] + //tag::associations-one-to-one-bidirectional-lazy-example[] public void addDetails(PhoneDetails details) { - details.setPhone(this); + details.setPhone( this ); this.details = details; } public void removeDetails() { - if (details != null) { - details.setPhone(null); + if ( details != null ) { + details.setPhone( null ); this.details = null; } } @@ -108,7 +107,7 @@ public static class PhoneDetails { //Getters and setters are omitted for brevity - //end::associations-one-to-one-bidirectional-lazy-example[] + //end::associations-one-to-one-bidirectional-lazy-example[] public PhoneDetails() { } @@ -138,7 +137,7 @@ public Phone getPhone() { public void setPhone(Phone phone) { this.phone = phone; } - //tag::associations-one-to-one-bidirectional-lazy-example[] + //tag::associations-one-to-one-bidirectional-lazy-example[] } //end::associations-one-to-one-bidirectional-lazy-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToOneBidirectionalTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToOneBidirectionalTest.java index 726b6d0ae692..a54ba8abd682 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToOneBidirectionalTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToOneBidirectionalTest.java @@ -12,70 +12,66 @@ import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.OneToOne; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Assert; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Vlad Mihalcea */ -public class OneToOneBidirectionalTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Phone.class, - PhoneDetails.class, - }; - } +@Jpa( + annotatedClasses = { + OneToOneBidirectionalTest.Phone.class, + OneToOneBidirectionalTest.PhoneDetails.class, + } +) +public class OneToOneBidirectionalTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { - Phone phone = new Phone("123-456-7890"); - PhoneDetails details = new PhoneDetails("T-Mobile", "GSM"); - - phone.addDetails(details); - entityManager.persist(phone); - }); + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Phone phone = new Phone( "123-456-7890" ); + PhoneDetails details = new PhoneDetails( "T-Mobile", "GSM" ); + + phone.addDetails( details ); + entityManager.persist( phone ); + } ); } @Test - public void testConstraint() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testConstraint(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::associations-one-to-one-bidirectional-lifecycle-example[] - Phone phone = new Phone("123-456-7890"); - PhoneDetails details = new PhoneDetails("T-Mobile", "GSM"); + Phone phone = new Phone( "123-456-7890" ); + PhoneDetails details = new PhoneDetails( "T-Mobile", "GSM" ); - phone.addDetails(details); - entityManager.persist(phone); + phone.addDetails( details ); + entityManager.persist( phone ); //end::associations-one-to-one-bidirectional-lifecycle-example[] - }); + } ); try { - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { - Phone phone = entityManager.find(Phone.class, 1L); + Phone phone = entityManager.find( Phone.class, 1L ); //tag::associations-one-to-one-bidirectional-constraint-example[] - PhoneDetails otherDetails = new PhoneDetails("T-Mobile", "CDMA"); - otherDetails.setPhone(phone); - entityManager.persist(otherDetails); + PhoneDetails otherDetails = new PhoneDetails( "T-Mobile", "CDMA" ); + otherDetails.setPhone( phone ); + entityManager.persist( otherDetails ); entityManager.flush(); entityManager.clear(); //throws jakarta.persistence.PersistenceException: org.hibernate.HibernateException: More than one row with the given identifier was found: 1 - phone = entityManager.find(Phone.class, phone.getId()); + phone = entityManager.find( Phone.class, phone.getId() ); //end::associations-one-to-one-bidirectional-constraint-example[] phone.getDetails().getProvider(); - }); - Assert.fail("Expected: HHH000327: Error performing load command : org.hibernate.HibernateException: More than one row with the given identifier was found: 1"); + } ); + fail( "Expected: HHH000327: Error performing load command : org.hibernate.HibernateException: More than one row with the given identifier was found: 1" ); } catch (Exception expected) { - log.error("Expected", expected); + //expected } } @@ -91,16 +87,16 @@ public static class Phone { private String number; @OneToOne( - mappedBy = "phone", - cascade = CascadeType.ALL, - orphanRemoval = true, - fetch = FetchType.LAZY + mappedBy = "phone", + cascade = CascadeType.ALL, + orphanRemoval = true, + fetch = FetchType.LAZY ) private PhoneDetails details; //Getters and setters are omitted for brevity - //end::associations-one-to-one-bidirectional-example[] + //end::associations-one-to-one-bidirectional-example[] public Phone() { } @@ -121,15 +117,15 @@ public PhoneDetails getDetails() { return details; } - //tag::associations-one-to-one-bidirectional-example[] + //tag::associations-one-to-one-bidirectional-example[] public void addDetails(PhoneDetails details) { - details.setPhone(this); + details.setPhone( this ); this.details = details; } public void removeDetails() { - if (details != null) { - details.setPhone(null); + if ( details != null ) { + details.setPhone( null ); this.details = null; } } @@ -152,7 +148,7 @@ public static class PhoneDetails { //Getters and setters are omitted for brevity - //end::associations-one-to-one-bidirectional-example[] + //end::associations-one-to-one-bidirectional-example[] public PhoneDetails() { } @@ -181,7 +177,7 @@ public Phone getPhone() { public void setPhone(Phone phone) { this.phone = phone; } - //tag::associations-one-to-one-bidirectional-example[] + //tag::associations-one-to-one-bidirectional-example[] } //end::associations-one-to-one-bidirectional-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToOneMapsIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToOneMapsIdTest.java index 451003a9db75..f7b903cba42c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToOneMapsIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToOneMapsIdTest.java @@ -8,54 +8,50 @@ import jakarta.persistence.Id; import jakarta.persistence.MapsId; import jakarta.persistence.OneToOne; - import org.hibernate.annotations.NaturalId; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Vlad Mihalcea */ -public class OneToOneMapsIdTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - PersonDetails.class - }; - } +@Jpa( + annotatedClasses = { + OneToOneMapsIdTest.Person.class, + OneToOneMapsIdTest.PersonDetails.class + } +) +public class OneToOneMapsIdTest { @Test - public void testLifecycle() { + public void testLifecycle(EntityManagerFactoryScope scope) { //tag::identifiers-derived-mapsid-persist-example[] - doInJPA(this::entityManagerFactory, entityManager -> { - Person person = new Person("ABC-123"); - person.setId(1L); - entityManager.persist(person); + scope.inTransaction( entityManager -> { + Person person = new Person( "ABC-123" ); + person.setId( 1L ); + entityManager.persist( person ); PersonDetails personDetails = new PersonDetails(); - personDetails.setNickName("John Doe"); - personDetails.setPerson(person); + personDetails.setNickName( "John Doe" ); + personDetails.setPerson( person ); - entityManager.persist(personDetails); - }); + entityManager.persist( personDetails ); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { - PersonDetails personDetails = entityManager.find(PersonDetails.class, 1L); + scope.inTransaction( entityManager -> { + PersonDetails personDetails = entityManager.find( PersonDetails.class, 1L ); - assertEquals("John Doe", personDetails.getNickName()); - }); + assertThat( personDetails.getNickName() ).isEqualTo( "John Doe" ); + } ); //end::identifiers-derived-mapsid-persist-example[] } //tag::identifiers-derived-mapsid[] @Entity(name = "Person") - public static class Person { + public static class Person { @Id private Long id; @@ -63,7 +59,8 @@ public static class Person { @NaturalId private String registrationNumber; - public Person() {} + public Person() { + } public Person(String registrationNumber) { this.registrationNumber = registrationNumber; @@ -83,11 +80,11 @@ public void setId(Long id) { public String getRegistrationNumber() { return registrationNumber; } - //tag::identifiers-derived-mapsid[] + //tag::identifiers-derived-mapsid[] } @Entity(name = "PersonDetails") - public static class PersonDetails { + public static class PersonDetails { @Id private Long id; @@ -116,7 +113,7 @@ public Person getPerson() { public void setPerson(Person person) { this.person = person; } - //tag::identifiers-derived-mapsid[] + //tag::identifiers-derived-mapsid[] } //end::identifiers-derived-mapsid[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToOnePrimaryKeyJoinColumnTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToOnePrimaryKeyJoinColumnTest.java index 18ba13951fc3..b460906e61b2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToOnePrimaryKeyJoinColumnTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToOnePrimaryKeyJoinColumnTest.java @@ -8,54 +8,50 @@ import jakarta.persistence.Id; import jakarta.persistence.OneToOne; import jakarta.persistence.PrimaryKeyJoinColumn; - import org.hibernate.annotations.NaturalId; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Vlad Mihalcea */ -public class OneToOnePrimaryKeyJoinColumnTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - PersonDetails.class - }; - } +@Jpa( + annotatedClasses = { + OneToOnePrimaryKeyJoinColumnTest.Person.class, + OneToOnePrimaryKeyJoinColumnTest.PersonDetails.class + } +) +public class OneToOnePrimaryKeyJoinColumnTest { @Test - public void testLifecycle() { + public void testLifecycle(EntityManagerFactoryScope scope) { //tag::identifiers-derived-primarykeyjoincolumn-persist-example[] - doInJPA(this::entityManagerFactory, entityManager -> { - Person person = new Person("ABC-123"); - person.setId(1L); - entityManager.persist(person); + scope.inTransaction( entityManager -> { + Person person = new Person( "ABC-123" ); + person.setId( 1L ); + entityManager.persist( person ); PersonDetails personDetails = new PersonDetails(); - personDetails.setNickName("John Doe"); - personDetails.setPerson(person); + personDetails.setNickName( "John Doe" ); + personDetails.setPerson( person ); - entityManager.persist(personDetails); - }); + entityManager.persist( personDetails ); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { - PersonDetails personDetails = entityManager.find(PersonDetails.class, 1L); + scope.inTransaction( entityManager -> { + PersonDetails personDetails = entityManager.find( PersonDetails.class, 1L ); - assertEquals("John Doe", personDetails.getNickName()); - }); + assertThat( personDetails.getNickName() ).isEqualTo( "John Doe" ); + } ); //end::identifiers-derived-primarykeyjoincolumn-persist-example[] } //tag::identifiers-derived-primarykeyjoincolumn[] @Entity(name = "Person") - public static class Person { + public static class Person { @Id private Long id; @@ -63,7 +59,8 @@ public static class Person { @NaturalId private String registrationNumber; - public Person() {} + public Person() { + } public Person(String registrationNumber) { this.registrationNumber = registrationNumber; @@ -83,11 +80,11 @@ public void setId(Long id) { public String getRegistrationNumber() { return registrationNumber; } - //tag::identifiers-derived-primarykeyjoincolumn[] + //tag::identifiers-derived-primarykeyjoincolumn[] } @Entity(name = "PersonDetails") - public static class PersonDetails { + public static class PersonDetails { @Id private Long id; @@ -126,7 +123,7 @@ public Person getPerson() { return person; } - //tag::identifiers-derived-primarykeyjoincolumn[] + //tag::identifiers-derived-primarykeyjoincolumn[] } //end::identifiers-derived-primarykeyjoincolumn[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToOneUnidirectionalTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToOneUnidirectionalTest.java index b731dc9e41a8..2700bd9c1b48 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToOneUnidirectionalTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToOneUnidirectionalTest.java @@ -10,36 +10,31 @@ import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.OneToOne; - -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class OneToOneUnidirectionalTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Phone.class, - PhoneDetails.class, - }; - } +@Jpa( + annotatedClasses = { + OneToOneUnidirectionalTest.Phone.class, + OneToOneUnidirectionalTest.PhoneDetails.class, + } +) +public class OneToOneUnidirectionalTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { - Phone phone = new Phone("123-456-7890"); - PhoneDetails details = new PhoneDetails("T-Mobile", "GSM"); - - phone.setDetails(details); - entityManager.persist(phone); - entityManager.persist(details); - }); + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Phone phone = new Phone( "123-456-7890" ); + PhoneDetails details = new PhoneDetails( "T-Mobile", "GSM" ); + + phone.setDetails( details ); + entityManager.persist( phone ); + entityManager.persist( details ); + } ); } //tag::associations-one-to-one-unidirectional-example[] @@ -59,7 +54,7 @@ public static class Phone { //Getters and setters are omitted for brevity - //end::associations-one-to-one-unidirectional-example[] + //end::associations-one-to-one-unidirectional-example[] public Phone() { } @@ -83,7 +78,7 @@ public PhoneDetails getDetails() { public void setDetails(PhoneDetails details) { this.details = details; } - //tag::associations-one-to-one-unidirectional-example[] + //tag::associations-one-to-one-unidirectional-example[] } @Entity(name = "PhoneDetails") @@ -99,7 +94,7 @@ public static class PhoneDetails { //Getters and setters are omitted for brevity - //end::associations-one-to-one-unidirectional-example[] + //end::associations-one-to-one-unidirectional-example[] public PhoneDetails() { } @@ -120,7 +115,7 @@ public String getTechnology() { public void setTechnology(String technology) { this.technology = technology; } - //tag::associations-one-to-one-unidirectional-example[] + //tag::associations-one-to-one-unidirectional-example[] } //end::associations-one-to-one-unidirectional-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/UnidirectionalManyToManyRemoveTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/UnidirectionalManyToManyRemoveTest.java index e311bbb3039c..92509829be6c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/UnidirectionalManyToManyRemoveTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/UnidirectionalManyToManyRemoveTest.java @@ -4,62 +4,58 @@ */ package org.hibernate.orm.test.associations; -import java.util.ArrayList; -import java.util.List; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.ManyToMany; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import java.util.ArrayList; +import java.util.List; /** * @author Vlad Mihalcea */ -public class UnidirectionalManyToManyRemoveTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Address.class, - }; - } +@Jpa( + annotatedClasses = { + UnidirectionalManyToManyRemoveTest.Person.class, + UnidirectionalManyToManyRemoveTest.Address.class, + } +) +public class UnidirectionalManyToManyRemoveTest { @Test - public void testRemove() { + public void testRemove(EntityManagerFactoryScope scope) { try { - final Long personId = doInJPA(this::entityManagerFactory, entityManager -> { + final Long personId = scope.fromTransaction( entityManager -> { Person person1 = new Person(); Person person2 = new Person(); - Address address1 = new Address("12th Avenue", "12A"); - Address address2 = new Address("18th Avenue", "18B"); + Address address1 = new Address( "12th Avenue", "12A" ); + Address address2 = new Address( "18th Avenue", "18B" ); - person1.getAddresses().add(address1); - person1.getAddresses().add(address2); + person1.getAddresses().add( address1 ); + person1.getAddresses().add( address2 ); - person2.getAddresses().add(address1); + person2.getAddresses().add( address1 ); - entityManager.persist(person1); - entityManager.persist(person2); + entityManager.persist( person1 ); + entityManager.persist( person2 ); return person1.id; - }); - doInJPA(this::entityManagerFactory, entityManager -> { + } ); - Person person1 = entityManager.find(Person.class, personId); - entityManager.remove(person1); - }); + scope.inTransaction( entityManager -> { + Person person1 = entityManager.find( Person.class, personId ); + entityManager.remove( person1 ); + } ); } catch (Exception expected) { - log.error("Expected", expected); + //expected } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/AnyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/AnyTest.java index a7485975a6c3..e866c7021824 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/AnyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/AnyTest.java @@ -4,77 +4,71 @@ */ package org.hibernate.orm.test.associations.any; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.Jira; -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.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Vlad Mihalcea */ -public class AnyTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - IntegerProperty.class, - StringProperty.class, - PropertyHolder.class, - PropertyHolder2.class, - }; - } - - @Override - protected String[] getAnnotatedPackages() { - return new String[] { - getClass().getPackage().getName() - }; - } +@DomainModel( + annotatedClasses = { + IntegerProperty.class, + StringProperty.class, + PropertyHolder.class, + PropertyHolder2.class, + }, + annotatedPackageNames = "org.hibernate.orm.test.associations.any" +) +@SessionFactory +public class AnyTest { @Test - public void test() { + public void test(SessionFactoryScope scope) { - doInHibernate(this::sessionFactory, session -> { + scope.inTransaction( session -> { //tag::associations-any-persist-example[] IntegerProperty ageProperty = new IntegerProperty(); - ageProperty.setId(1L); - ageProperty.setName("age"); - ageProperty.setValue(23); + ageProperty.setId( 1L ); + ageProperty.setName( "age" ); + ageProperty.setValue( 23 ); - session.persist(ageProperty); + session.persist( ageProperty ); StringProperty nameProperty = new StringProperty(); - nameProperty.setId(1L); - nameProperty.setName("name"); - nameProperty.setValue("John Doe"); + nameProperty.setId( 1L ); + nameProperty.setName( "name" ); + nameProperty.setValue( "John Doe" ); - session.persist(nameProperty); + session.persist( nameProperty ); PropertyHolder namePropertyHolder = new PropertyHolder(); - namePropertyHolder.setId(1L); - namePropertyHolder.setProperty(nameProperty); + namePropertyHolder.setId( 1L ); + namePropertyHolder.setProperty( nameProperty ); - session.persist(namePropertyHolder); + session.persist( namePropertyHolder ); //end::associations-any-persist-example[] - }); + } ); - doInHibernate(this::sessionFactory, session -> { + scope.inTransaction( session -> { //tag::associations-any-query-example[] - PropertyHolder propertyHolder = session.get(PropertyHolder.class, 1L); + PropertyHolder propertyHolder = session.get( PropertyHolder.class, 1L ); - assertEquals("name", propertyHolder.getProperty().getName()); - assertEquals("John Doe", propertyHolder.getProperty().getValue()); + assertThat( propertyHolder.getProperty().getName() ).isEqualTo( "name" ); + assertThat( propertyHolder.getProperty().getValue() ).isEqualTo( "John Doe" ); //end::associations-any-query-example[] - }); + } ); } @Test - @Jira( "https://hibernate.atlassian.net/browse/HHH-16938" ) - public void testMetaAnnotated() { - doInHibernate( this::sessionFactory, session -> { + @Jira("https://hibernate.atlassian.net/browse/HHH-16938") + public void testMetaAnnotated(SessionFactoryScope scope) { + scope.inTransaction( session -> { final StringProperty nameProperty = new StringProperty(); nameProperty.setId( 2L ); nameProperty.setName( "name2" ); @@ -85,15 +79,15 @@ public void testMetaAnnotated() { namePropertyHolder.setProperty( nameProperty ); session.persist( namePropertyHolder ); } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { final PropertyHolder2 propertyHolder = session.get( PropertyHolder2.class, 2L ); - assertEquals( "name2", propertyHolder.getProperty().getName() ); - assertEquals( "Mario Rossi", propertyHolder.getProperty().getValue() ); + assertThat( propertyHolder.getProperty().getName() ).isEqualTo( "name2" ); + assertThat( propertyHolder.getProperty().getValue() ).isEqualTo( "Mario Rossi" ); final String propertyType = session.createNativeQuery( "select property_type from property_holder2", String.class ).getSingleResult(); - assertEquals( "S", propertyType ); + assertThat( propertyType ).isEqualTo( "S" ); } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/ManyToAnyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/ManyToAnyTest.java index ceb5acb13ca8..9ddb979f0a55 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/ManyToAnyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/ManyToAnyTest.java @@ -4,74 +4,67 @@ */ package org.hibernate.orm.test.associations.any; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -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.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Vlad Mihalcea */ -public class ManyToAnyTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - IntegerProperty.class, - StringProperty.class, - PropertyRepository.class - }; - } - - @Override - protected String[] getAnnotatedPackages() { - return new String[] { - getClass().getPackage().getName() - }; - } +@DomainModel( + annotatedClasses = { + IntegerProperty.class, + StringProperty.class, + PropertyRepository.class + }, + annotatedPackageNames = "org.hibernate.orm.test.associations.any" +) +@SessionFactory +public class ManyToAnyTest { @Test - public void test() { + public void test(SessionFactoryScope scope) { - doInHibernate(this::sessionFactory, session -> { + scope.inTransaction( session -> { //tag::associations-many-to-any-persist-example[] IntegerProperty ageProperty = new IntegerProperty(); - ageProperty.setId(1L); - ageProperty.setName("age"); - ageProperty.setValue(23); + ageProperty.setId( 1L ); + ageProperty.setName( "age" ); + ageProperty.setValue( 23 ); - session.persist(ageProperty); + session.persist( ageProperty ); StringProperty nameProperty = new StringProperty(); - nameProperty.setId(1L); - nameProperty.setName("name"); - nameProperty.setValue("John Doe"); + nameProperty.setId( 1L ); + nameProperty.setName( "name" ); + nameProperty.setValue( "John Doe" ); - session.persist(nameProperty); + session.persist( nameProperty ); PropertyRepository propertyRepository = new PropertyRepository(); - propertyRepository.setId(1L); + propertyRepository.setId( 1L ); - propertyRepository.getProperties().add(ageProperty); - propertyRepository.getProperties().add(nameProperty); + propertyRepository.getProperties().add( ageProperty ); + propertyRepository.getProperties().add( nameProperty ); - session.persist(propertyRepository); + session.persist( propertyRepository ); //end::associations-many-to-any-persist-example[] - }); + } ); - doInHibernate(this::sessionFactory, session -> { + scope.inTransaction( session -> { //tag::associations-many-to-any-query-example[] - PropertyRepository propertyRepository = session.get(PropertyRepository.class, 1L); + PropertyRepository propertyRepository = session.get( PropertyRepository.class, 1L ); - assertEquals(2, propertyRepository.getProperties().size()); + assertThat( propertyRepository.getProperties().size() ).isEqualTo( 2 ); - for(Property property : propertyRepository.getProperties()) { - assertNotNull(property.getValue()); + for ( Property property : propertyRepository.getProperties() ) { + assertThat( property.getValue() ).isNotNull(); } //end::associations-many-to-any-query-example[] - }); + } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/batch/BatchOptimisticLockingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/batch/BatchOptimisticLockingTest.java index 96e671c6274c..a0471e83b5b4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/batch/BatchOptimisticLockingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/batch/BatchOptimisticLockingTest.java @@ -4,54 +4,55 @@ */ package org.hibernate.orm.test.batch; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.OptimisticLockException; import jakarta.persistence.RollbackException; +import jakarta.persistence.Version; import org.hibernate.cfg.AvailableSettings; import org.hibernate.dialect.CockroachDialect; - +import org.hibernate.dialect.Dialect; import org.hibernate.dialect.MariaDBDialect; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -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.Test; -import jakarta.persistence.Entity; -import jakarta.persistence.Id; -import jakarta.persistence.OptimisticLockException; -import jakarta.persistence.Version; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hibernate.testing.orm.junit.DialectContext.getDialect; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Vlad Mihalcea */ -public class BatchOptimisticLockingTest extends - BaseNonConfigCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + BatchOptimisticLockingTest.Person.class + } +) +@SessionFactory +@ServiceRegistry( + settings = { + @Setting(name = AvailableSettings.STATEMENT_BATCH_SIZE, value = "2"), + @Setting(name = AvailableSettings.DIALECT_NATIVE_PARAM_MARKERS, value = "false") + } +) +public class BatchOptimisticLockingTest { private final ExecutorService executorService = Executors.newSingleThreadExecutor(); - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - Person.class, - }; - } - - @Override - protected void addSettings(Map settings) { - settings.put( AvailableSettings.STATEMENT_BATCH_SIZE, String.valueOf( 2 ) ); - settings.put( AvailableSettings.DIALECT_NATIVE_PARAM_MARKERS, Boolean.FALSE ); - } @Test - public void testBatchAndOptimisticLocking() { - doInHibernate( this::sessionFactory, session -> { + public void testBatchAndOptimisticLocking(SessionFactoryScope scope) { + scope.inTransaction( session -> { Person person1 = new Person(); person1.id = 1L; person1.name = "First"; @@ -69,58 +70,49 @@ public void testBatchAndOptimisticLocking() { } ); - try { - inTransaction( session -> { - List persons = session - .createSelectionQuery( "select p from Person p", Person.class ) - .getResultList(); - - for ( int i = 0; i < persons.size(); i++ ) { - Person person = persons.get( i ); - person.name += " Person"; - - if ( i == 1 ) { - try { - executorService.submit( () -> { - doInHibernate( this::sessionFactory, _session -> { - Person _person = _session.find( Person.class, person.id ); - _person.name += " Person is the new Boss!"; - } ); - } ).get(); - } - catch (InterruptedException|ExecutionException e) { - fail(e.getMessage()); - } + Exception exception = assertThrows( Exception.class, () -> scope.inTransaction( session -> { + List persons = session + .createSelectionQuery( "select p from Person p", Person.class ) + .getResultList(); + + for ( int i = 0; i < persons.size(); i++ ) { + Person person = persons.get( i ); + person.name += " Person"; + + if ( i == 1 ) { + try { + executorService.submit( () -> { + scope.inTransaction( _session -> { + Person _person = _session.find( Person.class, person.id ); + _person.name += " Person is the new Boss!"; + } ); + } ).get(); + } + catch (InterruptedException | ExecutionException e) { + fail( e.getMessage() ); } } - } ); + } + } ) ); + + Dialect dialect = scope.getSessionFactory().getJdbcServices().getDialect(); + if ( dialect instanceof CockroachDialect ) { + // CockroachDB always runs in SERIALIZABLE isolation, and uses SQL state 40001 to indicate + // serialization failure. The failure is mapped to a RollbackException. + assertThat( exception ).isInstanceOf( RollbackException.class ); + var msg = "could not execute batch"; + assertThat( exception.getMessage() ).contains( msg ); } - catch (Exception expected) { - if ( getDialect() instanceof CockroachDialect ) { - // CockroachDB always runs in SERIALIZABLE isolation, and uses SQL state 40001 to indicate - // serialization failure. The failure is mapped to a RollbackException. - assertEquals( RollbackException.class, expected.getClass() ); - var msg = "could not execute batch"; - assertEquals( - msg, - expected.getMessage().substring( 0, msg.length() ) - ); + else { + assertThat( exception ).isInstanceOf( OptimisticLockException.class ); + + if ( dialect instanceof MariaDBDialect && getDialect().getVersion().isAfter( 11, 6, 2 ) ) { + assertThat( exception.getMessage() ).contains( "Record has changed since last read in table 'Person'" ); + } else { - assertEquals( OptimisticLockException.class, expected.getClass() ); - - if ( getDialect() instanceof MariaDBDialect && getDialect().getVersion().isAfter( 11, 6, 2 )) { - assertTrue( - expected.getMessage() - .contains( "Record has changed since last read in table 'Person'" ) - ); - } else { - assertTrue( - expected.getMessage() - .startsWith( - "Batch update returned unexpected row count from update 1 (expected row count 1 but was 0) [update Person set name=?,version=? where id=? and version=?]" ) - ); - } + assertThat( exception.getMessage() ).startsWith( + "Batch update returned unexpected row count from update 1 (expected row count 1 but was 0) [update Person set name=?,version=? where id=? and version=?]" ); } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/batch/BatchTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/batch/BatchTests.java index 12127abe782b..776d3fe60152 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/batch/BatchTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/batch/BatchTests.java @@ -4,331 +4,267 @@ */ package org.hibernate.orm.test.batch; -import jakarta.persistence.EntityManager; -import jakarta.persistence.EntityTransaction; - import org.hibernate.CacheMode; import org.hibernate.ScrollMode; import org.hibernate.ScrollableResults; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.StatelessSession; -import org.hibernate.Transaction; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.hibernate.resource.transaction.spi.TransactionStatus; import org.hibernate.testing.orm.domain.userguide.Account; import org.hibernate.testing.orm.domain.userguide.Call; import org.hibernate.testing.orm.domain.userguide.Partner; import org.hibernate.testing.orm.domain.userguide.Payment; import org.hibernate.testing.orm.domain.userguide.Person; import org.hibernate.testing.orm.domain.userguide.Phone; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Vlad Mihalcea */ -public class BatchTests extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class, - Call.class, - Account.class, - Payment.class, - Partner.class - }; - } +@Jpa( + annotatedClasses = { + Person.class, + Phone.class, + Call.class, + Account.class, + Payment.class, + Partner.class + } +) +public class BatchTests { @Test - public void testScroll() { - withScroll(); + public void testScroll(EntityManagerFactoryScope scope) { + withScroll( scope ); } @Test - public void testStatelessSession() { - withStatelessSession(); + public void testStatelessSession(EntityManagerFactoryScope scope) { + withStatelessSession( scope ); } @Test - public void testBulk() { - doInJPA(this::entityManagerFactory, entityManager -> { - entityManager.persist(new Person("Vlad")); - entityManager.persist(new Person("Mihalcea")); - }); - doInJPA(this::entityManagerFactory, entityManager -> { + public void testBulk(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + entityManager.persist( new Person( "Vlad" ) ); + entityManager.persist( new Person( "Mihalcea" ) ); + } ); + scope.inTransaction( entityManager -> { String oldName = "Vlad"; String newName = "Alexandru"; //tag::batch-session-jdbc-batch-size-example[] entityManager - .unwrap(Session.class) - .setJdbcBatchSize(10); + .unwrap( Session.class ) + .setJdbcBatchSize( 10 ); //end::batch-session-jdbc-batch-size-example[] - }); - doInJPA(this::entityManagerFactory, entityManager -> { + } ); + scope.inTransaction( entityManager -> { String oldName = "Vlad"; String newName = "Alexandru"; //tag::batch-bulk-jpql-update-example[] int updatedEntities = entityManager.createQuery( - "update Person p " + - "set p.name = :newName " + - "where p.name = :oldName") - .setParameter("oldName", oldName) - .setParameter("newName", newName) - .executeUpdate(); + "update Person p " + + "set p.name = :newName " + + "where p.name = :oldName" ) + .setParameter( "oldName", oldName ) + .setParameter( "newName", newName ) + .executeUpdate(); //end::batch-bulk-jpql-update-example[] - assertEquals(1, updatedEntities); - }); + assertThat( updatedEntities ).isEqualTo( 1 ); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { String oldName = "Alexandru"; String newName = "Vlad"; - Session session = entityManager.unwrap(Session.class); + Session session = entityManager.unwrap( Session.class ); //tag::batch-bulk-hql-update-example[] int updatedEntities = session.createMutationQuery( - "update Person " + - "set name = :newName " + - "where name = :oldName") - .setParameter("oldName", oldName) - .setParameter("newName", newName) - .executeUpdate(); + "update Person " + + "set name = :newName " + + "where name = :oldName" ) + .setParameter( "oldName", oldName ) + .setParameter( "newName", newName ) + .executeUpdate(); //end::batch-bulk-hql-update-example[] - assertEquals(1, updatedEntities); - }); + assertThat( updatedEntities ).isEqualTo( 1 ); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { String oldName = "Vlad"; String newName = "Alexandru"; - Session session = entityManager.unwrap(Session.class); + Session session = entityManager.unwrap( Session.class ); //tag::batch-bulk-hql-update-version-example[] int updatedEntities = session.createMutationQuery( - "update versioned Person " + - "set name = :newName " + - "where name = :oldName") - .setParameter("oldName", oldName) - .setParameter("newName", newName) - .executeUpdate(); + "update versioned Person " + + "set name = :newName " + + "where name = :oldName" ) + .setParameter( "oldName", oldName ) + .setParameter( "newName", newName ) + .executeUpdate(); //end::batch-bulk-hql-update-version-example[] - assertEquals(1, updatedEntities); - }); + assertThat( updatedEntities ).isEqualTo( 1 ); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { String name = "Alexandru"; //tag::batch-bulk-jpql-delete-example[] int deletedEntities = entityManager.createQuery( - "delete Person p " + - "where p.name = :name") - .setParameter("name", name) - .executeUpdate(); + "delete Person p " + + "where p.name = :name" ) + .setParameter( "name", name ) + .executeUpdate(); //end::batch-bulk-jpql-delete-example[] - assertEquals(1, deletedEntities); - }); + assertThat( deletedEntities ).isEqualTo( 1 ); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { - Session session = entityManager.unwrap(Session.class); + Session session = entityManager.unwrap( Session.class ); //tag::batch-bulk-hql-insert-example[] int insertedEntities = session.createMutationQuery( - "insert into Partner (id, name) " + - "select p.id, p.name " + - "from Person p ") - .executeUpdate(); + "insert into Partner (id, name) " + + "select p.id, p.name " + + "from Person p " ) + .executeUpdate(); //end::batch-bulk-hql-insert-example[] - assertEquals(1, insertedEntities); - }); + assertThat( insertedEntities ).isEqualTo( 1 ); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { String name = "Mihalcea"; - Session session = entityManager.unwrap(Session.class); + Session session = entityManager.unwrap( Session.class ); //tag::batch-bulk-hql-delete-example[] int deletedEntities = session.createMutationQuery( - "delete Person " + - "where name = :name") - .setParameter("name", name) - .executeUpdate(); + "delete Person " + + "where name = :name" ) + .setParameter( "name", name ) + .executeUpdate(); //end::batch-bulk-hql-delete-example[] - assertEquals(1, deletedEntities); - }); + assertThat( deletedEntities ).isEqualTo( 1 ); + } ); } - private void withoutBatch() { + private void withoutBatch(EntityManagerFactoryScope scope) { //tag::batch-session-batch-example[] - EntityManager entityManager = null; - EntityTransaction txn = null; - try { - entityManager = entityManagerFactory().createEntityManager(); - - txn = entityManager.getTransaction(); - txn.begin(); - - for (int i = 0; i < 100_000; i++) { - Person Person = new Person(String.format("Person %d", i)); - entityManager.persist(Person); - } - - txn.commit(); - } - catch (RuntimeException e) { - if (txn != null && txn.isActive()) { - txn.rollback(); - } - throw e; - } - finally { - if (entityManager != null) { - entityManager.close(); - } - } + scope.inTransaction( + entityManager -> { + for ( int i = 0; i < 100_000; i++ ) { + Person Person = new Person( String.format( "Person %d", i ) ); + entityManager.persist( Person ); + } + } + ); //end::batch-session-batch-example[] } - private void withBatch() { + private void withBatch(EntityManagerFactoryScope scope) { int entityCount = 100; + int batchSize = 25; //tag::batch-session-batch-insert-example[] - EntityManager entityManager = null; - EntityTransaction txn = null; - try { - entityManager = entityManagerFactory().createEntityManager(); - - txn = entityManager.getTransaction(); - txn.begin(); - - int batchSize = 25; - - for (int i = 0; i < entityCount; i++) { - if (i > 0 && i % batchSize == 0) { - //flush a batch of inserts and release memory - entityManager.flush(); - entityManager.clear(); + scope.inTransaction( + entityManager -> { + for ( int i = 0; i < entityCount; i++ ) { + if ( i > 0 && i % batchSize == 0 ) { + //flush a batch of inserts and release memory + entityManager.flush(); + entityManager.clear(); + } + + Person Person = new Person( String.format( "Person %d", i ) ); + entityManager.persist( Person ); + } } - - Person Person = new Person(String.format("Person %d", i)); - entityManager.persist(Person); - } - - txn.commit(); - } - catch (RuntimeException e) { - if (txn != null && txn.isActive()) { - txn.rollback(); - } - throw e; - } - finally { - if (entityManager != null) { - entityManager.close(); - } - } + ); //end::batch-session-batch-insert-example[] } - private void withScroll() { - withBatch(); + private void withScroll(EntityManagerFactoryScope scope) { + withBatch( scope ); + int batchSize = 25; //tag::batch-session-scroll-example[] - EntityManager entityManager = null; - EntityTransaction txn = null; - ScrollableResults scrollableResults = null; - try { - entityManager = entityManagerFactory().createEntityManager(); - - txn = entityManager.getTransaction(); - txn.begin(); - - int batchSize = 25; - - Session session = entityManager.unwrap(Session.class); - - scrollableResults = - session.createSelectionQuery("select p from Person p") - .setCacheMode(CacheMode.IGNORE) - .scroll(ScrollMode.FORWARD_ONLY); - - int count = 0; - while (scrollableResults.next()) { - Person Person = (Person) scrollableResults.get(); - processPerson(Person); - if (++count % batchSize == 0) { - //flush a batch of updates and release memory: - entityManager.flush(); - entityManager.clear(); + scope.inTransaction( + entityManager -> { + ScrollableResults scrollableResults = null; + try { + scrollableResults = entityManager.unwrap( Session.class ) + .createSelectionQuery( "select p from Person p", Person.class ) + .setCacheMode( CacheMode.IGNORE ) + .scroll( ScrollMode.FORWARD_ONLY ); + + int count = 0; + while ( scrollableResults.next() ) { + Person Person = (Person) scrollableResults.get(); + processPerson( Person ); + if ( ++count % batchSize == 0 ) { + //flush a batch of updates and release memory: + entityManager.flush(); + entityManager.clear(); + } + } + } + finally { + if ( scrollableResults != null ) { + scrollableResults.close(); + } + } } - } - - txn.commit(); - } - catch (RuntimeException e) { - if (txn != null && txn.isActive()) { - txn.rollback(); - } - throw e; - } - finally { - if (scrollableResults != null) { - scrollableResults.close(); - } - if (entityManager != null) { - entityManager.close(); - } - } + ); //end::batch-session-scroll-example[] } - private void withStatelessSession() { - withBatch(); - + private void withStatelessSession(EntityManagerFactoryScope scope) { + withBatch( scope ); + SessionFactory sessionFactory = scope.getEntityManagerFactory().unwrap( SessionFactory.class ); //tag::batch-stateless-session-example[] StatelessSession statelessSession = null; - Transaction txn = null; ScrollableResults scrollableResults = null; try { - SessionFactory sessionFactory = entityManagerFactory().unwrap(SessionFactory.class); statelessSession = sessionFactory.openStatelessSession(); - - txn = statelessSession.getTransaction(); - txn.begin(); - + statelessSession.beginTransaction(); scrollableResults = - statelessSession.createSelectionQuery("select p from Person p") - .scroll(ScrollMode.FORWARD_ONLY); + statelessSession.createSelectionQuery( "select p from Person p", Person.class ) + .scroll( ScrollMode.FORWARD_ONLY ); - while (scrollableResults.next()) { + while ( scrollableResults.next() ) { Person Person = (Person) scrollableResults.get(); - processPerson(Person); - statelessSession.update(Person); + processPerson( Person ); + statelessSession.update( Person ); } - - txn.commit(); - } - catch (RuntimeException e) { - if (txn != null && txn.getStatus() == TransactionStatus.ACTIVE) { - txn.rollback(); - } - throw e; + statelessSession.getTransaction().commit(); } finally { - if (scrollableResults != null) { - scrollableResults.close(); + try { + if ( scrollableResults != null ) { + scrollableResults.close(); + } + + if ( statelessSession != null ) { + if ( statelessSession.getTransaction().isActive() ) { + statelessSession.getTransaction().rollback(); + } + } } - if (statelessSession != null) { - statelessSession.close(); + finally { + if ( statelessSession != null ) { + statelessSession.close(); + } } } //end::batch-stateless-session-example[] } private void processPerson(Person Person) { - if (Person.getId() % 1000 == 0) { - log.infof("Processing [%s]", Person.getName()); + if ( Person.getId() % 1000 == 0 ) { + Person.getName(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/batch/BatchingBatchFailureTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/batch/BatchingBatchFailureTest.java index d4727217b183..8ee65a6c355d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/batch/BatchingBatchFailureTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/batch/BatchingBatchFailureTest.java @@ -4,46 +4,46 @@ */ package org.hibernate.orm.test.batch; -import java.lang.reflect.Field; - +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; import org.hibernate.SessionEventListener; import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; import org.hibernate.engine.jdbc.batch.spi.Batch; import org.hibernate.engine.jdbc.mutation.group.PreparedStatementDetails; import org.hibernate.engine.spi.SessionImplementor; - +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 jakarta.persistence.Column; -import jakarta.persistence.Entity; -import jakarta.persistence.Id; -import jakarta.persistence.Table; +import java.lang.reflect.Field; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Shawn Clowater * @author Steve Ebersole */ -@JiraKey( value = "HHH-7689" ) -public class BatchingBatchFailureTest extends BaseCoreFunctionalTestCase implements SessionEventListener { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { User.class }; - } - - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - // explicitly enable batching - configuration.setProperty( AvailableSettings.STATEMENT_BATCH_SIZE, 5 ); - // and disable in-vm nullability checking (so we can force in-db not-null constraint violations) - configuration.setProperty( AvailableSettings.CHECK_NULLABILITY, false ); - } +@JiraKey(value = "HHH-7689") +@DomainModel( + annotatedClasses = { + BatchingBatchFailureTest.User.class + } +) +@SessionFactory +@ServiceRegistry( + settings = { + @Setting(name = AvailableSettings.STATEMENT_BATCH_SIZE, value = "5"), + @Setting(name = AvailableSettings.CHECK_NULLABILITY, value = "false") + } +) +public class BatchingBatchFailureTest implements SessionEventListener { SessionImplementor session; Batch batch; @@ -56,16 +56,17 @@ public void jdbcExecuteBatchStart() { batch = (Batch) field.get( session.getJdbcCoordinator() ); } catch (Exception e) { - throw new RuntimeException(e); + throw new RuntimeException( e ); } } @Test - public void testBasicInsertion() { - session = sessionFactory().withOptions().eventListeners( this ).openSession(); - session.getTransaction().begin(); + public void testBasicInsertion(SessionFactoryScope scope) { + session = scope.getSessionFactory().withOptions().eventListeners( this ).openSession(); + try { + session.getTransaction().begin(); session.persist( new User( 1, "ok" ) ); session.persist( new User( 2, null ) ); session.persist( new User( 3, "ok" ) ); @@ -87,7 +88,8 @@ public void testBasicInsertion() { } else { // //check to see that there aren't any statements queued up (this can be an issue if using SavePoints) - final PreparedStatementDetails statementDetails = batch.getStatementGroup().getSingleStatementDetails(); + final PreparedStatementDetails statementDetails = batch.getStatementGroup() + .getSingleStatementDetails(); assertThat( statementDetails.getStatement() ).isNull(); } } @@ -101,8 +103,8 @@ public void testBasicInsertion() { } } - @Entity( name = "User" ) - @Table( name = "`USER`" ) + @Entity(name = "User") + @Table(name = "`USER`") public static class User { private Integer id; private String name; @@ -124,7 +126,7 @@ public void setId(Integer id) { this.id = id; } - @Column( nullable = false ) + @Column(nullable = false) public String getName() { return name; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/batch/BatchingInheritanceDeleteTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/batch/BatchingInheritanceDeleteTest.java index 90da08ba4e7c..867fa67dc553 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/batch/BatchingInheritanceDeleteTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/batch/BatchingInheritanceDeleteTest.java @@ -4,8 +4,6 @@ */ package org.hibernate.orm.test.batch; -import java.util.ArrayList; -import java.util.List; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -19,59 +17,60 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.MappedSuperclass; import jakarta.persistence.OneToMany; - import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; - +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.ArrayList; +import java.util.List; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Vlad Mihalcea */ -@JiraKey( value = "HHH-12470" ) -public class BatchingInheritanceDeleteTest extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - Foo.class, - Bar.class, - Baz.class - }; - } - - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - configuration.setProperty( AvailableSettings.STATEMENT_BATCH_SIZE, 25 ); - } +@JiraKey(value = "HHH-12470") +@DomainModel( + annotatedClasses = { + BatchingInheritanceDeleteTest.Foo.class, + BatchingInheritanceDeleteTest.Bar.class, + BatchingInheritanceDeleteTest.Baz.class + } +) +@SessionFactory +@ServiceRegistry( + settings = { + @Setting(name = AvailableSettings.STATEMENT_BATCH_SIZE, value = "25") + } +) +public class BatchingInheritanceDeleteTest { @Test //@FailureExpected( jiraKey = "HHH-12470" ) - public void testDelete() { - doInHibernate( this::sessionFactory, s -> { - Bar bar = new Bar("bar"); + public void testDelete(SessionFactoryScope scope) { + scope.inTransaction( s -> { + Bar bar = new Bar( "bar" ); - Foo foo = new Foo("foo"); - foo.setBar(bar); + Foo foo = new Foo( "foo" ); + foo.setBar( bar ); - s.persist(foo); - s.persist(bar); + s.persist( foo ); + s.persist( bar ); s.flush(); - s.remove(foo); - s.remove(bar); + s.remove( foo ); + s.remove( bar ); s.flush(); - assertThat(s.find(Foo.class, foo.getId()), nullValue()); - assertThat(s.find(Bar.class, bar.getId()), nullValue()); + assertThat( s.find( Foo.class, foo.getId() ) ).isNull(); + assertThat( s.find( Bar.class, bar.getId() ) ).isNull(); } ); } @@ -112,7 +111,7 @@ public void setBazList(final List bazList) { @Override public String toString() { final StringBuilder builder = new StringBuilder(); - builder.append("Bar [name=").append(name).append("]"); + builder.append( "Bar [name=" ).append( name ).append( "]" ); return builder.toString(); } } @@ -155,7 +154,7 @@ public void setName(final String name) { @Override public String toString() { final StringBuilder builder = new StringBuilder(); - builder.append("Bar [name=").append(name).append("]"); + builder.append( "Bar [name=" ).append( name ).append( "]" ); return builder.toString(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/batch/NonBatchingBatchFailureTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/batch/NonBatchingBatchFailureTest.java index 8f9b01c7873d..f04d931a24e7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/batch/NonBatchingBatchFailureTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/batch/NonBatchingBatchFailureTest.java @@ -4,83 +4,80 @@ */ package org.hibernate.orm.test.batch; -import java.lang.reflect.Field; - -import org.hibernate.Session; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; -import org.hibernate.engine.jdbc.batch.spi.Batch; -import org.hibernate.engine.spi.SessionImplementor; - -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; - import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; +import org.hibernate.cfg.AvailableSettings; +import org.hibernate.engine.jdbc.batch.spi.Batch; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.JiraKey; +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.lang.reflect.Field; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.fail; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; /** * @author Shawn Clowater * @author Steve Ebersole */ -@JiraKey( value = "HHH-7689" ) -public class NonBatchingBatchFailureTest extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { User.class }; - } - - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - // explicitly disable batching - configuration.setProperty( AvailableSettings.STATEMENT_BATCH_SIZE, -1 ); - // and disable in-vm nullability checking (so we can force in-db not-null constraint violations) - configuration.setProperty( AvailableSettings.CHECK_NULLABILITY, false ); - } - - @Test - public void testBasicInsertion() { - Session session = openSession(); - session.getTransaction().begin(); - - try { - session.persist( new User( 1, "ok" ) ); - session.persist( new User( 2, null ) ); - session.persist( new User( 3, "ok" ) ); - // the flush should fail - session.flush(); - fail( "Expecting failed flush" ); - } - catch (Exception expected) { - System.out.println( "Caught expected exception : " + expected ); - expected.printStackTrace( System.out ); - - try { - //at this point the transaction is still active but the batch should have been aborted (have to use reflection to get at the field) - SessionImplementor sessionImplementor = (SessionImplementor) session; - Field field = sessionImplementor.getJdbcCoordinator().getClass().getDeclaredField( "currentBatch" ); - field.setAccessible( true ); - Batch batch = (Batch) field.get( sessionImplementor.getJdbcCoordinator() ); - assertNull( batch ); - } - catch (Exception fieldException) { - fail( "Couldn't inspect field " + fieldException.getMessage() ); - } +@JiraKey(value = "HHH-7689") +@DomainModel( + annotatedClasses = { + NonBatchingBatchFailureTest.User.class } - finally { - session.getTransaction().rollback(); - session.close(); +) +@SessionFactory +@ServiceRegistry( + settings = { + @Setting(name = AvailableSettings.STATEMENT_BATCH_SIZE, value = "-1"), + @Setting(name = AvailableSettings.CHECK_NULLABILITY, value = "false") } +) +public class NonBatchingBatchFailureTest { + + @Test + public void testBasicInsertion(SessionFactoryScope scope) { + scope.inSession( + session -> { + session.getTransaction().begin(); + + try { + session.persist( new User( 1, "ok" ) ); + session.persist( new User( 2, null ) ); + session.persist( new User( 3, "ok" ) ); + // the flush should fail + session.flush(); + fail( "Expecting failed flush" ); + } + catch (Exception expected) { + try { + //at this point the transaction is still active but the batch should have been aborted (have to use reflection to get at the field) + Field field = session.getJdbcCoordinator().getClass().getDeclaredField( "currentBatch" ); + field.setAccessible( true ); + Batch batch = (Batch) field.get( session.getJdbcCoordinator() ); + assertThat( batch ).isNull(); + } + catch (Exception fieldException) { + fail( "Couldn't inspect field " + fieldException.getMessage() ); + } + } + finally { + session.getTransaction().rollback(); + } + } + ); } - @Entity( name = "User" ) - @Table( name = "`USER`" ) + @Entity(name = "User") + @Table(name = "`USER`") public static class User { private Integer id; private String name; @@ -102,7 +99,7 @@ public void setId(Integer id) { this.id = id; } - @Column( nullable = false ) + @Column(nullable = false) public String getName() { return name; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/BootstrapTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/BootstrapTest.java index 5073f9edd2b6..4e7de7a2205e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/BootstrapTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/BootstrapTest.java @@ -380,6 +380,7 @@ public void test_bootstrap_bootstrap_native_SessionFactory_example() { SessionFactory sessionFactory = metadata.getSessionFactoryBuilder() .applyBeanManager(getBeanManager()) .build(); + sessionFactory.close(); //end::bootstrap-native-SessionFactory-example[] } { @@ -410,6 +411,7 @@ public void test_bootstrap_bootstrap_native_SessionFactory_example() { SessionFactory sessionFactory = sessionFactoryBuilder.build(); //end::bootstrap-native-SessionFactoryBuilder-example[] + sessionFactory.close(); } } catch (Exception ignore) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/access/jpa/AccessMappingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/access/jpa/AccessMappingTest.java index 976bc11d123f..77f51ae684d6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/access/jpa/AccessMappingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/access/jpa/AccessMappingTest.java @@ -14,16 +14,16 @@ import org.hibernate.property.access.spi.GetterFieldImpl; import org.hibernate.property.access.spi.GetterMethodImpl; import org.hibernate.service.ServiceRegistry; -import org.hibernate.type.descriptor.java.spi.JdbcTypeRecommendationException; - import org.hibernate.testing.ServiceRegistryBuilder; +import org.hibernate.testing.orm.junit.BaseUnitTest; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.type.descriptor.java.spi.JdbcTypeRecommendationException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.fail; /** @@ -31,15 +31,16 @@ * * @author Hardy Ferentschik */ +@BaseUnitTest public class AccessMappingTest { private ServiceRegistry serviceRegistry; - @Before + @BeforeEach public void setUp() { serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry( Environment.getProperties() ); } - @After + @AfterEach public void tearDown() { if ( serviceRegistry != null ) { ServiceRegistryBuilder.destroy( serviceRegistry ); @@ -51,19 +52,12 @@ public void testInconsistentAnnotationPlacement() { Configuration cfg = new Configuration(); cfg.addAnnotatedClass( Course1.class ); cfg.addAnnotatedClass( Student.class ); - SessionFactory sf = null; - try { - sf = cfg.buildSessionFactory( serviceRegistry ); + try (SessionFactory sf = cfg.buildSessionFactory( serviceRegistry )) { fail( "@Id and @OneToMany are not placed consistently in test entities. SessionFactory creation should fail." ); } catch (MappingException | JdbcTypeRecommendationException e) { // success } - finally { - if ( sf != null ) { - sf.close(); - } - } } @Test @@ -72,20 +66,16 @@ public void testFieldAnnotationPlacement() { Class classUnderTest = Course6.class; cfg.addAnnotatedClass( classUnderTest ); cfg.addAnnotatedClass( Student.class ); - SessionFactoryImplementor factory = (SessionFactoryImplementor) cfg.buildSessionFactory( serviceRegistry ); - try { + try (SessionFactoryImplementor factory = (SessionFactoryImplementor) cfg + .buildSessionFactory( serviceRegistry )) { final EntityPersister entityPersister = factory.getRuntimeMetamodels() .getMappingMetamodel() - .getEntityDescriptor(classUnderTest.getName()); + .getEntityDescriptor( classUnderTest.getName() ); final BasicEntityIdentifierMappingImpl identifierMapping = (BasicEntityIdentifierMappingImpl) entityPersister.getIdentifierMapping(); - assertTrue( - "Field access should be used.", - identifierMapping.getPropertyAccess().getGetter() instanceof GetterFieldImpl - ); - } - finally { - factory.close(); + assertThat( identifierMapping.getPropertyAccess().getGetter() ) + .describedAs( "Field access should be used." ) + .isInstanceOf( GetterFieldImpl.class ); } } @@ -95,43 +85,36 @@ public void testPropertyAnnotationPlacement() { Class classUnderTest = Course7.class; cfg.addAnnotatedClass( classUnderTest ); cfg.addAnnotatedClass( Student.class ); - SessionFactoryImplementor factory = (SessionFactoryImplementor) cfg.buildSessionFactory( serviceRegistry ); - try { + + try (SessionFactoryImplementor factory = (SessionFactoryImplementor) cfg + .buildSessionFactory( serviceRegistry )) { final EntityPersister entityPersister = factory.getRuntimeMetamodels() .getMappingMetamodel() - .getEntityDescriptor(classUnderTest.getName()); + .getEntityDescriptor( classUnderTest.getName() ); final BasicEntityIdentifierMappingImpl identifierMapping = (BasicEntityIdentifierMappingImpl) entityPersister.getIdentifierMapping(); - assertTrue( - "Property access should be used.", - identifierMapping.getPropertyAccess().getGetter() instanceof GetterMethodImpl - ); - } - finally { - factory.close(); + assertThat( identifierMapping.getPropertyAccess().getGetter() ) + .describedAs( "Property access should be used." ) + .isInstanceOf( GetterMethodImpl.class ); } } @Test - public void testExplicitPropertyAccessAnnotationsOnProperty() throws Exception { + public void testExplicitPropertyAccessAnnotationsOnProperty() { Configuration cfg = new Configuration(); Class classUnderTest = Course2.class; cfg.addAnnotatedClass( classUnderTest ); cfg.addAnnotatedClass( Student.class ); - SessionFactoryImplementor factory = (SessionFactoryImplementor) cfg.buildSessionFactory( serviceRegistry ); - try { + try (SessionFactoryImplementor factory = (SessionFactoryImplementor) cfg + .buildSessionFactory( serviceRegistry )) { final EntityPersister entityPersister = factory.getRuntimeMetamodels() .getMappingMetamodel() - .getEntityDescriptor(classUnderTest.getName()); + .getEntityDescriptor( classUnderTest.getName() ); final BasicEntityIdentifierMappingImpl identifierMapping = (BasicEntityIdentifierMappingImpl) entityPersister.getIdentifierMapping(); - assertTrue( - "Property access should be used.", - identifierMapping.getPropertyAccess().getGetter() instanceof GetterMethodImpl - ); - } - finally { - factory.close(); + assertThat( identifierMapping.getPropertyAccess().getGetter() ) + .describedAs( "Property access should be used." ) + .isInstanceOf( GetterMethodImpl.class ); } } @@ -140,19 +123,12 @@ public void testExplicitPropertyAccessAnnotationsOnField() { Configuration cfg = new Configuration(); cfg.addAnnotatedClass( Course4.class ); cfg.addAnnotatedClass( Student.class ); - SessionFactory sf = null; - try { - sf = cfg.buildSessionFactory( serviceRegistry ); + try (SessionFactory sf = cfg.buildSessionFactory( serviceRegistry )) { fail( "@Id and @OneToMany are not placed consistently in test entities. SessionFactory creation should fail." ); } catch (MappingException e) { // success } - finally { - if ( sf != null ) { - sf.close(); - } - } } @Test @@ -161,25 +137,20 @@ public void testExplicitPropertyAccessAnnotationsWithHibernateStyleOverride() { Class classUnderTest = Course3.class; cfg.addAnnotatedClass( classUnderTest ); cfg.addAnnotatedClass( Student.class ); - SessionFactoryImplementor factory = (SessionFactoryImplementor) cfg.buildSessionFactory( serviceRegistry ); - try { + try (SessionFactoryImplementor factory = (SessionFactoryImplementor) cfg + .buildSessionFactory( serviceRegistry )) { final EntityPersister entityPersister = factory.getRuntimeMetamodels() .getMappingMetamodel() - .getEntityDescriptor(classUnderTest.getName()); + .getEntityDescriptor( classUnderTest.getName() ); final BasicEntityIdentifierMappingImpl identifierMapping = (BasicEntityIdentifierMappingImpl) entityPersister.getIdentifierMapping(); - assertTrue( - "Field access should be used.", - identifierMapping.getPropertyAccess().getGetter() instanceof GetterFieldImpl - ); + assertThat( identifierMapping.getPropertyAccess().getGetter() ) + .describedAs( "Field access should be used." ) + .isInstanceOf( GetterFieldImpl.class ); - assertTrue( - "Property access should be used.", - entityPersister.getAttributeMapping( 0 ).getPropertyAccess().getGetter() instanceof GetterMethodImpl - ); - } - finally { - factory.close(); + assertThat( entityPersister.getAttributeMapping( 0 ).getPropertyAccess().getGetter() ) + .describedAs( "Property access should be used." ) + .isInstanceOf( GetterMethodImpl.class ); } } @@ -189,25 +160,23 @@ public void testExplicitPropertyAccessAnnotationsWithJpaStyleOverride() { Class classUnderTest = Course5.class; cfg.addAnnotatedClass( classUnderTest ); cfg.addAnnotatedClass( Student.class ); - SessionFactoryImplementor factory = (SessionFactoryImplementor) cfg.buildSessionFactory( serviceRegistry ); - try { + try (SessionFactoryImplementor factory = (SessionFactoryImplementor) cfg + .buildSessionFactory( serviceRegistry )) { final EntityPersister entityPersister = factory.getRuntimeMetamodels() .getMappingMetamodel() - .getEntityDescriptor(classUnderTest.getName()); + .getEntityDescriptor( classUnderTest.getName() ); final BasicEntityIdentifierMappingImpl identifierMapping = (BasicEntityIdentifierMappingImpl) entityPersister.getIdentifierMapping(); - assertTrue( - "Field access should be used.", - identifierMapping.getPropertyAccess().getGetter() instanceof GetterFieldImpl - ); + assertThat( - assertTrue( - "Property access should be used.", - entityPersister.getAttributeMapping( 0 ).getPropertyAccess().getGetter() instanceof GetterMethodImpl - ); - } - finally { - factory.close(); + identifierMapping.getPropertyAccess().getGetter() + ) + .describedAs( "Field access should be used." ) + .isInstanceOf( GetterFieldImpl.class ); + + assertThat( entityPersister.getAttributeMapping( 0 ).getPropertyAccess().getGetter() ) + .describedAs( "Property access should be used." ) + .isInstanceOf( GetterMethodImpl.class ); } } @@ -218,20 +187,18 @@ public void testDefaultFieldAccessIsInherited() { cfg.addAnnotatedClass( classUnderTest ); cfg.addAnnotatedClass( Person.class ); cfg.addAnnotatedClass( Being.class ); - SessionFactoryImplementor factory = (SessionFactoryImplementor) cfg.buildSessionFactory( serviceRegistry ); - try { + try (SessionFactoryImplementor factory = (SessionFactoryImplementor) cfg + .buildSessionFactory( serviceRegistry )) { final EntityPersister entityPersister = factory.getRuntimeMetamodels() .getMappingMetamodel() - .getEntityDescriptor(classUnderTest.getName()); + .getEntityDescriptor( classUnderTest.getName() ); final BasicEntityIdentifierMappingImpl identifierMapping = (BasicEntityIdentifierMappingImpl) entityPersister.getIdentifierMapping(); - assertTrue( - "Field access should be used since the default access mode gets inherited", - identifierMapping.getPropertyAccess().getGetter() instanceof GetterFieldImpl - ); - } - finally { - factory.close(); + assertThat( + identifierMapping.getPropertyAccess().getGetter() ) + .describedAs( "Field access should be used since the default access mode gets inherited" ) + .isInstanceOf( GetterFieldImpl.class ); + ; } } @@ -241,29 +208,24 @@ public void testDefaultPropertyAccessIsInherited() { cfg.addAnnotatedClass( Horse.class ); cfg.addAnnotatedClass( Animal.class ); - SessionFactoryImplementor factory = (SessionFactoryImplementor) cfg.buildSessionFactory( serviceRegistry ); - try { + try (SessionFactoryImplementor factory = (SessionFactoryImplementor) cfg + .buildSessionFactory( serviceRegistry )) { EntityPersister entityPersister = factory.getRuntimeMetamodels() .getMappingMetamodel() - .getEntityDescriptor(Animal.class.getName()); + .getEntityDescriptor( Animal.class.getName() ); final BasicEntityIdentifierMappingImpl identifierMapping = (BasicEntityIdentifierMappingImpl) entityPersister.getIdentifierMapping(); - assertTrue( - "Property access should be used since explicity configured via @Access", - identifierMapping.getPropertyAccess().getGetter() instanceof GetterMethodImpl - ); + assertThat( identifierMapping.getPropertyAccess().getGetter() ) + .describedAs( "Property access should be used since explicity configured via @Access" ) + .isInstanceOf( GetterMethodImpl.class ); entityPersister = factory.getRuntimeMetamodels() .getMappingMetamodel() - .getEntityDescriptor(Horse.class.getName()); + .getEntityDescriptor( Horse.class.getName() ); - assertTrue( - "Field access should be used since the default access mode gets inherited", - entityPersister.getAttributeMapping( 0 ).getPropertyAccess().getGetter() instanceof GetterFieldImpl - ); - } - finally { - factory.close(); + assertThat( entityPersister.getAttributeMapping( 0 ).getPropertyAccess().getGetter() ) + .describedAs( "Field access should be used since the default access mode gets inherited" ) + .isInstanceOf( GetterFieldImpl.class ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/embedded/NestedEmbeddableAttributeOverrideTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/embedded/NestedEmbeddableAttributeOverrideTest.java index ddc4257dbaeb..f4290a3ec04c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/embedded/NestedEmbeddableAttributeOverrideTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/embedded/NestedEmbeddableAttributeOverrideTest.java @@ -4,39 +4,40 @@ */ package org.hibernate.orm.test.bootstrap.binding.annotations.embedded; -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; /** * @author Brett Meyer */ -public class NestedEmbeddableAttributeOverrideTest extends BaseCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + EntityWithNestedEmbeddables.class + } +) +@SessionFactory +public class NestedEmbeddableAttributeOverrideTest { @Test - @JiraKey(value="HHH-8021") - public void testAttributeOverride() { + @JiraKey(value = "HHH-8021") + public void testAttributeOverride(SessionFactoryScope scope) { EmbeddableB embedB = new EmbeddableB(); embedB.setEmbedAttrB( "B" ); EmbeddableA embedA = new EmbeddableA(); - embedA.setEmbedAttrA("A"); - embedA.setEmbedB(embedB); + embedA.setEmbedAttrA( "A" ); + embedA.setEmbedB( embedB ); EntityWithNestedEmbeddables entity = new EntityWithNestedEmbeddables(); - entity.setEmbedA(embedA); - - Session s = openSession(); - s.beginTransaction(); - s.persist( entity ); - s.getTransaction().commit(); - s.close(); - } + entity.setEmbedA( embedA ); - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { EntityWithNestedEmbeddables.class }; + scope.inTransaction( + session -> { + session.persist( entity ); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/override/AssociationOverrideSchemaTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/override/AssociationOverrideSchemaTest.java index fa4b100b4a74..44b47b1163f8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/override/AssociationOverrideSchemaTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/override/AssociationOverrideSchemaTest.java @@ -6,53 +6,57 @@ import org.hibernate.dialect.H2Dialect; import org.hibernate.mapping.Table; - -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; import org.hibernate.orm.test.util.SchemaUtil; -import org.junit.Assert; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Lukasz Antoniak */ @RequiresDialect(H2Dialect.class) @JiraKey(value = "HHH-6662") -public class AssociationOverrideSchemaTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + Entry.class, + BlogEntry.class + } +) +@SessionFactory( + createSecondarySchemas = true +) +public class AssociationOverrideSchemaTest { + public static final String SCHEMA_NAME = "OTHER_SCHEMA"; public static final String TABLE_NAME = "BLOG_TAGS"; public static final String ID_COLUMN_NAME = "BLOG_ID"; public static final String VALUE_COLUMN_NAME = "BLOG_TAG"; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Entry.class, BlogEntry.class }; - } - - @Override - protected String createSecondSchema() { - return SCHEMA_NAME; - } @Test - public void testJoinTableSchemaName() { - for ( Table table : metadata().collectTableMappings() ) { + public void testJoinTableSchemaName(SessionFactoryScope scope) { + for ( Table table : scope.getMetadataImplementor().collectTableMappings() ) { if ( TABLE_NAME.equals( table.getName() ) ) { - Assert.assertEquals( SCHEMA_NAME, table.getSchema() ); + assertThat( table.getSchema() ).isEqualTo( SCHEMA_NAME ); return; } } - Assert.fail(); + fail("Table " + TABLE_NAME + " not found"); } @Test - public void testJoinTableJoinColumnName() { - Assert.assertTrue( SchemaUtil.isColumnPresent( TABLE_NAME, ID_COLUMN_NAME, metadata() ) ); + public void testJoinTableJoinColumnName(SessionFactoryScope scope) { + assertThat( SchemaUtil.isColumnPresent( TABLE_NAME, ID_COLUMN_NAME, scope.getMetadataImplementor() ) ).isTrue(); } @Test - public void testJoinTableColumnName() { - Assert.assertTrue( SchemaUtil.isColumnPresent( TABLE_NAME, VALUE_COLUMN_NAME, metadata() ) ); + public void testJoinTableColumnName(SessionFactoryScope scope) { + assertThat( SchemaUtil.isColumnPresent( TABLE_NAME, VALUE_COLUMN_NAME, scope.getMetadataImplementor() ) ).isTrue(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/override/AttributeOverrideTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/override/AttributeOverrideTest.java index 3fe292ec1f73..53a23c206036 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/override/AttributeOverrideTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/override/AttributeOverrideTest.java @@ -4,48 +4,52 @@ */ package org.hibernate.orm.test.bootstrap.binding.annotations.override; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; import org.hibernate.orm.test.util.SchemaUtil; -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.Test; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Emmanuel Bernard */ -public class AttributeOverrideTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + PropertyInfo.class, + PropertyRecord.class, + Address.class + } +) +@SessionFactory +public class AttributeOverrideTest { + @Test - public void testMapKeyValue() throws Exception { - assertTrue( isColumnPresent( "PropertyRecord_parcels", "ASSESSMENT") ); - assertTrue( isColumnPresent( "PropertyRecord_parcels", "SQUARE_FEET") ); - assertTrue( isColumnPresent( "PropertyRecord_parcels", "STREET_NAME") ); + public void testMapKeyValue(SessionFactoryScope scope) { + assertThatColumnIsPresent( "PropertyRecord_parcels", "ASSESSMENT", scope ); + assertThatColumnIsPresent( "PropertyRecord_parcels", "SQUARE_FEET", scope ); + assertThatColumnIsPresent( "PropertyRecord_parcels", "STREET_NAME", scope ); //legacy mappings - assertTrue( isColumnPresent( "LegacyParcels", "ASSESSMENT") ); - assertTrue( isColumnPresent( "LegacyParcels", "SQUARE_FEET") ); - assertTrue( isColumnPresent( "LegacyParcels", "STREET_NAME") ); + assertThatColumnIsPresent( "LegacyParcels", "ASSESSMENT", scope ); + assertThatColumnIsPresent( "LegacyParcels", "SQUARE_FEET", scope ); + assertThatColumnIsPresent( "LegacyParcels", "STREET_NAME", scope ); } @Test - public void testElementCollection() throws Exception { - assertTrue( isColumnPresent( "PropertyRecord_unsortedParcels", "ASSESSMENT") ); - assertTrue( isColumnPresent( "PropertyRecord_unsortedParcels", "SQUARE_FEET") ); + public void testElementCollection(SessionFactoryScope scope) { + assertThatColumnIsPresent( "PropertyRecord_unsortedParcels", "ASSESSMENT", scope ); + assertThatColumnIsPresent( "PropertyRecord_unsortedParcels", "SQUARE_FEET", scope ); //legacy mappings - assertTrue( isColumnPresent( "PropertyRecord_legacyUnsortedParcels", "ASSESSMENT") ); - assertTrue( isColumnPresent( "PropertyRecord_legacyUnsortedParcels", "SQUARE_FEET") ); + assertThatColumnIsPresent( "PropertyRecord_legacyUnsortedParcels", "ASSESSMENT", scope ); + assertThatColumnIsPresent( "PropertyRecord_legacyUnsortedParcels", "SQUARE_FEET", scope ); } - public boolean isColumnPresent(String tableName, String columnName) { - return SchemaUtil.isColumnPresent( tableName, columnName, metadata() ); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - PropertyInfo.class, - PropertyRecord.class, - Address.class - }; + public void assertThatColumnIsPresent(String tableName, String columnName, SessionFactoryScope scope) { + assertThat( SchemaUtil.isColumnPresent( tableName, columnName, scope.getMetadataImplementor() ) ) + .describedAs( "Column [" + columnName + "] is not present" ) + .isTrue(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/override/InheritedAttributeOverridingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/override/InheritedAttributeOverridingTest.java index f2d564e46d62..eb969d64465e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/override/InheritedAttributeOverridingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/override/InheritedAttributeOverridingTest.java @@ -14,25 +14,26 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.spi.MetadataImplementor; +import org.hibernate.testing.orm.junit.BaseUnitTest; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.util.ServiceRegistryUtil; -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; /** * @author Steve Ebersole */ -public class InheritedAttributeOverridingTest extends BaseUnitTestCase { +@BaseUnitTest +public class InheritedAttributeOverridingTest { private StandardServiceRegistry standardServiceRegistry; - @Before + @BeforeEach public void buildServiceRegistry() { standardServiceRegistry = ServiceRegistryUtil.serviceRegistry(); } - @After + @AfterEach public void releaseServiceRegistry() { if ( standardServiceRegistry != null ) { StandardServiceRegistryBuilder.destroy( standardServiceRegistry ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/naming/ImplicitIndexColumnNameSourceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/naming/ImplicitIndexColumnNameSourceTest.java index 578a20647489..dfa066bc230c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/naming/ImplicitIndexColumnNameSourceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/naming/ImplicitIndexColumnNameSourceTest.java @@ -6,21 +6,22 @@ import org.hibernate.boot.model.naming.ImplicitIndexColumnNameSource; import org.hibernate.boot.model.naming.ImplicitNameSource; - +import org.hibernate.testing.orm.junit.BaseUnitTest; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dmytro Bondar */ +@BaseUnitTest public class ImplicitIndexColumnNameSourceTest { @Test @JiraKey(value = "HHH-10810") public void testExtensionImplicitNameSource() { - assertTrue( ImplicitNameSource.class.isAssignableFrom( ImplicitIndexColumnNameSource.class ) ); + assertThat( ImplicitNameSource.class ).isAssignableFrom( ImplicitIndexColumnNameSource.class ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/jpa/PersistenceUnitInfoTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/jpa/PersistenceUnitInfoTests.java index 4d1133b43ac2..e6585dde4600 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/jpa/PersistenceUnitInfoTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/jpa/PersistenceUnitInfoTests.java @@ -4,39 +4,36 @@ */ package org.hibernate.orm.test.bootstrap.jpa; -import java.util.Collections; -import java.util.Map; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.spi.PersistenceProvider; -import javax.sql.DataSource; - import org.hibernate.cfg.AvailableSettings; import org.hibernate.dialect.H2Dialect; import org.hibernate.engine.jdbc.connections.internal.DataSourceConnectionProvider; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.jpa.HibernatePersistenceProvider; - -import org.hibernate.testing.RequiresDialect; import org.hibernate.testing.jdbc.DataSourceStub; - +import org.hibernate.testing.orm.junit.BaseUnitTest; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.util.jpa.PersistenceUnitInfoAdapter; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; +import javax.sql.DataSource; +import java.util.Collections; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; /** * @author Steve Ebersole */ -@RequiresDialect( H2Dialect.class ) -public class PersistenceUnitInfoTests extends BaseUnitTestCase { +@RequiresDialect(H2Dialect.class) +@BaseUnitTest +public class PersistenceUnitInfoTests { + @Test - @JiraKey( value = "HHH-13432" ) + @JiraKey(value = "HHH-13432") public void testNonJtaDataExposedAsProperty() { final DataSource puDataSource = new DataSourceStub( "puDataSource" ); final PersistenceUnitInfoAdapter info = new PersistenceUnitInfoAdapter() { @@ -49,28 +46,26 @@ public DataSource getNonJtaDataSource() { final PersistenceProvider provider = new HibernatePersistenceProvider(); - final EntityManagerFactory emf = provider.createContainerEntityManagerFactory( - info, - Collections.emptyMap() - ); - - // first let's check the DataSource used in the EMF... - final ConnectionProvider connectionProvider = emf.unwrap( SessionFactoryImplementor.class ) - .getServiceRegistry() - .getService( ConnectionProvider.class ); - assertThat( connectionProvider, instanceOf( DataSourceConnectionProvider.class ) ); - final DataSourceConnectionProvider dsCp = (DataSourceConnectionProvider) connectionProvider; - assertThat( dsCp.getDataSource(), is( puDataSource ) ); - - // now let's check that it is exposed via the EMF properties - // - note : the spec does not indicate that this should work, but - // it worked this way in previous versions - final Object o = emf.getProperties().get( AvailableSettings.JPA_NON_JTA_DATASOURCE ); - assertThat( o, is( puDataSource ) ); + try (EntityManagerFactory emf = provider.createContainerEntityManagerFactory( info, Collections.emptyMap() )) { + // first let's check the DataSource used in the EMF... + final ConnectionProvider connectionProvider = emf.unwrap( SessionFactoryImplementor.class ) + .getServiceRegistry() + .getService( ConnectionProvider.class ); + assertThat( connectionProvider ).isInstanceOf( DataSourceConnectionProvider.class ); + final DataSourceConnectionProvider dsCp = (DataSourceConnectionProvider) connectionProvider; + assertThat( dsCp ).isNotNull(); + assertThat( dsCp.getDataSource() ).isEqualTo( puDataSource ); + + // now let's check that it is exposed via the EMF properties + // - note : the spec does not indicate that this should work, but + // it worked this way in previous versions + final Object o = emf.getProperties().get( AvailableSettings.JAKARTA_NON_JTA_DATASOURCE ); + assertThat( o ).isEqualTo( puDataSource ); + } } @Test - @JiraKey( value = "HHH-13432" ) + @JiraKey(value = "HHH-13432") public void testJtaDataExposedAsProperty() { final DataSource puDataSource = new DataSourceStub( "puDataSource" ); final PersistenceUnitInfoAdapter info = new PersistenceUnitInfoAdapter() { @@ -83,24 +78,23 @@ public DataSource getJtaDataSource() { final PersistenceProvider provider = new HibernatePersistenceProvider(); - final EntityManagerFactory emf = provider.createContainerEntityManagerFactory( - info, - Collections.emptyMap() - ); - - // first let's check the DataSource used in the EMF... - final ConnectionProvider connectionProvider = emf.unwrap( SessionFactoryImplementor.class ) - .getServiceRegistry() - .getService( ConnectionProvider.class ); - assertThat( connectionProvider, instanceOf( DataSourceConnectionProvider.class ) ); - final DataSourceConnectionProvider dsCp = (DataSourceConnectionProvider) connectionProvider; - assertThat( dsCp.getDataSource(), is( puDataSource ) ); - - // now let's check that it is exposed via the EMF properties - // - again, the spec does not indicate that this should work, but - // it worked this way in previous versions - final Map properties = emf.getProperties(); - final Object o = properties.get( AvailableSettings.JPA_JTA_DATASOURCE ); - assertEquals( puDataSource, o ); + try (EntityManagerFactory emf = provider.createContainerEntityManagerFactory( info, Collections.emptyMap() )) { + + // first let's check the DataSource used in the EMF... + final ConnectionProvider connectionProvider = emf.unwrap( SessionFactoryImplementor.class ) + .getServiceRegistry() + .getService( ConnectionProvider.class ); + assertThat( connectionProvider ).isInstanceOf( DataSourceConnectionProvider.class ); + final DataSourceConnectionProvider dsCp = (DataSourceConnectionProvider) connectionProvider; + assertThat( dsCp ).isNotNull(); + assertThat( dsCp.getDataSource() ).isEqualTo( puDataSource ); + + // now let's check that it is exposed via the EMF properties + // - again, the spec does not indicate that this should work, but + // it worked this way in previous versions + final Map properties = emf.getProperties(); + final Object o = properties.get( AvailableSettings.JAKARTA_JTA_DATASOURCE ); + assertThat( o ).isEqualTo( puDataSource ); + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/jpa/PersistenceUnitOverridesTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/jpa/PersistenceUnitOverridesTests.java index 00abd23f5ae4..e7c148d768a5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/jpa/PersistenceUnitOverridesTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/jpa/PersistenceUnitOverridesTests.java @@ -4,12 +4,11 @@ */ package org.hibernate.orm.test.bootstrap.jpa; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; -import javax.sql.DataSource; - +import jakarta.persistence.Entity; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.Id; +import jakarta.persistence.spi.PersistenceProvider; +import jakarta.persistence.spi.PersistenceUnitInfo; import org.hibernate.cache.spi.access.AccessType; import org.hibernate.cfg.AvailableSettings; import org.hibernate.dialect.DatabaseVersion; @@ -22,44 +21,38 @@ import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.jpa.HibernatePersistenceProvider; import org.hibernate.persister.entity.EntityPersister; - -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.env.ConnectionProviderBuilder; import org.hibernate.testing.jdbc.DataSourceStub; -import org.hibernate.testing.junit4.BaseUnitTestCase; +import org.hibernate.testing.orm.junit.BaseUnitTest; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.util.ServiceRegistryUtil; import org.hibernate.testing.util.jpa.DelegatingPersistenceUnitInfo; import org.hibernate.testing.util.jpa.PersistenceUnitInfoAdapter; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import jakarta.persistence.Entity; -import jakarta.persistence.EntityManagerFactory; -import jakarta.persistence.Id; -import jakarta.persistence.metamodel.EntityType; -import jakarta.persistence.spi.PersistenceProvider; -import jakarta.persistence.spi.PersistenceUnitInfo; +import javax.sql.DataSource; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Steve Ebersole */ -@RequiresDialect( H2Dialect.class ) -public class PersistenceUnitOverridesTests extends BaseUnitTestCase { +@RequiresDialect(H2Dialect.class) +@BaseUnitTest +public class PersistenceUnitOverridesTests { @Test public void testPassingIntegrationJpaJdbcOverrides() { // the integration overrides say to use the "db2" JPA connection settings (which should override the persistence unit values) - final Map integrationOverrides = ConnectionProviderBuilder.getJpaConnectionProviderProperties( "db2" ); + final Properties integrationOverrides = ConnectionProviderBuilder.getJpaConnectionProviderProperties( "db2" ); - final EntityManagerFactory emf = new HibernatePersistenceProvider().createContainerEntityManagerFactory( + try (final EntityManagerFactory emf = new HibernatePersistenceProvider().createContainerEntityManagerFactory( new PersistenceUnitInfoAdapter() { @Override public Properties getProperties() { @@ -67,20 +60,15 @@ public Properties getProperties() { return ConnectionProviderBuilder.getJpaConnectionProviderProperties( "db1" ); } }, - integrationOverrides - ); + integrationOverrides )) { - try { final Map properties = emf.getProperties(); - final Object hibernateJdbcDriver = properties.get( AvailableSettings.URL ); - assertThat( hibernateJdbcDriver, notNullValue() ); + final Object hibernateJdbcDriver = properties.get( AvailableSettings.JAKARTA_JDBC_URL ); + assertThat( hibernateJdbcDriver ).isNotNull(); - final Object jpaJdbcDriver = properties.get( AvailableSettings.JPA_JDBC_URL ); - assertThat( (String) jpaJdbcDriver, containsString( "db2" ) ); - } - finally { - emf.close(); + final Object jpaJdbcDriver = properties.get( AvailableSettings.JAKARTA_JDBC_URL ); + assertThat( (String) jpaJdbcDriver ).contains( "db2" ); } } @@ -96,36 +84,34 @@ public void testPassingIntegrationJtaDataSourceOverrideForJpaJdbcSettings() { // todo (6.0) : fix for Oracle see HHH-13432 // puInfo.getProperties().setProperty( AvailableSettings.HQL_BULK_ID_STRATEGY, MultiTableBulkIdStrategyStub.class.getName() ); - final EntityManagerFactory emf = provider.createContainerEntityManagerFactory( + try (final EntityManagerFactory emf = provider.createContainerEntityManagerFactory( puInfo, - Collections.singletonMap( AvailableSettings.JPA_JTA_DATASOURCE, integrationDataSource ) - ); + Collections.singletonMap( AvailableSettings.JAKARTA_JTA_DATASOURCE, integrationDataSource ) + )) { + - try { // first let's check the DataSource used in the EMF... final ConnectionProvider connectionProvider = emf.unwrap( SessionFactoryImplementor.class ) .getServiceRegistry() .getService( ConnectionProvider.class ); - assertThat( connectionProvider, instanceOf( DataSourceConnectionProvider.class ) ); + assertThat( connectionProvider ).isInstanceOf( DataSourceConnectionProvider.class ); final DataSourceConnectionProvider dsCp = (DataSourceConnectionProvider) connectionProvider; - assertThat( dsCp.getDataSource(), is( integrationDataSource ) ); + assertThat( dsCp ).isNotNull(); + assertThat( dsCp.getDataSource() ).isEqualTo( integrationDataSource ); // now let's check that it is exposed via the EMF properties // - note : the spec does not indicate that this should work, but // it worked this way in previous versions final Object jtaDs = emf.getProperties().get( AvailableSettings.JPA_JTA_DATASOURCE ); - assertThat( jtaDs, is( integrationDataSource ) ); + assertThat( jtaDs ).isEqualTo( integrationDataSource ); // Additionally, we should have set Hibernate's DATASOURCE setting final Object hibDs = emf.getProperties().get( AvailableSettings.JPA_JTA_DATASOURCE ); - assertThat( hibDs, is( integrationDataSource ) ); + assertThat( hibDs ).isEqualTo( integrationDataSource ); // Make sure the non-jta-data-source setting was cleared or otherwise null - final Object nonJtaDs = emf.getProperties().get( AvailableSettings.JPA_NON_JTA_DATASOURCE ); - assertThat( nonJtaDs, nullValue() ); - } - finally { - emf.close(); + final Object nonJtaDs = emf.getProperties().get( AvailableSettings.JAKARTA_NON_JTA_DATASOURCE ); + assertThat( nonJtaDs ).isNull(); } } @@ -169,31 +155,26 @@ public Properties getProperties() { } }; - final EntityManagerFactory emf = provider.createContainerEntityManagerFactory( + try (final EntityManagerFactory emf = provider.createContainerEntityManagerFactory( new PersistenceUnitInfoAdapter(), // however, provide JPA connection settings as "integration settings", which according to JPA spec should override the persistence unit values. // - note that it is unclear in the spec whether JDBC value in the integration settings should override // a JTA DataSource (nor the reverse). However, that is a useful thing to support ConnectionProviderBuilder.getJpaConnectionProviderProperties( "db2" ) - ); - - try { + )) { final Map properties = emf.getProperties(); final Object hibernateJdbcDriver = properties.get( AvailableSettings.URL ); - assertThat( hibernateJdbcDriver, notNullValue() ); + assertThat( hibernateJdbcDriver ).isNotNull(); final Object jpaJdbcDriver = properties.get( AvailableSettings.JPA_JDBC_URL ); - assertThat( (String) jpaJdbcDriver, containsString( "db2" ) ); + assertThat( (String) jpaJdbcDriver ).contains( "db2" ); // see if the values had the affect to adjust the `ConnectionProvider` used final ConnectionProvider connectionProvider = emf.unwrap( SessionFactoryImplementor.class ) .getServiceRegistry() .getService( ConnectionProvider.class ); - assertThat( connectionProvider, instanceOf( DriverManagerConnectionProvider.class ) ); - } - finally { - emf.close(); + assertThat( connectionProvider ).isInstanceOf( DriverManagerConnectionProvider.class ); } } @@ -222,31 +203,27 @@ public DataSource getJtaDataSource() { } }; - final EntityManagerFactory emf = provider.createContainerEntityManagerFactory( + try (final EntityManagerFactory emf = provider.createContainerEntityManagerFactory( new PersistenceUnitInfoAdapter(), // however, provide JPA connection settings as "integration settings", which according to JPA spec should override the persistence unit values. // - note that it is unclear in the spec whether JDBC value in the integration settings should override // a JTA DataSource (nor the reverse). However, that is a useful thing to support ConnectionProviderBuilder.getJpaConnectionProviderProperties( "db2" ) - ); + )) { - try { final Map properties = emf.getProperties(); final Object hibernateJdbcDriver = properties.get( AvailableSettings.URL ); - assertThat( hibernateJdbcDriver, notNullValue() ); + assertThat( hibernateJdbcDriver ).isNotNull(); final Object jpaJdbcDriver = properties.get( AvailableSettings.JPA_JDBC_URL ); - assertThat( (String) jpaJdbcDriver, containsString( "db2" ) ); + assertThat( (String) jpaJdbcDriver ).contains( "db2" ); // see if the values had the affect to adjust the `ConnectionProvider` used final ConnectionProvider connectionProvider = emf.unwrap( SessionFactoryImplementor.class ) .getServiceRegistry() .getService( ConnectionProvider.class ); - assertThat( connectionProvider, instanceOf( DriverManagerConnectionProvider.class ) ); - } - finally { - emf.close(); + assertThat( connectionProvider ).isInstanceOf( DriverManagerConnectionProvider.class ); } } @@ -277,39 +254,35 @@ public DataSource getJtaDataSource() { } }; - final Map integrationOverrides = new HashMap(); + final Map integrationOverrides = new HashMap<>(); //noinspection unchecked integrationOverrides.put( AvailableSettings.JPA_JTA_DATASOURCE, integrationDataSource ); // todo (6.0) : fix for Oracle see HHH-13432 // integrationOverrides.put( AvailableSettings.HQL_BULK_ID_STRATEGY, new MultiTableBulkIdStrategyStub() ); - final EntityManagerFactory emf = provider.createContainerEntityManagerFactory( + try (final EntityManagerFactory emf = provider.createContainerEntityManagerFactory( new PersistenceUnitInfoAdapter(), integrationOverrides - ); - - try { + )) { final Map properties = emf.getProperties(); final Object datasource = properties.get( AvailableSettings.JPA_JTA_DATASOURCE ); - assertThat( datasource, is( integrationDataSource ) ); + assertThat( datasource ).isEqualTo( integrationDataSource ); // see if the values had the affect to adjust the `ConnectionProvider` used final ConnectionProvider connectionProvider = emf.unwrap( SessionFactoryImplementor.class ) .getServiceRegistry() .getService( ConnectionProvider.class ); - assertThat( connectionProvider, instanceOf( DataSourceConnectionProvider.class ) ); + assertThat( connectionProvider ).isInstanceOf( DataSourceConnectionProvider.class ); final DataSourceConnectionProvider datasourceConnectionProvider = (DataSourceConnectionProvider) connectionProvider; - assertThat( datasourceConnectionProvider.getDataSource(), is( integrationDataSource ) ); - } - finally { - emf.close(); + assertThat( datasourceConnectionProvider ).isNotNull(); + assertThat( datasourceConnectionProvider.getDataSource() ).isEqualTo( integrationDataSource ); } } @Test - @JiraKey( value = "HHH-13640" ) + @JiraKey(value = "HHH-13640") public void testIntegrationOverridesOfPersistenceXmlDataSource() { // mimics a DataSource defined in the persistence.xml @@ -325,38 +298,32 @@ public DataSource getNonJtaDataSource() { // Now create "integration Map" that overrides the DataSource to use final DataSource override = new DataSourceStub( "integrationDataSource" ); - final Map integrationSettings = new HashMap<>(); + final Map integrationSettings = new HashMap<>(); integrationSettings.put( AvailableSettings.JPA_NON_JTA_DATASOURCE, override ); // todo (6.0) : fix for Oracle see HHH-13432 // integrationSettings.put( AvailableSettings.HQL_BULK_ID_STRATEGY, new MultiTableBulkIdStrategyStub() ); final PersistenceProvider provider = new HibernatePersistenceProvider(); - final EntityManagerFactory emf = provider.createContainerEntityManagerFactory( - info, - integrationSettings - ); - - try { + try (final EntityManagerFactory emf = provider.createContainerEntityManagerFactory( info, + integrationSettings )) { final Map properties = emf.getProperties(); - assertThat( properties.get( AvailableSettings.JPA_NON_JTA_DATASOURCE ), notNullValue() ); - assertThat( properties.get( AvailableSettings.JPA_NON_JTA_DATASOURCE ), is( override ) ); + assertThat( properties.get( AvailableSettings.JPA_NON_JTA_DATASOURCE ) ).isNotNull(); + assertThat( properties.get( AvailableSettings.JPA_NON_JTA_DATASOURCE ) ).isEqualTo( override ); final SessionFactoryImplementor sessionFactory = emf.unwrap( SessionFactoryImplementor.class ); - final ConnectionProvider connectionProvider = sessionFactory.getServiceRegistry().getService( ConnectionProvider.class ); - assertThat( connectionProvider, instanceOf( DataSourceConnectionProvider.class ) ); + final ConnectionProvider connectionProvider = sessionFactory.getServiceRegistry() + .getService( ConnectionProvider.class ); + assertThat( connectionProvider ).isInstanceOf( DataSourceConnectionProvider.class ); final DataSourceConnectionProvider dsProvider = (DataSourceConnectionProvider) connectionProvider; - assertThat( dsProvider.getDataSource(), is( override ) ); - } - finally { - emf.close(); + assertThat( dsProvider.getDataSource() ).isEqualTo( override ); } } @Test - @JiraKey( value = "HHH-13640" ) + @JiraKey(value = "HHH-13640") public void testIntegrationOverridesOfPersistenceXmlDataSourceWithDriverManagerInfo() { // mimics a DataSource defined in the persistence.xml @@ -369,7 +336,7 @@ public DataSource getNonJtaDataSource() { } }; - final Map integrationSettings = ServiceRegistryUtil.createBaseSettings(); + final Map integrationSettings = ServiceRegistryUtil.createBaseSettings(); integrationSettings.put( AvailableSettings.JPA_JDBC_DRIVER, ConnectionProviderBuilder.DRIVER ); integrationSettings.put( AvailableSettings.JPA_JDBC_URL, ConnectionProviderBuilder.URL ); integrationSettings.put( AvailableSettings.JPA_JDBC_USER, ConnectionProviderBuilder.USER ); @@ -378,24 +345,19 @@ public DataSource getNonJtaDataSource() { final PersistenceProvider provider = new HibernatePersistenceProvider(); - final EntityManagerFactory emf = provider.createContainerEntityManagerFactory( + try (final EntityManagerFactory emf = provider.createContainerEntityManagerFactory( info, integrationSettings - ); - - try { + )) { final SessionFactoryImplementor sessionFactory = emf.unwrap( SessionFactoryImplementor.class ); final ConnectionProvider connectionProvider = sessionFactory.getServiceRegistry().getService( ConnectionProvider.class ); - assertThat( connectionProvider, instanceOf( DriverManagerConnectionProvider.class ) ); - } - finally { - emf.close(); + assertThat( connectionProvider ).isInstanceOf( DriverManagerConnectionProvider.class ); } } @Test - @JiraKey( value = "HHH-13640" ) + @JiraKey(value = "HHH-13640") public void testIntegrationOverridesOfPersistenceXmlDataSourceWithDriverManagerInfoUsingJakarta() { // mimics a DataSource defined in the persistence.xml @@ -408,7 +370,7 @@ public DataSource getNonJtaDataSource() { } }; - final Map integrationSettings = ServiceRegistryUtil.createBaseSettings(); + final Map integrationSettings = ServiceRegistryUtil.createBaseSettings(); integrationSettings.put( AvailableSettings.JAKARTA_JDBC_DRIVER, ConnectionProviderBuilder.DRIVER ); integrationSettings.put( AvailableSettings.JAKARTA_JDBC_URL, ConnectionProviderBuilder.URL ); integrationSettings.put( AvailableSettings.JAKARTA_JDBC_USER, ConnectionProviderBuilder.USER ); @@ -417,19 +379,14 @@ public DataSource getNonJtaDataSource() { final PersistenceProvider provider = new HibernatePersistenceProvider(); - final EntityManagerFactory emf = provider.createContainerEntityManagerFactory( + try (final EntityManagerFactory emf = provider.createContainerEntityManagerFactory( info, integrationSettings - ); - - try { + )) { final SessionFactoryImplementor sessionFactory = emf.unwrap( SessionFactoryImplementor.class ); final ConnectionProvider connectionProvider = sessionFactory.getServiceRegistry().getService( ConnectionProvider.class ); - assertThat( connectionProvider, instanceOf( DriverManagerConnectionProvider.class ) ); - } - finally { - emf.close(); + assertThat( connectionProvider ).isInstanceOf( DriverManagerConnectionProvider.class ); } } @@ -437,6 +394,7 @@ public DataSource getNonJtaDataSource() { public void testCfgXmlBaseline() { final PersistenceUnitInfoAdapter info = new PersistenceUnitInfoAdapter() { private final Properties props = new Properties(); + { props.put( AvailableSettings.CFG_XML_FILE, "org/hibernate/orm/test/bootstrap/jpa/hibernate.cfg.xml" ); } @@ -449,28 +407,20 @@ public Properties getProperties() { final PersistenceProvider provider = new HibernatePersistenceProvider(); - final Map integrationSettings = ServiceRegistryUtil.createBaseSettings(); + final Map integrationSettings = ServiceRegistryUtil.createBaseSettings(); - final EntityManagerFactory emf = provider.createContainerEntityManagerFactory( + try (final EntityManagerFactory emf = provider.createContainerEntityManagerFactory( info, integrationSettings - ); + )) { + assertThat( emf.getProperties().get( AvailableSettings.DIALECT ) ) + .isEqualTo( PersistenceUnitDialect.class.getName() ); - try { - assertThat( - emf.getProperties().get( AvailableSettings.DIALECT ), - is( PersistenceUnitDialect.class.getName() ) - ); - assertThat( - emf.unwrap( SessionFactoryImplementor.class ).getJdbcServices().getDialect(), - instanceOf( PersistenceUnitDialect.class ) - ); - - final EntityType entityMapping = emf.getMetamodel().entity( MappedEntity.class ); - assertThat( entityMapping, notNullValue() ); - } - finally { - emf.close(); + assertThat( emf.unwrap( SessionFactoryImplementor.class ).getJdbcServices().getDialect() ) + .isInstanceOf( PersistenceUnitDialect.class ); + + assertThat( emf.getMetamodel().entity( MappedEntity.class ) ) + .isNotNull(); } } @@ -478,6 +428,7 @@ public Properties getProperties() { public void testIntegrationOverridesOfCfgXml() { final PersistenceUnitInfoAdapter info = new PersistenceUnitInfoAdapter() { private final Properties props = new Properties(); + { props.put( AvailableSettings.CFG_XML_FILE, "org/hibernate/orm/test/bootstrap/jpa/hibernate.cfg.xml" ); } @@ -493,33 +444,23 @@ public Properties getProperties() { final Map integrationSettings = ServiceRegistryUtil.createBaseSettings(); integrationSettings.put( AvailableSettings.DIALECT, IntegrationDialect.class.getName() ); - final EntityManagerFactory emf = provider.createContainerEntityManagerFactory( + try (final EntityManagerFactory emf = provider.createContainerEntityManagerFactory( info, integrationSettings - ); + )) { + assertThat( emf.getProperties().get( AvailableSettings.DIALECT ) ) + .isEqualTo( IntegrationDialect.class.getName() ); - try { - assertThat( - emf.getProperties().get( AvailableSettings.DIALECT ), - is( IntegrationDialect.class.getName() ) - ); - assertThat( - emf.unwrap( SessionFactoryImplementor.class ).getJdbcServices().getDialect(), - instanceOf( IntegrationDialect.class ) - ); + assertThat( emf.unwrap( SessionFactoryImplementor.class ).getJdbcServices().getDialect() ) + .isInstanceOf( IntegrationDialect.class ); final EntityPersister entityMapping = emf.unwrap( SessionFactoryImplementor.class ) .getRuntimeMetamodels() .getMappingMetamodel() .getEntityDescriptor( MappedEntity.class ); - assertThat( entityMapping, notNullValue() ); - assertThat( - entityMapping.getCacheAccessStrategy().getAccessType(), - is( AccessType.READ_ONLY ) - ); - } - finally { - emf.close(); + assertThat( entityMapping ).isNotNull(); + assertThat( entityMapping.getCacheAccessStrategy().getAccessType() ) + .isEqualTo( AccessType.READ_ONLY ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/registry/classloading/HibernateClassLoaderLeaksTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/registry/classloading/HibernateClassLoaderLeaksTest.java index 0a13223ae872..dc0b2e34ace9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/registry/classloading/HibernateClassLoaderLeaksTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/registry/classloading/HibernateClassLoaderLeaksTest.java @@ -16,6 +16,7 @@ import org.junit.Assert; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; /** @@ -25,6 +26,7 @@ * it's best to focus on a single DB. */ @RequiresDialect(H2Dialect.class) +@Disabled public class HibernateClassLoaderLeaksTest { private static Set knownDrivers; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/registry/classloading/LeakUtilitySelfTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/registry/classloading/LeakUtilitySelfTest.java index c9fc8ef3a024..a34dbd0cf259 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/registry/classloading/LeakUtilitySelfTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/registry/classloading/LeakUtilitySelfTest.java @@ -4,12 +4,15 @@ */ package org.hibernate.orm.test.bootstrap.registry.classloading; -import org.junit.Assert; -import org.junit.Test; +import org.hibernate.testing.orm.junit.BaseUnitTest; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; /** * Tests the testing utility PhantomReferenceLeakDetector */ +@BaseUnitTest public class LeakUtilitySelfTest { @Test @@ -19,7 +22,8 @@ public void verifyLeakUtility() { @Test public void verifyLeakUtilitySpotsLeak() { - Assert.assertFalse( PhantomReferenceLeakDetector.verifyActionNotLeaking( LeakUtilitySelfTest::troubleSomeLeak, 2, 1 ) ); + assertThat( PhantomReferenceLeakDetector.verifyActionNotLeaking( LeakUtilitySelfTest::troubleSomeLeak, 2, 1 ) ) + .isFalse(); } private static SomeSpecialObject notALeak() { @@ -32,7 +36,7 @@ private static SomeSpecialObject troubleSomeLeak() { return specialThing; } - private static final ThreadLocal tl = new ThreadLocal<>(); + private static final ThreadLocal tl = new ThreadLocal<>(); static class SomeSpecialObject { @Override diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/schema/SchemaToolingAutoActionTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/schema/SchemaToolingAutoActionTests.java index 047bb5debe66..931295afdde6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/schema/SchemaToolingAutoActionTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/schema/SchemaToolingAutoActionTests.java @@ -4,21 +4,22 @@ */ package org.hibernate.orm.test.bootstrap.schema; -import java.util.Properties; - import org.hibernate.cfg.AvailableSettings; +import org.hibernate.testing.orm.junit.BaseUnitTest; import org.hibernate.tool.schema.Action; import org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.ActionGrouping; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import java.util.Properties; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Steve Ebersole */ +@BaseUnitTest public class SchemaToolingAutoActionTests { + @Test public void testLegacySettingAsAction() { final Properties props = new Properties(); @@ -26,7 +27,7 @@ public void testLegacySettingAsAction() { final ActionGrouping actionGrouping = ActionGrouping.interpret( props ); - assertThat( actionGrouping.databaseAction(), is( Action.CREATE_DROP ) ); + assertThat( actionGrouping.databaseAction() ).isEqualTo( Action.CREATE_DROP ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/AbstractSqlFunctionMetadataBuilderContributorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/AbstractSqlFunctionMetadataBuilderContributorTest.java index ac9f6c227da7..83d54408c035 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/AbstractSqlFunctionMetadataBuilderContributorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/AbstractSqlFunctionMetadataBuilderContributorTest.java @@ -4,36 +4,34 @@ */ package org.hibernate.orm.test.bootstrap.spi.metadatabuildercontributor; -import java.util.Map; import jakarta.persistence.Entity; import jakarta.persistence.Id; - import org.hibernate.annotations.NaturalId; import org.hibernate.dialect.H2Dialect; import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryBasedFunctionalTest; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; +import java.util.Map; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Vlad Mihalcea */ @RequiresDialect(H2Dialect.class) -@JiraKey( value = "HHH-12589" ) -public abstract class AbstractSqlFunctionMetadataBuilderContributorTest extends BaseEntityManagerFunctionalTestCase { +public abstract class AbstractSqlFunctionMetadataBuilderContributorTest + extends EntityManagerFactoryBasedFunctionalTest { @Override protected Class[] getAnnotatedClasses() { return new Class[] { - Employee.class, + Employee.class, }; } + @Override protected void addConfigOptions(Map options) { options.put( @@ -46,28 +44,25 @@ protected void addConfigOptions(Map options) { final Employee employee = new Employee(); - @Override - protected void afterEntityManagerFactoryBuilt() { - doInJPA( this::entityManagerFactory, entityManager -> { + @Test + public void test() { + inTransaction( entityManager -> { employee.id = 1L; employee.username = "user@acme.com"; entityManager.persist( employee ); } ); - } - @Test - public void test() { - doInJPA( this::entityManagerFactory, entityManager -> { + inTransaction( entityManager -> { int result = entityManager.createQuery( - "select INSTR(e.username,'@acme.com') " + - "from Employee e " + - "where " + - " e.id = :employeeId", Integer.class ) - .setParameter( "employeeId", employee.id ) - .getSingleResult(); - - assertEquals( 5, result ); + "select INSTR(e.username,'@acme.com') " + + "from Employee e " + + "where " + + " e.id = :employeeId", Integer.class ) + .setParameter( "employeeId", employee.id ) + .getSingleResult(); + + assertThat( result ).isEqualTo( 5 ); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/AttributeConverterMetadataBuilderContributorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/AttributeConverterMetadataBuilderContributorTest.java index 347cab7e48ea..50cbc2809d18 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/AttributeConverterMetadataBuilderContributorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/AttributeConverterMetadataBuilderContributorTest.java @@ -4,41 +4,48 @@ */ package org.hibernate.orm.test.bootstrap.spi.metadatabuildercontributor; -import java.time.YearMonth; -import java.util.Map; import jakarta.persistence.AttributeConverter; import jakarta.persistence.Column; import jakarta.persistence.Converter; import jakarta.persistence.Entity; import jakarta.persistence.Id; - import org.hibernate.annotations.NaturalId; import org.hibernate.boot.spi.MetadataBuilderContributor; import org.hibernate.dialect.H2Dialect; import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.EntityManagerFactoryBasedFunctionalTest; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.SettingProvider; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.YearMonth; +import java.util.Map; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Vlad Mihalcea */ @RequiresDialect(H2Dialect.class) -@JiraKey( value = "HHH-13040" ) -public class AttributeConverterMetadataBuilderContributorTest extends BaseEntityManagerFunctionalTestCase { +@JiraKey(value = "HHH-13040") +public class AttributeConverterMetadataBuilderContributorTest extends EntityManagerFactoryBasedFunctionalTest { @Override protected Class[] getAnnotatedClasses() { return new Class[] { - Employee.class, + Employee.class, }; } + public static class MetadataBuilderProvider implements SettingProvider.Provider { + @Override + public Object getSetting() { + return null; + } + } + @Override protected void addConfigOptions(Map options) { options.put( @@ -50,9 +57,9 @@ protected void addConfigOptions(Map options) { final Employee employee = new Employee(); - @Override - protected void afterEntityManagerFactoryBuilt() { - doInJPA( this::entityManagerFactory, entityManager -> { + @BeforeEach + protected void setUp() { + inTransaction( entityManager -> { employee.id = 1L; employee.username = "user@acme.com"; employee.nextVacation = YearMonth.of( 2018, 12 ); @@ -63,10 +70,10 @@ protected void afterEntityManagerFactoryBuilt() { @Test public void test() { - doInJPA( this::entityManagerFactory, entityManager -> { - Employee employee = entityManager.find(Employee.class, 1L); + inTransaction( entityManager -> { + Employee employee = entityManager.find( Employee.class, 1L ); - assertEquals( YearMonth.of( 2018, 12 ), employee.nextVacation ); + assertThat( employee.nextVacation ).isEqualTo( YearMonth.of( 2018, 12 ) ); } ); } @@ -94,7 +101,7 @@ public Integer convertToDatabaseColumn(YearMonth attribute) { @Override public YearMonth convertToEntityAttribute(Integer dbData) { - return YearMonth.of(dbData / 100, dbData % 100); + return YearMonth.of( dbData / 100, dbData % 100 ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/SqlFunctionMetadataBuilderContributorClassNameTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/SqlFunctionMetadataBuilderContributorClassNameTest.java index 716afc48059e..eb658205d754 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/SqlFunctionMetadataBuilderContributorClassNameTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/SqlFunctionMetadataBuilderContributorClassNameTest.java @@ -5,15 +5,14 @@ package org.hibernate.orm.test.bootstrap.spi.metadatabuildercontributor; import org.hibernate.dialect.H2Dialect; - -import org.hibernate.testing.RequiresDialect; import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialect; /** * @author Vlad Mihalcea */ @RequiresDialect(H2Dialect.class) -@JiraKey( value = "HHH-12589" ) +@JiraKey(value = "HHH-12589") public class SqlFunctionMetadataBuilderContributorClassNameTest extends AbstractSqlFunctionMetadataBuilderContributorTest { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/SqlFunctionMetadataBuilderContributorClassTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/SqlFunctionMetadataBuilderContributorClassTest.java index 96c56564a457..cfefcf55cf07 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/SqlFunctionMetadataBuilderContributorClassTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/SqlFunctionMetadataBuilderContributorClassTest.java @@ -5,16 +5,15 @@ package org.hibernate.orm.test.bootstrap.spi.metadatabuildercontributor; import org.hibernate.dialect.H2Dialect; - -import org.hibernate.testing.RequiresDialect; import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialect; /** * @author Vlad Mihalcea */ @RequiresDialect(H2Dialect.class) -@JiraKey( value = "HHH-12589" ) +@JiraKey(value = "HHH-12589") public class SqlFunctionMetadataBuilderContributorClassTest extends AbstractSqlFunctionMetadataBuilderContributorTest { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/SqlFunctionMetadataBuilderContributorIllegalArgumentTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/SqlFunctionMetadataBuilderContributorIllegalArgumentTest.java index 912f214a52ed..9bf2df9617ab 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/SqlFunctionMetadataBuilderContributorIllegalArgumentTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/SqlFunctionMetadataBuilderContributorIllegalArgumentTest.java @@ -4,19 +4,21 @@ */ package org.hibernate.orm.test.bootstrap.spi.metadatabuildercontributor; +import jakarta.persistence.EntityManagerFactory; import org.hibernate.dialect.H2Dialect; - -import org.hibernate.testing.RequiresDialect; import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.fail; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author Vlad Mihalcea */ @RequiresDialect(H2Dialect.class) -@JiraKey( value = "HHH-12589" ) +@JiraKey(value = "HHH-12589") public class SqlFunctionMetadataBuilderContributorIllegalArgumentTest extends AbstractSqlFunctionMetadataBuilderContributorTest { @@ -26,23 +28,25 @@ protected Object matadataBuilderContributor() { } @Override - public void buildEntityManagerFactory() { + public EntityManagerFactory produceEntityManagerFactory() { + EntityManagerFactory entityManagerFactory = null; try { - super.buildEntityManagerFactory(); - - fail("Should throw exception!"); + entityManagerFactory = super.produceEntityManagerFactory(); + fail( "Should throw exception!" ); } catch (IllegalArgumentException e) { - assertTrue( e.getMessage().startsWith( "The provided hibernate.metadata_builder_contributor setting value" ) ); + assertThat( e.getMessage() ).startsWith( + "The provided hibernate.metadata_builder_contributor setting value" ); } + return entityManagerFactory; } @Override + @Test public void test() { try { super.test(); - - fail("Should throw exception!"); + fail( "Should throw exception!" ); } catch (Exception expected) { } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/SqlFunctionMetadataBuilderContributorIllegalClassArgumentTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/SqlFunctionMetadataBuilderContributorIllegalClassArgumentTest.java index 27cd8ff784a9..27fef27acad9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/SqlFunctionMetadataBuilderContributorIllegalClassArgumentTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/SqlFunctionMetadataBuilderContributorIllegalClassArgumentTest.java @@ -4,22 +4,21 @@ */ package org.hibernate.orm.test.bootstrap.spi.metadatabuildercontributor; +import jakarta.persistence.EntityManagerFactory; import org.hibernate.dialect.H2Dialect; - -import org.hibernate.testing.RequiresDialect; import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.junit.jupiter.api.Test; -import org.hamcrest.Matchers; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.fail; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.fail; /** * @author Vlad Mihalcea */ @RequiresDialect(H2Dialect.class) -@JiraKey( value = "HHH-12589" ) +@JiraKey(value = "HHH-12589") public class SqlFunctionMetadataBuilderContributorIllegalClassArgumentTest extends AbstractSqlFunctionMetadataBuilderContributorTest { @@ -29,32 +28,27 @@ protected Object matadataBuilderContributor() { } @Override - public void buildEntityManagerFactory() { + public EntityManagerFactory produceEntityManagerFactory() { + EntityManagerFactory entityManagerFactory = null; try { - super.buildEntityManagerFactory(); - - fail("Should throw exception!"); + entityManagerFactory = super.produceEntityManagerFactory(); + fail( "Should throw exception!" ); } catch (ClassCastException e) { - System.out.println( "Checking exception : " + e.getMessage() ); - - assertThat( - e.getMessage(), - // depends on the JDK used - Matchers.anyOf( - containsString( "cannot be cast to" ), - containsString( "incompatible with" ) - ) - ); + assertThat( e.getMessage() ) + .containsAnyOf( + "cannot be cast to", + "incompatible with" ); } + return entityManagerFactory; } @Override + @Test public void test() { try { super.test(); - - fail("Should throw exception!"); + fail( "Should throw exception!" ); } catch (Exception expected) { } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/SqlFunctionMetadataBuilderContributorInstanceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/SqlFunctionMetadataBuilderContributorInstanceTest.java index f94c28103ca8..6204253ac16f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/SqlFunctionMetadataBuilderContributorInstanceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/SqlFunctionMetadataBuilderContributorInstanceTest.java @@ -5,7 +5,6 @@ package org.hibernate.orm.test.bootstrap.spi.metadatabuildercontributor; import org.hibernate.dialect.H2Dialect; - import org.hibernate.testing.RequiresDialect; import org.hibernate.testing.orm.junit.JiraKey; @@ -13,7 +12,7 @@ * @author Vlad Mihalcea */ @RequiresDialect(H2Dialect.class) -@JiraKey( value = "HHH-12589" ) +@JiraKey(value = "HHH-12589") public class SqlFunctionMetadataBuilderContributorInstanceTest extends AbstractSqlFunctionMetadataBuilderContributorTest { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/AbstractMutationStrategyCompositeIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/AbstractMutationStrategyCompositeIdTest.java index 95fd07ff4aa2..c52fc0a25ba2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/AbstractMutationStrategyCompositeIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/AbstractMutationStrategyCompositeIdTest.java @@ -4,76 +4,44 @@ */ package org.hibernate.orm.test.bulkid; -import java.io.Serializable; -import java.util.Objects; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Inheritance; import jakarta.persistence.InheritanceType; +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 org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableMutationStrategy; +import java.io.Serializable; +import java.util.Objects; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Before; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; -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.assertTrue; /** * @author Vlad Mihalcea */ -public abstract class AbstractMutationStrategyCompositeIdTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Doctor.class, - Engineer.class - }; - } - - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - Class mutationStrategyClass = getMultiTableMutationStrategyClass(); - if ( mutationStrategyClass != null ) { - configuration.setProperty( AvailableSettings.QUERY_MULTI_TABLE_MUTATION_STRATEGY, mutationStrategyClass ); +@DomainModel( + annotatedClasses = { + AbstractMutationStrategyCompositeIdTest.Person.class, + AbstractMutationStrategyCompositeIdTest.Doctor.class, + AbstractMutationStrategyCompositeIdTest.Engineer.class } - Class insertStrategyClass = getMultiTableInsertStrategyClass(); - if ( insertStrategyClass != null ) { - configuration.setProperty( AvailableSettings.QUERY_MULTI_TABLE_INSERT_STRATEGY, insertStrategyClass ); - } - } - - protected abstract Class getMultiTableMutationStrategyClass(); - - protected abstract Class getMultiTableInsertStrategyClass(); - - @Override - protected boolean isCleanupTestDataRequired() { - return true; - } - - @Override - protected boolean isCleanupTestDataUsingBulkDelete() { - return true; - } +) +@SessionFactory +public abstract class AbstractMutationStrategyCompositeIdTest { - @Before - public void setUp() { - doInHibernate( this::sessionFactory, session -> { + @BeforeEach + public void setUp(SessionFactoryScope scope) { + scope.inTransaction( session -> { for ( int i = 0; i < entityCount(); i++ ) { Doctor doctor = new Doctor(); doctor.setId( i + 1 ); doctor.setCompanyName( "Red Hat USA" ); - doctor.setEmployed( ( i % 2 ) == 0 ); + doctor.setEmployed( (i % 2) == 0 ); session.persist( doctor ); } @@ -81,11 +49,16 @@ public void setUp() { Engineer engineer = new Engineer(); engineer.setId( i + 1 + entityCount() ); engineer.setCompanyName( "Red Hat Europe" ); - engineer.setEmployed( ( i % 2 ) == 0 ); - engineer.setFellow( ( i % 2 ) == 1 ); + engineer.setEmployed( (i % 2) == 0 ); + engineer.setFellow( (i % 2) == 1 ); session.persist( engineer ); } - }); + } ); + } + + @AfterEach + public void tearDown(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } protected int entityCount() { @@ -93,68 +66,71 @@ protected int entityCount() { } @Test - public void testUpdate() { - doInHibernate( this::sessionFactory, session -> { - int updateCount = session.createQuery( "update Person set name = :name where employed = :employed" ) + public void testUpdate(SessionFactoryScope scope) { + scope.inTransaction( session -> { + int updateCount = session.createMutationQuery( "update Person set name = :name where employed = :employed" ) .setParameter( "name", "John Doe" ) .setParameter( "employed", true ) .executeUpdate(); - assertEquals(entityCount(), updateCount); - }); + assertThat( updateCount ).isEqualTo( entityCount() ); + } ); } @Test - public void testDeleteFromPerson() { - doInHibernate( this::sessionFactory, session -> { + public void testDeleteFromPerson(SessionFactoryScope scope) { + scope.inTransaction( session -> { //tag::batch-bulk-hql-temp-table-delete-query-example[] - int updateCount = session.createQuery( - "delete from Person where employed = :employed" ) - .setParameter( "employed", false ) - .executeUpdate(); + int updateCount = session.createMutationQuery( + "delete from Person where employed = :employed" ) + .setParameter( "employed", false ) + .executeUpdate(); //end::batch-bulk-hql-temp-table-delete-query-example[] - assertEquals( entityCount(), updateCount ); - }); + assertThat( updateCount ).isEqualTo( entityCount() ); + } ); } @Test - public void testDeleteFromEngineer() { - doInHibernate( this::sessionFactory, session -> { - int updateCount = session.createQuery( "delete from Engineer where fellow = :fellow" ) + public void testDeleteFromEngineer(SessionFactoryScope scope) { + scope.inTransaction( session -> { + int updateCount = session.createMutationQuery( "delete from Engineer where fellow = :fellow" ) .setParameter( "fellow", true ) .executeUpdate(); - assertEquals( entityCount() / 2, updateCount ); - }); + assertThat( updateCount ).isEqualTo( entityCount() / 2 ); + + } ); } @Test - public void testInsert() { - doInHibernate( this::sessionFactory, session -> { - session.createQuery( "insert into Engineer(id, companyName, name, employed, fellow) values (0, 'Red Hat', :name, :employed, false)" ) + public void testInsert(SessionFactoryScope scope) { + scope.inTransaction( session -> { + session.createMutationQuery( + "insert into Engineer(id, companyName, name, employed, fellow) values (0, 'Red Hat', :name, :employed, false)" ) .setParameter( "name", "John Doe" ) .setParameter( "employed", true ) .executeUpdate(); final Engineer engineer = session.find( Engineer.class, new AbstractMutationStrategyCompositeIdTest_.Person_.Id( 0, "Red Hat" ) ); - assertEquals( "John Doe", engineer.getName() ); - assertTrue( engineer.isEmployed() ); - assertFalse( engineer.isFellow() ); - }); + assertThat( engineer.getName() ).isEqualTo( "John Doe" ); + assertThat( engineer.isEmployed() ).isTrue(); + assertThat( engineer.isFellow() ).isFalse(); + } ); } @Test - public void testInsertSelect() { - doInHibernate( this::sessionFactory, session -> { - final int insertCount = session.createQuery( "insert into Engineer(id, companyName, name, employed, fellow) " - + "select d.id + " + (entityCount() * 2) + ", 'Red Hat', 'John Doe', true, false from Doctor d" ) + public void testInsertSelect(SessionFactoryScope scope) { + scope.inTransaction( session -> { + final int insertCount = session.createMutationQuery( + "insert into Engineer(id, companyName, name, employed, fellow) " + + "select d.id + " + (entityCount() * 2) + ", 'Red Hat', 'John Doe', true, false from Doctor d" ) .executeUpdate(); final Engineer engineer = session.find( Engineer.class, new AbstractMutationStrategyCompositeIdTest_.Person_.Id( entityCount() * 2 + 1, "Red Hat" ) ); - assertEquals( entityCount(), insertCount ); - assertEquals( "John Doe", engineer.getName() ); - assertTrue( engineer.isEmployed() ); - assertFalse( engineer.isFellow() ); - }); + assertThat( insertCount ).isEqualTo( entityCount() ); + assertThat( engineer.getName() ).isEqualTo( "John Doe" ); + assertThat( engineer.isEmployed() ).isTrue(); + assertThat( engineer.isFellow() ).isFalse(); + } ); } //tag::batch-bulk-hql-temp-table-base-class-example[] @@ -174,7 +150,7 @@ public static class Person implements Serializable { //Getters and setters are omitted for brevity - //end::batch-bulk-hql-temp-table-base-class-example[] + //end::batch-bulk-hql-temp-table-base-class-example[] public Integer getId() { return id; @@ -213,19 +189,19 @@ public boolean equals(Object o) { if ( this == o ) { return true; } - if ( !( o instanceof Person ) ) { + if ( !(o instanceof Person) ) { return false; } Person person = (Person) o; return Objects.equals( getId(), person.getId() ) && - Objects.equals( getCompanyName(), person.getCompanyName() ); + Objects.equals( getCompanyName(), person.getCompanyName() ); } @Override public int hashCode() { return Objects.hash( getId(), getCompanyName() ); } - //tag::batch-bulk-hql-temp-table-base-class-example[] + //tag::batch-bulk-hql-temp-table-base-class-example[] } //end::batch-bulk-hql-temp-table-base-class-example[] @@ -241,7 +217,7 @@ public static class Engineer extends Person { //Getters and setters are omitted for brevity - //end::batch-bulk-hql-temp-table-sub-classes-example[] + //end::batch-bulk-hql-temp-table-sub-classes-example[] public boolean isFellow() { return fellow; @@ -250,7 +226,7 @@ public boolean isFellow() { public void setFellow(boolean fellow) { this.fellow = fellow; } - //tag::batch-bulk-hql-temp-table-sub-classes-example[] + //tag::batch-bulk-hql-temp-table-sub-classes-example[] } //end::batch-bulk-hql-temp-table-sub-classes-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/AbstractMutationStrategyGeneratedIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/AbstractMutationStrategyGeneratedIdTest.java index 2c99efe211f5..7a6e8a279935 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/AbstractMutationStrategyGeneratedIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/AbstractMutationStrategyGeneratedIdTest.java @@ -11,119 +11,101 @@ import jakarta.persistence.Inheritance; import jakarta.persistence.InheritanceType; import jakarta.persistence.SequenceGenerator; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Before; -import org.junit.Test; - -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.assertTrue; - -public abstract class AbstractMutationStrategyGeneratedIdTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Doctor.class, - Engineer.class - }; - } - - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - Class insertStrategyClass = getMultiTableInsertStrategyClass(); - if ( insertStrategyClass != null ) { - configuration.setProperty( AvailableSettings.QUERY_MULTI_TABLE_INSERT_STRATEGY, insertStrategyClass ); +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.assertThat; + +@DomainModel( + annotatedClasses = { + AbstractMutationStrategyGeneratedIdTest.Person.class, + AbstractMutationStrategyGeneratedIdTest.Doctor.class, + AbstractMutationStrategyGeneratedIdTest.Engineer.class } - } - - protected abstract Class getMultiTableInsertStrategyClass(); - - @Override - protected boolean isCleanupTestDataRequired() { - return true; - } +) +@SessionFactory +public abstract class AbstractMutationStrategyGeneratedIdTest { - @Override - protected boolean isCleanupTestDataUsingBulkDelete() { - return true; - } - - @Before - public void setUp() { - doInHibernate( this::sessionFactory, session -> { + @BeforeEach + public void setUp(SessionFactoryScope scope) { + scope.inTransaction( session -> { Doctor doctor = new Doctor(); doctor.setName( "Doctor John" ); doctor.setEmployed( true ); session.persist( doctor ); - }); + } ); + } + + @AfterEach + public void tearDown(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Test - public void testInsertStatic() { - doInHibernate( this::sessionFactory, session -> { - session.createQuery( "insert into Engineer(id, name, employed, fellow) values (0, :name, :employed, false)" ) + public void testInsertStatic(SessionFactoryScope scope) { + scope.inTransaction( session -> { + session.createMutationQuery( + "insert into Engineer(id, name, employed, fellow) values (0, :name, :employed, false)" ) .setParameter( "name", "John Doe" ) .setParameter( "employed", true ) .executeUpdate(); final Engineer engineer = session.find( Engineer.class, 0 ); - assertEquals( "John Doe", engineer.getName() ); - assertTrue( engineer.isEmployed() ); - assertFalse( engineer.isFellow() ); - }); + assertThat( engineer.getName() ).isEqualTo( "John Doe" ); + assertThat( engineer.isEmployed() ).isTrue(); + assertThat( engineer.isFellow() ).isFalse(); + } ); } @Test - public void testInsertGenerated() { - doInHibernate( this::sessionFactory, session -> { - session.createQuery( "insert into Engineer(name, employed, fellow) values (:name, :employed, false)" ) + public void testInsertGenerated(SessionFactoryScope scope) { + scope.inTransaction( session -> { + session.createMutationQuery( + "insert into Engineer(name, employed, fellow) values (:name, :employed, false)" ) .setParameter( "name", "John Doe" ) .setParameter( "employed", true ) .executeUpdate(); final Engineer engineer = session.createQuery( "from Engineer e where e.name = 'John Doe'", Engineer.class ) .getSingleResult(); - assertEquals( "John Doe", engineer.getName() ); - assertTrue( engineer.isEmployed() ); - assertFalse( engineer.isFellow() ); - }); + assertThat( engineer.getName() ).isEqualTo( "John Doe" ); + assertThat( engineer.isEmployed() ).isTrue(); + assertThat( engineer.isFellow() ).isFalse(); + } ); } @Test - public void testInsertSelectStatic() { - doInHibernate( this::sessionFactory, session -> { - final int insertCount = session.createQuery( "insert into Engineer(id, name, employed, fellow) " - + "select d.id + 1, 'John Doe', true, false from Doctor d" ) + public void testInsertSelectStatic(SessionFactoryScope scope) { + scope.inTransaction( session -> { + final int insertCount = session.createMutationQuery( "insert into Engineer(id, name, employed, fellow) " + + "select d.id + 1, 'John Doe', true, false from Doctor d" ) .executeUpdate(); final Engineer engineer = session.createQuery( "from Engineer e where e.name = 'John Doe'", Engineer.class ) .getSingleResult(); - assertEquals( 1, insertCount ); - assertEquals( "John Doe", engineer.getName() ); - assertTrue( engineer.isEmployed() ); - assertFalse( engineer.isFellow() ); - }); + assertThat( insertCount ).isEqualTo( 1 ); + assertThat( engineer.getName() ).isEqualTo( "John Doe" ); + assertThat( engineer.isEmployed() ).isTrue(); + assertThat( engineer.isFellow() ).isFalse(); + } ); } @Test - public void testInsertSelectGenerated() { - doInHibernate( this::sessionFactory, session -> { - final int insertCount = session.createQuery( "insert into Engineer(name, employed, fellow) " - + "select 'John Doe', true, false from Doctor d" ) + public void testInsertSelectGenerated(SessionFactoryScope scope) { + scope.inTransaction( session -> { + final int insertCount = session.createMutationQuery( "insert into Engineer(name, employed, fellow) " + + "select 'John Doe', true, false from Doctor d" ) .executeUpdate(); final Engineer engineer = session.createQuery( "from Engineer e where e.name = 'John Doe'", Engineer.class ) .getSingleResult(); - assertEquals( 1, insertCount ); - assertEquals( "John Doe", engineer.getName() ); - assertTrue( engineer.isEmployed() ); - assertFalse( engineer.isFellow() ); - }); + assertThat( insertCount ).isEqualTo( 1 ); + assertThat( engineer.getName() ).isEqualTo( "John Doe" ); + assertThat( engineer.isEmployed() ).isTrue(); + assertThat( engineer.isFellow() ).isFalse(); + } ); } @Entity(name = "Person") @@ -163,6 +145,7 @@ public void setEmployed(boolean employed) { this.employed = employed; } } + @Entity(name = "Doctor") public static class Doctor extends Person { } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/AbstractMutationStrategyGeneratedIdWithOptimizerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/AbstractMutationStrategyGeneratedIdWithOptimizerTest.java index 522dfb57e628..8813b6e6c76c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/AbstractMutationStrategyGeneratedIdWithOptimizerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/AbstractMutationStrategyGeneratedIdWithOptimizerTest.java @@ -6,123 +6,105 @@ import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; -import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.Inheritance; import jakarta.persistence.InheritanceType; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Before; -import org.junit.Test; - -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.assertTrue; - -public abstract class AbstractMutationStrategyGeneratedIdWithOptimizerTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Doctor.class, - Engineer.class - }; - } - - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - Class insertStrategyClass = getMultiTableInsertStrategyClass(); - if ( insertStrategyClass != null ) { - configuration.setProperty( AvailableSettings.QUERY_MULTI_TABLE_INSERT_STRATEGY, insertStrategyClass ); +import jakarta.persistence.SequenceGenerator; +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.assertThat; + +@DomainModel( + annotatedClasses = { + AbstractMutationStrategyGeneratedIdWithOptimizerTest.Person.class, + AbstractMutationStrategyGeneratedIdWithOptimizerTest.Doctor.class, + AbstractMutationStrategyGeneratedIdWithOptimizerTest.Engineer.class } - } - - protected abstract Class getMultiTableInsertStrategyClass(); - - @Override - protected boolean isCleanupTestDataRequired() { - return true; - } +) +@SessionFactory +public abstract class AbstractMutationStrategyGeneratedIdWithOptimizerTest { - @Override - protected boolean isCleanupTestDataUsingBulkDelete() { - return true; - } - - @Before - public void setUp() { - doInHibernate( this::sessionFactory, session -> { + @BeforeEach + public void setUp(SessionFactoryScope scope) { + scope.inTransaction( session -> { Doctor doctor = new Doctor(); doctor.setName( "Doctor John" ); doctor.setEmployed( true ); session.persist( doctor ); - }); + } ); + } + + @AfterEach + public void tearDown(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Test - public void testInsertStatic() { - doInHibernate( this::sessionFactory, session -> { - session.createQuery( "insert into Engineer(id, name, employed, fellow) values (0, :name, :employed, false)" ) + public void testInsertStatic(SessionFactoryScope scope) { + scope.inTransaction( session -> { + session.createMutationQuery( + "insert into Engineer(id, name, employed, fellow) values (0, :name, :employed, false)" ) .setParameter( "name", "John Doe" ) .setParameter( "employed", true ) .executeUpdate(); final Engineer engineer = session.find( Engineer.class, 0 ); - assertEquals( "John Doe", engineer.getName() ); - assertTrue( engineer.isEmployed() ); - assertFalse( engineer.isFellow() ); - }); + assertThat( engineer.getName() ).isEqualTo( "John Doe" ); + assertThat( engineer.isEmployed() ).isTrue(); + assertThat( engineer.isFellow() ).isFalse(); + } ); } @Test - public void testInsertGenerated() { - doInHibernate( this::sessionFactory, session -> { - session.createQuery( "insert into Engineer(name, employed, fellow) values (:name, :employed, false)" ) + public void testInsertGenerated(SessionFactoryScope scope) { + scope.inTransaction( session -> { + session.createMutationQuery( + "insert into Engineer(name, employed, fellow) values (:name, :employed, false)" ) .setParameter( "name", "John Doe" ) .setParameter( "employed", true ) .executeUpdate(); final Engineer engineer = session.createQuery( "from Engineer e where e.name = 'John Doe'", Engineer.class ) .getSingleResult(); - assertEquals( "John Doe", engineer.getName() ); - assertTrue( engineer.isEmployed() ); - assertFalse( engineer.isFellow() ); - }); + assertThat( engineer.getName() ).isEqualTo( "John Doe" ); + assertThat( engineer.isEmployed() ).isTrue(); + assertThat( engineer.isFellow() ).isFalse(); + } ); } @Test - public void testInsertSelectStatic() { - doInHibernate( this::sessionFactory, session -> { - final int insertCount = session.createQuery( "insert into Engineer(id, name, employed, fellow) " - + "select d.id + 1, 'John Doe', true, false from Doctor d" ) + public void testInsertSelectStatic(SessionFactoryScope scope) { + scope.inTransaction( session -> { + final int insertCount = session.createMutationQuery( "insert into Engineer(id, name, employed, fellow) " + + "select d.id + 1, 'John Doe', true, false from Doctor d" ) .executeUpdate(); final Engineer engineer = session.createQuery( "from Engineer e where e.name = 'John Doe'", Engineer.class ) .getSingleResult(); - assertEquals( 1, insertCount ); - assertEquals( "John Doe", engineer.getName() ); - assertTrue( engineer.isEmployed() ); - assertFalse( engineer.isFellow() ); - }); + assertThat( insertCount ).isEqualTo( 1 ); + assertThat( engineer.getName() ).isEqualTo( "John Doe" ); + assertThat( engineer.isEmployed() ).isTrue(); + assertThat( engineer.isFellow() ).isFalse(); + } ); } @Test - public void testInsertSelectGenerated() { - doInHibernate( this::sessionFactory, session -> { - final int insertCount = session.createQuery( "insert into Engineer(name, employed, fellow) " - + "select 'John Doe', true, false from Doctor d" ) + public void testInsertSelectGenerated(SessionFactoryScope scope) { + scope.inTransaction( session -> { + final int insertCount = session.createMutationQuery( "insert into Engineer(name, employed, fellow) " + + "select 'John Doe', true, false from Doctor d" ) .executeUpdate(); final Engineer engineer = session.createQuery( "from Engineer e where e.name = 'John Doe'", Engineer.class ) .getSingleResult(); - assertEquals( 1, insertCount ); - assertEquals( "John Doe", engineer.getName() ); - assertTrue( engineer.isEmployed() ); - assertFalse( engineer.isFellow() ); - }); + assertThat( insertCount ).isEqualTo( 1 ); + assertThat( engineer.getName() ).isEqualTo( "John Doe" ); + assertThat( engineer.isEmployed() ).isTrue(); + assertThat( engineer.isFellow() ).isFalse(); + } ); } @Entity(name = "Person") @@ -130,7 +112,8 @@ public void testInsertSelectGenerated() { public static class Person { @Id - @GeneratedValue(strategy = GenerationType.SEQUENCE) + @GeneratedValue( generator = "a_sequence") + @SequenceGenerator(name = "a_sequence", sequenceName = "person_sequence") private Integer id; private String name; @@ -161,6 +144,7 @@ public void setEmployed(boolean employed) { this.employed = employed; } } + @Entity(name = "Doctor") public static class Doctor extends Person { } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/AbstractMutationStrategyGeneratedIdentityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/AbstractMutationStrategyGeneratedIdentityTest.java index dd7236fb806b..1dba5b8473c4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/AbstractMutationStrategyGeneratedIdentityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/AbstractMutationStrategyGeneratedIdentityTest.java @@ -10,131 +10,118 @@ import jakarta.persistence.Id; import jakarta.persistence.Inheritance; import jakarta.persistence.InheritanceType; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; import org.hibernate.community.dialect.InformixDialect; import org.hibernate.dialect.AbstractTransactSQLDialect; import org.hibernate.dialect.MySQLDialect; import org.hibernate.dialect.OracleDialect; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +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.Before; -import org.junit.Test; - -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.assertTrue; - -public abstract class AbstractMutationStrategyGeneratedIdentityTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Doctor.class, - Engineer.class - }; - } - - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - Class insertStrategyClass = getMultiTableInsertStrategyClass(); - if ( insertStrategyClass != null ) { - configuration.setProperty( AvailableSettings.QUERY_MULTI_TABLE_INSERT_STRATEGY, insertStrategyClass ); - } - } - - protected abstract Class getMultiTableInsertStrategyClass(); +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; - @Override - protected boolean isCleanupTestDataRequired() { - return true; - } +import static org.assertj.core.api.Assertions.assertThat; - @Override - protected boolean isCleanupTestDataUsingBulkDelete() { - return true; - } +@DomainModel( + annotatedClasses = { + AbstractMutationStrategyGeneratedIdentityTest.Person.class, + AbstractMutationStrategyGeneratedIdentityTest.Doctor.class, + AbstractMutationStrategyGeneratedIdentityTest.Engineer.class + } +) +@SessionFactory +public abstract class AbstractMutationStrategyGeneratedIdentityTest { - @Before - public void setUp() { - doInHibernate( this::sessionFactory, session -> { + @BeforeEach + public void setUp(SessionFactoryScope scope) { + scope.inTransaction( session -> { Doctor doctor = new Doctor(); doctor.setName( "Doctor John" ); doctor.setEmployed( true ); session.persist( doctor ); - }); + } ); + } + + @AfterEach + public void tearDown(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Test - @SkipForDialect(dialectClass = MySQLDialect.class, matchSubTypes = true, reason = "MySQL ignores a provided value for an auto_increment column if it's lower than the current sequence value") - @SkipForDialect(dialectClass = AbstractTransactSQLDialect.class, matchSubTypes = true, reason = "T-SQL complains IDENTITY_INSERT is off when a value for an identity column is provided") + @SkipForDialect(dialectClass = MySQLDialect.class, matchSubTypes = true, + reason = "MySQL ignores a provided value for an auto_increment column if it's lower than the current sequence value") + @SkipForDialect(dialectClass = AbstractTransactSQLDialect.class, matchSubTypes = true, + reason = "T-SQL complains IDENTITY_INSERT is off when a value for an identity column is provided") @SkipForDialect(dialectClass = InformixDialect.class, reason = "Informix counts from 1 like a normal person") - public void testInsertStatic() { - doInHibernate( this::sessionFactory, session -> { - session.createQuery( "insert into Engineer(id, name, employed, fellow) values (0, :name, :employed, false)" ) + public void testInsertStatic(SessionFactoryScope scope) { + scope.inTransaction( session -> { + session.createMutationQuery( + "insert into Engineer(id, name, employed, fellow) values (0, :name, :employed, false)" ) .setParameter( "name", "John Doe" ) .setParameter( "employed", true ) .executeUpdate(); final Engineer engineer = session.find( Engineer.class, 0 ); - assertEquals( "John Doe", engineer.getName() ); - assertTrue( engineer.isEmployed() ); - assertFalse( engineer.isFellow() ); - }); + assertThat( engineer.getName() ).isEqualTo( "John Doe" ); + assertThat( engineer.isEmployed() ).isTrue(); + assertThat( engineer.isFellow() ).isFalse(); + } ); } @Test - @SkipForDialect(dialectClass = OracleDialect.class, reason = "Oracle doesn't support insert-select with a returning clause") - public void testInsertGenerated() { - doInHibernate( this::sessionFactory, session -> { - session.createQuery( "insert into Engineer(name, employed, fellow) values (:name, :employed, false)" ) + @SkipForDialect(dialectClass = OracleDialect.class, + reason = "Oracle doesn't support insert-select with a returning clause") + public void testInsertGenerated(SessionFactoryScope scope) { + scope.inTransaction( session -> { + session.createMutationQuery( "insert into Engineer(name, employed, fellow) values (:name, :employed, false)" ) .setParameter( "name", "John Doe" ) .setParameter( "employed", true ) .executeUpdate(); final Engineer engineer = session.createQuery( "from Engineer e where e.name = 'John Doe'", Engineer.class ) .getSingleResult(); - assertEquals( "John Doe", engineer.getName() ); - assertTrue( engineer.isEmployed() ); - assertFalse( engineer.isFellow() ); - }); + assertThat( engineer.getName() ).isEqualTo( "John Doe" ); + assertThat( engineer.isEmployed() ).isTrue(); + assertThat( engineer.isFellow() ).isFalse(); + } ); } @Test - @SkipForDialect(dialectClass = MySQLDialect.class, matchSubTypes = true, reason = "MySQL ignores a provided value for an auto_increment column if it's lower than the current sequence value") - @SkipForDialect(dialectClass = AbstractTransactSQLDialect.class, matchSubTypes = true, reason = "T-SQL complains IDENTITY_INSERT is off when a value for an identity column is provided") - public void testInsertSelectStatic() { - doInHibernate( this::sessionFactory, session -> { - final int insertCount = session.createQuery( "insert into Engineer(id, name, employed, fellow) " + @SkipForDialect(dialectClass = MySQLDialect.class, matchSubTypes = true, + reason = "MySQL ignores a provided value for an auto_increment column if it's lower than the current sequence value") + @SkipForDialect(dialectClass = AbstractTransactSQLDialect.class, matchSubTypes = true, + reason = "T-SQL complains IDENTITY_INSERT is off when a value for an identity column is provided") + public void testInsertSelectStatic(SessionFactoryScope scope) { + scope.inTransaction( session -> { + final int insertCount = session.createMutationQuery( "insert into Engineer(id, name, employed, fellow) " + "select d.id + 1, 'John Doe', true, false from Doctor d" ) .executeUpdate(); final Engineer engineer = session.createQuery( "from Engineer e where e.name = 'John Doe'", Engineer.class ) .getSingleResult(); - assertEquals( 1, insertCount ); - assertEquals( "John Doe", engineer.getName() ); - assertTrue( engineer.isEmployed() ); - assertFalse( engineer.isFellow() ); - }); + assertThat( insertCount ).isEqualTo( 1 ); + assertThat( engineer.getName() ).isEqualTo( "John Doe" ); + assertThat( engineer.isEmployed() ).isTrue(); + assertThat( engineer.isFellow() ).isFalse(); + } ); } @Test - @SkipForDialect(dialectClass = OracleDialect.class, reason = "Oracle doesn't support insert-select with a returning clause") - public void testInsertSelectGenerated() { - doInHibernate( this::sessionFactory, session -> { - final int insertCount = session.createQuery( "insert into Engineer(name, employed, fellow) " + @SkipForDialect(dialectClass = OracleDialect.class, + reason = "Oracle doesn't support insert-select with a returning clause") + public void testInsertSelectGenerated(SessionFactoryScope scope) { + scope.inTransaction( session -> { + final int insertCount = session.createMutationQuery( "insert into Engineer(name, employed, fellow) " + "select 'John Doe', true, false from Doctor d" ) .executeUpdate(); final Engineer engineer = session.createQuery( "from Engineer e where e.name = 'John Doe'", Engineer.class ) .getSingleResult(); - assertEquals( 1, insertCount ); - assertEquals( "John Doe", engineer.getName() ); - assertTrue( engineer.isEmployed() ); - assertFalse( engineer.isFellow() ); - }); + assertThat( insertCount ).isEqualTo( 1 ); + assertThat( engineer.getName() ).isEqualTo( "John Doe" ); + assertThat( engineer.isEmployed() ).isTrue(); + assertThat( engineer.isFellow() ).isFalse(); + } ); } @Entity(name = "Person") @@ -173,6 +160,7 @@ public void setEmployed(boolean employed) { this.employed = employed; } } + @Entity(name = "Doctor") public static class Doctor extends Person { } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/AbstractMutationStrategyIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/AbstractMutationStrategyIdTest.java index 2cbb7136d98c..abc6300e00e9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/AbstractMutationStrategyIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/AbstractMutationStrategyIdTest.java @@ -12,105 +12,76 @@ import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaUpdate; import jakarta.persistence.criteria.Root; - -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableMutationStrategy; - -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.Jira; -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.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.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Vlad Mihalcea */ -public abstract class AbstractMutationStrategyIdTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Doctor.class, - Engineer.class - }; - } - - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - final Class mutationStrategyClass = getMultiTableMutationStrategyClass(); - if ( mutationStrategyClass != null ) { - configuration.setProperty( AvailableSettings.QUERY_MULTI_TABLE_MUTATION_STRATEGY, mutationStrategyClass ); - } - Class insertStrategyClass = getMultiTableInsertStrategyClass(); - if ( insertStrategyClass != null ) { - configuration.setProperty( AvailableSettings.QUERY_MULTI_TABLE_INSERT_STRATEGY, insertStrategyClass ); +@DomainModel( + annotatedClasses = { + AbstractMutationStrategyIdTest.Person.class, + AbstractMutationStrategyIdTest.Doctor.class, + AbstractMutationStrategyIdTest.Engineer.class } - } - - - protected abstract Class getMultiTableMutationStrategyClass(); - - protected abstract Class getMultiTableInsertStrategyClass(); +) +@SessionFactory +public abstract class AbstractMutationStrategyIdTest { - @Override - protected boolean isCleanupTestDataRequired() { - return true; - } - - @Override - protected boolean isCleanupTestDataUsingBulkDelete() { - return true; - } - - @Before - public void setUp() { - doInHibernate( this::sessionFactory, session -> { + @BeforeEach + public void setUp(SessionFactoryScope scope) { + scope.inTransaction( session -> { for ( int i = 0; i < entityCount(); i++ ) { Doctor doctor = new Doctor(); doctor.setId( i + 1 ); - doctor.setEmployed( ( i % 2 ) == 0 ); + doctor.setEmployed( (i % 2) == 0 ); session.persist( doctor ); } for ( int i = 0; i < entityCount(); i++ ) { Engineer engineer = new Engineer(); engineer.setId( i + 1 + entityCount() ); - engineer.setEmployed( ( i % 2 ) == 0 ); - engineer.setFellow( ( i % 2 ) == 1 ); + engineer.setEmployed( (i % 2) == 0 ); + engineer.setFellow( (i % 2) == 1 ); session.persist( engineer ); } - }); + } ); } + @AfterEach + public void tearDown(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); + } + + protected int entityCount() { return 10; } @Test - public void testUpdate() { - doInHibernate( this::sessionFactory, session -> { - int updateCount = session.createQuery( "update Person set name = :name where employed = :employed" ) + public void testUpdate(SessionFactoryScope scope) { + scope.inTransaction( session -> { + int updateCount = session.createMutationQuery( "update Person set name = :name where employed = :employed" ) .setParameter( "name", "John Doe" ) .setParameter( "employed", true ) .executeUpdate(); - assertEquals(entityCount(), updateCount); - }); + assertThat( updateCount ).isEqualTo( entityCount() ); + } ); } @Test - @Jira( value = "HHH-18373" ) - public void testNullValueUpdateWithCriteria() { - doInHibernate( this::sessionFactory, session -> { - EntityManager entityManager = session.unwrap( EntityManager.class); + @Jira(value = "HHH-18373") + public void testNullValueUpdateWithCriteria(SessionFactoryScope scope) { + scope.inTransaction( session -> { + EntityManager entityManager = session.unwrap( EntityManager.class ); CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaUpdate update = cb.createCriteriaUpdate( Person.class ).set( "name", null ); @@ -118,59 +89,60 @@ public void testNullValueUpdateWithCriteria() { update.where( cb.equal( person.get( "employed" ), true ) ); int updateCount = entityManager.createQuery( update ).executeUpdate(); - assertEquals( entityCount(), updateCount ); - }); + assertThat( updateCount ).isEqualTo( entityCount() ); + } ); } @Test - public void testDeleteFromPerson() { - doInHibernate( this::sessionFactory, session -> { - int updateCount = session.createQuery( - "delete from Person where employed = :employed" ) - .setParameter( "employed", false ) - .executeUpdate(); - assertEquals( entityCount(), updateCount ); - }); + public void testDeleteFromPerson(SessionFactoryScope scope) { + scope.inTransaction( session -> { + int updateCount = session.createMutationQuery( + "delete from Person where employed = :employed" ) + .setParameter( "employed", false ) + .executeUpdate(); + assertThat( updateCount ).isEqualTo( entityCount() ); + } ); } @Test - public void testDeleteFromEngineer() { - doInHibernate( this::sessionFactory, session -> { - int updateCount = session.createQuery( "delete from Engineer where fellow = :fellow" ) + public void testDeleteFromEngineer(SessionFactoryScope scope) { + scope.inTransaction( session -> { + int updateCount = session.createMutationQuery( "delete from Engineer where fellow = :fellow" ) .setParameter( "fellow", true ) .executeUpdate(); - assertEquals( entityCount() / 2, updateCount ); - }); + assertThat( updateCount ).isEqualTo( entityCount() / 2 ); + } ); } @Test - public void testInsert() { - doInHibernate( this::sessionFactory, session -> { - session.createQuery( "insert into Engineer(id, name, employed, fellow) values (0, :name, :employed, false)" ) + public void testInsert(SessionFactoryScope scope) { + scope.inTransaction( session -> { + session.createMutationQuery( + "insert into Engineer(id, name, employed, fellow) values (0, :name, :employed, false)" ) .setParameter( "name", "John Doe" ) .setParameter( "employed", true ) .executeUpdate(); final Engineer engineer = session.find( Engineer.class, 0 ); - assertEquals( "John Doe", engineer.getName() ); - assertTrue( engineer.isEmployed() ); - assertFalse( engineer.isFellow() ); - }); + assertThat( engineer.getName() ).isEqualTo( "John Doe" ); + assertThat( engineer.isEmployed() ).isTrue(); + assertThat( engineer.isFellow() ).isFalse(); + } ); } @Test - public void testInsertSelect() { - doInHibernate( this::sessionFactory, session -> { + public void testInsertSelect(SessionFactoryScope scope) { + scope.inTransaction( session -> { final int insertCount = session.createQuery( "insert into Engineer(id, name, employed, fellow) " + "select d.id + " + (entityCount() * 2) + ", 'John Doe', true, false from Doctor d" ) .executeUpdate(); final AbstractMutationStrategyIdTest.Engineer engineer = session.find( AbstractMutationStrategyIdTest.Engineer.class, entityCount() * 2 + 1 ); - assertEquals( entityCount(), insertCount ); - assertEquals( "John Doe", engineer.getName() ); - assertTrue( engineer.isEmployed() ); - assertFalse( engineer.isFellow() ); - }); + assertThat( insertCount ).isEqualTo( entityCount() ); + assertThat( engineer.getName() ).isEqualTo( "John Doe" ); + assertThat( engineer.isEmployed() ).isTrue(); + assertThat( engineer.isFellow() ).isFalse(); + } ); } @Entity(name = "Person") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/DefaultMutationStrategyCompositeIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/DefaultMutationStrategyCompositeIdTest.java index 0e2aa0fe2d88..14b13c068546 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/DefaultMutationStrategyCompositeIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/DefaultMutationStrategyCompositeIdTest.java @@ -4,21 +4,8 @@ */ package org.hibernate.orm.test.bulkid; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableMutationStrategy; - /** * @author Vlad Mihalcea */ public class DefaultMutationStrategyCompositeIdTest extends AbstractMutationStrategyCompositeIdTest { - - @Override - protected Class getMultiTableMutationStrategyClass() { - return null; - } - - @Override - protected Class getMultiTableInsertStrategyClass() { - return null; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/DefaultMutationStrategyGeneratedIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/DefaultMutationStrategyGeneratedIdTest.java index cb65394ac588..1e05df56b08d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/DefaultMutationStrategyGeneratedIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/DefaultMutationStrategyGeneratedIdTest.java @@ -4,12 +4,6 @@ */ package org.hibernate.orm.test.bulkid; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy; - public class DefaultMutationStrategyGeneratedIdTest extends AbstractMutationStrategyGeneratedIdTest { - @Override - protected Class getMultiTableInsertStrategyClass() { - return null; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/DefaultMutationStrategyGeneratedIdWithOptimizerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/DefaultMutationStrategyGeneratedIdWithOptimizerTest.java index ab9dca1c80af..f5b7d55533f4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/DefaultMutationStrategyGeneratedIdWithOptimizerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/DefaultMutationStrategyGeneratedIdWithOptimizerTest.java @@ -4,12 +4,7 @@ */ package org.hibernate.orm.test.bulkid; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy; +public class DefaultMutationStrategyGeneratedIdWithOptimizerTest + extends AbstractMutationStrategyGeneratedIdWithOptimizerTest { -public class DefaultMutationStrategyGeneratedIdWithOptimizerTest extends AbstractMutationStrategyGeneratedIdWithOptimizerTest { - - @Override - protected Class getMultiTableInsertStrategyClass() { - return null; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/DefaultMutationStrategyGeneratedIdentityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/DefaultMutationStrategyGeneratedIdentityTest.java index c101cfa5cb35..a5ef15e5e877 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/DefaultMutationStrategyGeneratedIdentityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/DefaultMutationStrategyGeneratedIdentityTest.java @@ -4,15 +4,10 @@ */ package org.hibernate.orm.test.bulkid; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy; import org.hibernate.testing.orm.junit.DialectFeatureChecks; import org.hibernate.testing.orm.junit.RequiresDialectFeature; @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsIdentityColumns.class) public class DefaultMutationStrategyGeneratedIdentityTest extends AbstractMutationStrategyGeneratedIdentityTest { - @Override - protected Class getMultiTableInsertStrategyClass() { - return null; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/DefaultMutationStrategyIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/DefaultMutationStrategyIdTest.java index 017832ab0b6f..3c63e6e48530 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/DefaultMutationStrategyIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/DefaultMutationStrategyIdTest.java @@ -4,21 +4,8 @@ */ package org.hibernate.orm.test.bulkid; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableMutationStrategy; - /** * @author Vlad Mihalcea */ public class DefaultMutationStrategyIdTest extends AbstractMutationStrategyIdTest { - - @Override - protected Class getMultiTableMutationStrategyClass() { - return null; - } - - @Override - protected Class getMultiTableInsertStrategyClass() { - return null; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/GlobalQuotedIdentifiersBulkIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/GlobalQuotedIdentifiersBulkIdTest.java index baa67a110ca6..9fbfb2eb8ebf 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/GlobalQuotedIdentifiersBulkIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/GlobalQuotedIdentifiersBulkIdTest.java @@ -4,10 +4,6 @@ */ package org.hibernate.orm.test.bulkid; -import java.sql.Timestamp; -import java.util.Arrays; -import java.util.Date; -import java.util.Map; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; @@ -15,77 +11,100 @@ import jakarta.persistence.InheritanceType; import jakarta.persistence.Temporal; import jakarta.persistence.TemporalType; - import org.hibernate.cfg.AvailableSettings; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; import org.hibernate.query.sqm.mutation.internal.inline.InlineMutationStrategy; - +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -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.hibernate.testing.orm.junit.SettingProvider; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.sql.Timestamp; +import java.util.Arrays; +import java.util.Date; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Vlad Mihalcea */ -@JiraKey( value = "HHH-12561" ) -public class GlobalQuotedIdentifiersBulkIdTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Doctor.class, - Engineer.class - }; - } - - @Override - protected void addConfigOptions(Map options) { - options.put( AvailableSettings.GLOBALLY_QUOTED_IDENTIFIERS, Boolean.TRUE ); - options.put( AvailableSettings.QUERY_MULTI_TABLE_MUTATION_STRATEGY, InlineMutationStrategy.class.getName() ); +@JiraKey(value = "HHH-12561") +@DomainModel( + annotatedClasses = { + GlobalQuotedIdentifiersBulkIdTest.Person.class, + GlobalQuotedIdentifiersBulkIdTest.Doctor.class, + GlobalQuotedIdentifiersBulkIdTest.Engineer.class + } +) +@SessionFactory +@ServiceRegistry( + settings = @Setting(name = AvailableSettings.GLOBALLY_QUOTED_IDENTIFIERS, value = "true"), + settingProviders = { + @SettingProvider( + settingName = AvailableSettings.QUERY_MULTI_TABLE_MUTATION_STRATEGY, + provider = GlobalQuotedIdentifiersBulkIdTest.QueryMultyTableMutationStrategyProvider.class + ) + } +) +public class GlobalQuotedIdentifiersBulkIdTest { + + public static class QueryMultyTableMutationStrategyProvider + implements SettingProvider.Provider { + @Override + public String getSetting() { + return InlineMutationStrategy.class.getName(); + } } - @Before - public void setUp() { - doInJPA( this::entityManagerFactory, entityManager -> { + @BeforeEach + public void setUp(SessionFactoryScope scope) { + scope.inTransaction( entityManager -> { for ( int i = 0; i < entityCount(); i++ ) { Doctor doctor = new Doctor(); - doctor.setEmployed( ( i % 2 ) == 0 ); + doctor.setEmployed( (i % 2) == 0 ); doctor.setEmployedOn( Timestamp.valueOf( "2018-06-01 00:00:00" ) ); entityManager.persist( doctor ); } for ( int i = 0; i < entityCount(); i++ ) { Engineer engineer = new Engineer(); - engineer.setEmployed( ( i % 2 ) == 0 ); + engineer.setEmployed( (i % 2) == 0 ); engineer.setEmployedOn( Timestamp.valueOf( "2018-06-01 00:00:00" ) ); - engineer.setFellow( ( i % 2 ) == 1 ); + engineer.setFellow( (i % 2) == 1 ); entityManager.persist( engineer ); } - }); + } ); + } + + @AfterEach + public void tearDown(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } + protected int entityCount() { return 5; } @Test - public void testBulkUpdate() { - doInJPA( this::entityManagerFactory, entityManager -> { + public void testBulkUpdate(SessionFactoryScope scope) { + scope.inTransaction( entityManager -> { int updateCount = entityManager.createQuery( - "UPDATE Person u " + - "SET u.employedOn = :date " + - "WHERE u.id IN :userIds" - ) - .setParameter( "date", Timestamp.valueOf( "2018-06-03 00:00:00" ) ) - .setParameter( "userIds", Arrays.asList(1L, 2L, 3L ) ) - .executeUpdate(); - - assertEquals(3, updateCount); - }); + "UPDATE Person u " + + "SET u.employedOn = :date " + + "WHERE u.id IN :userIds" + ) + .setParameter( "date", Timestamp.valueOf( "2018-06-03 00:00:00" ) ) + .setParameter( "userIds", Arrays.asList( 1L, 2L, 3L ) ) + .executeUpdate(); + + assertThat( updateCount ).isEqualTo( 3 ); + } ); } @Entity(name = "Person") @@ -100,7 +119,7 @@ public static class Person { private boolean employed; - @Temporal( TemporalType.TIMESTAMP ) + @Temporal(TemporalType.TIMESTAMP) private Date employedOn; public Long getId() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/GlobalTemporaryTableMutationStrategyCompositeIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/GlobalTemporaryTableMutationStrategyCompositeIdTest.java index 6427198a71c6..c25703ae4af4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/GlobalTemporaryTableMutationStrategyCompositeIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/GlobalTemporaryTableMutationStrategyCompositeIdTest.java @@ -4,23 +4,42 @@ */ package org.hibernate.orm.test.bulkid; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.query.sqm.mutation.internal.temptable.GlobalTemporaryTableInsertStrategy; import org.hibernate.query.sqm.mutation.internal.temptable.GlobalTemporaryTableMutationStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableMutationStrategy; import org.hibernate.testing.orm.junit.DialectFeatureChecks; import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SettingProvider; @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsGlobalTemporaryTable.class) +@ServiceRegistry( + settingProviders = { + @SettingProvider( + settingName = AvailableSettings.QUERY_MULTI_TABLE_MUTATION_STRATEGY, + provider = GlobalTemporaryTableMutationStrategyCompositeIdTest.QueryMultyTableMutationStrategyProvider.class + ), + @SettingProvider( + settingName = AvailableSettings.QUERY_MULTI_TABLE_INSERT_STRATEGY, + provider = GlobalTemporaryTableMutationStrategyCompositeIdTest.QueryMultyTableInsertStrategyProvider.class + ) + } +) public class GlobalTemporaryTableMutationStrategyCompositeIdTest extends AbstractMutationStrategyCompositeIdTest { - @Override - protected Class getMultiTableMutationStrategyClass() { - return GlobalTemporaryTableMutationStrategy.class; + public static class QueryMultyTableMutationStrategyProvider + implements SettingProvider.Provider { + @Override + public String getSetting() { + return GlobalTemporaryTableMutationStrategy.class.getName(); + } } - @Override - protected Class getMultiTableInsertStrategyClass() { - return GlobalTemporaryTableInsertStrategy.class; + public static class QueryMultyTableInsertStrategyProvider + implements SettingProvider.Provider { + @Override + public String getSetting() { + return GlobalTemporaryTableInsertStrategy.class.getName(); + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/GlobalTemporaryTableMutationStrategyGeneratedIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/GlobalTemporaryTableMutationStrategyGeneratedIdTest.java index 9e59892d23bc..6f5cc2d1c080 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/GlobalTemporaryTableMutationStrategyGeneratedIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/GlobalTemporaryTableMutationStrategyGeneratedIdTest.java @@ -4,16 +4,29 @@ */ package org.hibernate.orm.test.bulkid; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.query.sqm.mutation.internal.temptable.GlobalTemporaryTableInsertStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy; import org.hibernate.testing.orm.junit.DialectFeatureChecks; import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SettingProvider; @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsGlobalTemporaryTable.class) +@ServiceRegistry( + settingProviders = { + @SettingProvider( + settingName = AvailableSettings.QUERY_MULTI_TABLE_INSERT_STRATEGY, + provider = GlobalTemporaryTableMutationStrategyGeneratedIdTest.QueryMultyTableInsertStrategyProvider.class + ) + } +) public class GlobalTemporaryTableMutationStrategyGeneratedIdTest extends AbstractMutationStrategyGeneratedIdTest { - @Override - protected Class getMultiTableInsertStrategyClass() { - return GlobalTemporaryTableInsertStrategy.class; + public static class QueryMultyTableInsertStrategyProvider + implements SettingProvider.Provider { + @Override + public String getSetting() { + return GlobalTemporaryTableInsertStrategy.class.getName(); + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/GlobalTemporaryTableMutationStrategyGeneratedIdWithOptimizerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/GlobalTemporaryTableMutationStrategyGeneratedIdWithOptimizerTest.java index 1b340369d524..6b011f35a95c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/GlobalTemporaryTableMutationStrategyGeneratedIdWithOptimizerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/GlobalTemporaryTableMutationStrategyGeneratedIdWithOptimizerTest.java @@ -4,16 +4,30 @@ */ package org.hibernate.orm.test.bulkid; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.query.sqm.mutation.internal.temptable.GlobalTemporaryTableInsertStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy; import org.hibernate.testing.orm.junit.DialectFeatureChecks; import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SettingProvider; @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsGlobalTemporaryTable.class) -public class GlobalTemporaryTableMutationStrategyGeneratedIdWithOptimizerTest extends AbstractMutationStrategyGeneratedIdWithOptimizerTest { +@ServiceRegistry( + settingProviders = { + @SettingProvider( + settingName = AvailableSettings.QUERY_MULTI_TABLE_INSERT_STRATEGY, + provider = GlobalTemporaryTableMutationStrategyGeneratedIdWithOptimizerTest.QueryMultyTableInsertStrategyProvider.class + ) + } +) +public class GlobalTemporaryTableMutationStrategyGeneratedIdWithOptimizerTest + extends AbstractMutationStrategyGeneratedIdWithOptimizerTest { - @Override - protected Class getMultiTableInsertStrategyClass() { - return GlobalTemporaryTableInsertStrategy.class; + public static class QueryMultyTableInsertStrategyProvider + implements SettingProvider.Provider { + @Override + public String getSetting() { + return GlobalTemporaryTableInsertStrategy.class.getName(); + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/GlobalTemporaryTableMutationStrategyGeneratedIdentityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/GlobalTemporaryTableMutationStrategyGeneratedIdentityTest.java index f6a23fc9290b..20e7446a9b51 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/GlobalTemporaryTableMutationStrategyGeneratedIdentityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/GlobalTemporaryTableMutationStrategyGeneratedIdentityTest.java @@ -4,17 +4,31 @@ */ package org.hibernate.orm.test.bulkid; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.query.sqm.mutation.internal.temptable.GlobalTemporaryTableInsertStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy; import org.hibernate.testing.orm.junit.DialectFeatureChecks; import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SettingProvider; @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsGlobalTemporaryTable.class) @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsGlobalTemporaryTableIdentity.class) -public class GlobalTemporaryTableMutationStrategyGeneratedIdentityTest extends AbstractMutationStrategyGeneratedIdentityTest { +@ServiceRegistry( + settingProviders = { + @SettingProvider( + settingName = AvailableSettings.QUERY_MULTI_TABLE_INSERT_STRATEGY, + provider = GlobalTemporaryTableMutationStrategyGeneratedIdentityTest.QueryMultyTableInsertStrategyProvider.class + ) + } +) +public class GlobalTemporaryTableMutationStrategyGeneratedIdentityTest + extends AbstractMutationStrategyGeneratedIdentityTest { - @Override - protected Class getMultiTableInsertStrategyClass() { - return GlobalTemporaryTableInsertStrategy.class; + public static class QueryMultyTableInsertStrategyProvider + implements SettingProvider.Provider { + @Override + public String getSetting() { + return GlobalTemporaryTableInsertStrategy.class.getName(); + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/GlobalTemporaryTableMutationStrategyIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/GlobalTemporaryTableMutationStrategyIdTest.java index a4ee11741f38..08947d2c20ce 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/GlobalTemporaryTableMutationStrategyIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/GlobalTemporaryTableMutationStrategyIdTest.java @@ -4,23 +4,42 @@ */ package org.hibernate.orm.test.bulkid; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.query.sqm.mutation.internal.temptable.GlobalTemporaryTableInsertStrategy; import org.hibernate.query.sqm.mutation.internal.temptable.GlobalTemporaryTableMutationStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableMutationStrategy; import org.hibernate.testing.orm.junit.DialectFeatureChecks; import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SettingProvider; @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsGlobalTemporaryTable.class) +@ServiceRegistry( + settingProviders = { + @SettingProvider( + settingName = AvailableSettings.QUERY_MULTI_TABLE_MUTATION_STRATEGY, + provider = GlobalTemporaryTableMutationStrategyIdTest.QueryMultyTableMutationStrategyProvider.class + ), + @SettingProvider( + settingName = AvailableSettings.QUERY_MULTI_TABLE_INSERT_STRATEGY, + provider = GlobalTemporaryTableMutationStrategyIdTest.QueryMultyTableInsertStrategyProvider.class + ) + } +) public class GlobalTemporaryTableMutationStrategyIdTest extends AbstractMutationStrategyIdTest { - @Override - protected Class getMultiTableMutationStrategyClass() { - return GlobalTemporaryTableMutationStrategy.class; + public static class QueryMultyTableMutationStrategyProvider + implements SettingProvider.Provider { + @Override + public String getSetting() { + return GlobalTemporaryTableMutationStrategy.class.getName(); + } } - @Override - protected Class getMultiTableInsertStrategyClass() { - return GlobalTemporaryTableInsertStrategy.class; + public static class QueryMultyTableInsertStrategyProvider + implements SettingProvider.Provider { + @Override + public String getSetting() { + return GlobalTemporaryTableInsertStrategy.class.getName(); + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/InlineMutationStrategyCompositeIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/InlineMutationStrategyCompositeIdTest.java index 557a8dff7d48..91c4d90599d6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/InlineMutationStrategyCompositeIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/InlineMutationStrategyCompositeIdTest.java @@ -4,23 +4,30 @@ */ package org.hibernate.orm.test.bulkid; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.query.sqm.mutation.internal.inline.InlineMutationStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableMutationStrategy; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SettingProvider; /** * @author Vlad Mihalcea */ +@ServiceRegistry( + settingProviders = { + @SettingProvider( + settingName = AvailableSettings.QUERY_MULTI_TABLE_MUTATION_STRATEGY, + provider = InlineMutationStrategyCompositeIdTest.QueryMultyTableMutationStrategyProvider.class + ), + } +) public class InlineMutationStrategyCompositeIdTest extends AbstractMutationStrategyCompositeIdTest { - @Override - protected Class getMultiTableMutationStrategyClass() { - return InlineMutationStrategy.class; + public static class QueryMultyTableMutationStrategyProvider + implements SettingProvider.Provider { + @Override + public String getSetting() { + return InlineMutationStrategy.class.getName(); + } } - @Override - protected Class getMultiTableInsertStrategyClass() { - // No inline strategy for insert - return null; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/InlineMutationStrategyIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/InlineMutationStrategyIdTest.java index 6eba68db499a..6204d3391dad 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/InlineMutationStrategyIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/InlineMutationStrategyIdTest.java @@ -4,23 +4,29 @@ */ package org.hibernate.orm.test.bulkid; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.query.sqm.mutation.internal.inline.InlineMutationStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableMutationStrategy; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SettingProvider; /** * @author Vlad Mihalcea */ +@ServiceRegistry( + settingProviders = { + @SettingProvider( + settingName = AvailableSettings.QUERY_MULTI_TABLE_MUTATION_STRATEGY, + provider = InlineMutationStrategyIdTest.QueryMultyTableMutationStrategyProvider.class + ) + } +) public class InlineMutationStrategyIdTest extends AbstractMutationStrategyIdTest { - @Override - protected Class getMultiTableMutationStrategyClass() { - return InlineMutationStrategy.class; - } - - @Override - protected Class getMultiTableInsertStrategyClass() { - // No inline strategy for insert - return null; + public static class QueryMultyTableMutationStrategyProvider + implements SettingProvider.Provider { + @Override + public String getSetting() { + return InlineMutationStrategy.class.getName(); + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/LocalTemporaryTableMutationStrategyCompositeIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/LocalTemporaryTableMutationStrategyCompositeIdTest.java index 20d7040bda96..611306a10a9e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/LocalTemporaryTableMutationStrategyCompositeIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/LocalTemporaryTableMutationStrategyCompositeIdTest.java @@ -4,23 +4,42 @@ */ package org.hibernate.orm.test.bulkid; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.query.sqm.mutation.internal.temptable.LocalTemporaryTableInsertStrategy; import org.hibernate.query.sqm.mutation.internal.temptable.LocalTemporaryTableMutationStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableMutationStrategy; import org.hibernate.testing.orm.junit.DialectFeatureChecks; import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SettingProvider; @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsLocalTemporaryTable.class) +@ServiceRegistry( + settingProviders = { + @SettingProvider( + settingName = AvailableSettings.QUERY_MULTI_TABLE_MUTATION_STRATEGY, + provider = LocalTemporaryTableMutationStrategyCompositeIdTest.QueryMultyTableMutationStrategyProvider.class + ), + @SettingProvider( + settingName = AvailableSettings.QUERY_MULTI_TABLE_INSERT_STRATEGY, + provider = LocalTemporaryTableMutationStrategyCompositeIdTest.QueryMultyTableInsertStrategyProvider.class + ) + } +) public class LocalTemporaryTableMutationStrategyCompositeIdTest extends AbstractMutationStrategyCompositeIdTest { - @Override - protected Class getMultiTableMutationStrategyClass() { - return LocalTemporaryTableMutationStrategy.class; + public static class QueryMultyTableMutationStrategyProvider + implements SettingProvider.Provider { + @Override + public String getSetting() { + return LocalTemporaryTableMutationStrategy.class.getName(); + } } - @Override - protected Class getMultiTableInsertStrategyClass() { - return LocalTemporaryTableInsertStrategy.class; + public static class QueryMultyTableInsertStrategyProvider + implements SettingProvider.Provider { + @Override + public String getSetting() { + return LocalTemporaryTableInsertStrategy.class.getName(); + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/LocalTemporaryTableMutationStrategyGeneratedIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/LocalTemporaryTableMutationStrategyGeneratedIdTest.java index cbed391044a6..ec12f5f7cbd5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/LocalTemporaryTableMutationStrategyGeneratedIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/LocalTemporaryTableMutationStrategyGeneratedIdTest.java @@ -4,16 +4,29 @@ */ package org.hibernate.orm.test.bulkid; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.query.sqm.mutation.internal.temptable.LocalTemporaryTableInsertStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy; import org.hibernate.testing.orm.junit.DialectFeatureChecks; import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SettingProvider; @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsLocalTemporaryTable.class) +@ServiceRegistry( + settingProviders = { + @SettingProvider( + settingName = AvailableSettings.QUERY_MULTI_TABLE_INSERT_STRATEGY, + provider = LocalTemporaryTableMutationStrategyGeneratedIdTest.QueryMultyTableInsertStrategyProvider.class + ) + } +) public class LocalTemporaryTableMutationStrategyGeneratedIdTest extends AbstractMutationStrategyGeneratedIdTest { - @Override - protected Class getMultiTableInsertStrategyClass() { - return LocalTemporaryTableInsertStrategy.class; + public static class QueryMultyTableInsertStrategyProvider + implements SettingProvider.Provider { + @Override + public String getSetting() { + return LocalTemporaryTableInsertStrategy.class.getName(); + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/LocalTemporaryTableMutationStrategyGeneratedIdWithOptimizerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/LocalTemporaryTableMutationStrategyGeneratedIdWithOptimizerTest.java index 36cc58ee164e..5894cc4fc6c0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/LocalTemporaryTableMutationStrategyGeneratedIdWithOptimizerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/LocalTemporaryTableMutationStrategyGeneratedIdWithOptimizerTest.java @@ -4,16 +4,30 @@ */ package org.hibernate.orm.test.bulkid; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.query.sqm.mutation.internal.temptable.LocalTemporaryTableInsertStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy; import org.hibernate.testing.orm.junit.DialectFeatureChecks; import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SettingProvider; @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsLocalTemporaryTable.class) -public class LocalTemporaryTableMutationStrategyGeneratedIdWithOptimizerTest extends AbstractMutationStrategyGeneratedIdWithOptimizerTest { +@ServiceRegistry( + settingProviders = { + @SettingProvider( + settingName = AvailableSettings.QUERY_MULTI_TABLE_INSERT_STRATEGY, + provider = LocalTemporaryTableMutationStrategyGeneratedIdWithOptimizerTest.QueryMultyTableInsertStrategyProvider.class + ) + } +) +public class LocalTemporaryTableMutationStrategyGeneratedIdWithOptimizerTest + extends AbstractMutationStrategyGeneratedIdWithOptimizerTest { - @Override - protected Class getMultiTableInsertStrategyClass() { - return LocalTemporaryTableInsertStrategy.class; + public static class QueryMultyTableInsertStrategyProvider + implements SettingProvider.Provider { + @Override + public String getSetting() { + return LocalTemporaryTableInsertStrategy.class.getName(); + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/LocalTemporaryTableMutationStrategyGeneratedIdentityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/LocalTemporaryTableMutationStrategyGeneratedIdentityTest.java index 0909b1ddb01e..bb03e1c93261 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/LocalTemporaryTableMutationStrategyGeneratedIdentityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/LocalTemporaryTableMutationStrategyGeneratedIdentityTest.java @@ -4,17 +4,31 @@ */ package org.hibernate.orm.test.bulkid; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.query.sqm.mutation.internal.temptable.LocalTemporaryTableInsertStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy; import org.hibernate.testing.orm.junit.DialectFeatureChecks; import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SettingProvider; @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsLocalTemporaryTable.class) @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsLocalTemporaryTableIdentity.class) -public class LocalTemporaryTableMutationStrategyGeneratedIdentityTest extends AbstractMutationStrategyGeneratedIdentityTest { +@ServiceRegistry( + settingProviders = { + @SettingProvider( + settingName = AvailableSettings.QUERY_MULTI_TABLE_INSERT_STRATEGY, + provider = LocalTemporaryTableMutationStrategyGeneratedIdentityTest.QueryMultyTableInsertStrategyProvider.class + ) + } +) +public class LocalTemporaryTableMutationStrategyGeneratedIdentityTest + extends AbstractMutationStrategyGeneratedIdentityTest { - @Override - protected Class getMultiTableInsertStrategyClass() { - return LocalTemporaryTableInsertStrategy.class; + public static class QueryMultyTableInsertStrategyProvider + implements SettingProvider.Provider { + @Override + public String getSetting() { + return LocalTemporaryTableInsertStrategy.class.getName(); + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/LocalTemporaryTableMutationStrategyIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/LocalTemporaryTableMutationStrategyIdTest.java index cb0c05f1bb83..579a8a6c1a50 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/LocalTemporaryTableMutationStrategyIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/LocalTemporaryTableMutationStrategyIdTest.java @@ -4,23 +4,43 @@ */ package org.hibernate.orm.test.bulkid; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.query.sqm.mutation.internal.temptable.LocalTemporaryTableInsertStrategy; import org.hibernate.query.sqm.mutation.internal.temptable.LocalTemporaryTableMutationStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableMutationStrategy; import org.hibernate.testing.orm.junit.DialectFeatureChecks; import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SettingProvider; @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsLocalTemporaryTable.class) +@ServiceRegistry( + settingProviders = { + @SettingProvider( + settingName = AvailableSettings.QUERY_MULTI_TABLE_MUTATION_STRATEGY, + provider = LocalTemporaryTableMutationStrategyIdTest.QueryMultyTableMutationStrategyProvider.class + ), + @SettingProvider( + settingName = AvailableSettings.QUERY_MULTI_TABLE_INSERT_STRATEGY, + provider = LocalTemporaryTableMutationStrategyIdTest.QueryMultyTableInsertStrategyProvider.class + ) + } +) public class LocalTemporaryTableMutationStrategyIdTest extends AbstractMutationStrategyIdTest { - @Override - protected Class getMultiTableMutationStrategyClass() { - return LocalTemporaryTableMutationStrategy.class; + public static class QueryMultyTableMutationStrategyProvider + implements SettingProvider.Provider { + @Override + public String getSetting() { + return LocalTemporaryTableMutationStrategy.class.getName(); + } } - @Override - protected Class getMultiTableInsertStrategyClass() { - return LocalTemporaryTableInsertStrategy.class; + public static class QueryMultyTableInsertStrategyProvider + implements SettingProvider.Provider { + @Override + public String getSetting() { + return LocalTemporaryTableInsertStrategy.class.getName(); + } } + } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/PersistentTableMutationStrategyCompositeIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/PersistentTableMutationStrategyCompositeIdTest.java index 7506ed4d7b02..d0b295625a6c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/PersistentTableMutationStrategyCompositeIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/PersistentTableMutationStrategyCompositeIdTest.java @@ -4,20 +4,39 @@ */ package org.hibernate.orm.test.bulkid; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.query.sqm.mutation.internal.temptable.PersistentTableInsertStrategy; import org.hibernate.query.sqm.mutation.internal.temptable.PersistentTableMutationStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableMutationStrategy; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SettingProvider; +@ServiceRegistry( + settingProviders = { + @SettingProvider( + settingName = AvailableSettings.QUERY_MULTI_TABLE_MUTATION_STRATEGY, + provider = PersistentTableMutationStrategyCompositeIdTest.QueryMultyTableMutationStrategyProvider.class + ), + @SettingProvider( + settingName = AvailableSettings.QUERY_MULTI_TABLE_INSERT_STRATEGY, + provider = PersistentTableMutationStrategyCompositeIdTest.QueryMultyTableInsertStrategyProvider.class + ) + } +) public class PersistentTableMutationStrategyCompositeIdTest extends AbstractMutationStrategyCompositeIdTest { - @Override - protected Class getMultiTableMutationStrategyClass() { - return PersistentTableMutationStrategy.class; + public static class QueryMultyTableMutationStrategyProvider + implements SettingProvider.Provider { + @Override + public String getSetting() { + return PersistentTableMutationStrategy.class.getName(); + } } - @Override - protected Class getMultiTableInsertStrategyClass() { - return PersistentTableInsertStrategy.class; + public static class QueryMultyTableInsertStrategyProvider + implements SettingProvider.Provider { + @Override + public String getSetting() { + return PersistentTableInsertStrategy.class.getName(); + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/PersistentTableMutationStrategyGeneratedIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/PersistentTableMutationStrategyGeneratedIdTest.java index 4ab9a01e48d1..81388f5a425b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/PersistentTableMutationStrategyGeneratedIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/PersistentTableMutationStrategyGeneratedIdTest.java @@ -4,13 +4,26 @@ */ package org.hibernate.orm.test.bulkid; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.query.sqm.mutation.internal.temptable.PersistentTableInsertStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SettingProvider; +@ServiceRegistry( + settingProviders = { + @SettingProvider( + settingName = AvailableSettings.QUERY_MULTI_TABLE_INSERT_STRATEGY, + provider = PersistentTableMutationStrategyGeneratedIdTest.QueryMultyTableInsertStrategyProvider.class + ) + } +) public class PersistentTableMutationStrategyGeneratedIdTest extends AbstractMutationStrategyGeneratedIdTest { - @Override - protected Class getMultiTableInsertStrategyClass() { - return PersistentTableInsertStrategy.class; + public static class QueryMultyTableInsertStrategyProvider + implements SettingProvider.Provider { + @Override + public String getSetting() { + return PersistentTableInsertStrategy.class.getName(); + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/PersistentTableMutationStrategyGeneratedIdWithOptimizerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/PersistentTableMutationStrategyGeneratedIdWithOptimizerTest.java index c1597a0f84c4..2719b24c86a3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/PersistentTableMutationStrategyGeneratedIdWithOptimizerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/PersistentTableMutationStrategyGeneratedIdWithOptimizerTest.java @@ -4,13 +4,27 @@ */ package org.hibernate.orm.test.bulkid; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.query.sqm.mutation.internal.temptable.PersistentTableInsertStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SettingProvider; -public class PersistentTableMutationStrategyGeneratedIdWithOptimizerTest extends AbstractMutationStrategyGeneratedIdWithOptimizerTest { +@ServiceRegistry( + settingProviders = { + @SettingProvider( + settingName = AvailableSettings.QUERY_MULTI_TABLE_INSERT_STRATEGY, + provider = PersistentTableMutationStrategyGeneratedIdWithOptimizerTest.QueryMultyTableInsertStrategyProvider.class + ) + } +) +public class PersistentTableMutationStrategyGeneratedIdWithOptimizerTest + extends AbstractMutationStrategyGeneratedIdWithOptimizerTest { - @Override - protected Class getMultiTableInsertStrategyClass() { - return PersistentTableInsertStrategy.class; + public static class QueryMultyTableInsertStrategyProvider + implements SettingProvider.Provider { + @Override + public String getSetting() { + return PersistentTableInsertStrategy.class.getName(); + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/PersistentTableMutationStrategyGeneratedIdentityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/PersistentTableMutationStrategyGeneratedIdentityTest.java index cd8b7c0f18d0..e7154cf6da56 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/PersistentTableMutationStrategyGeneratedIdentityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/PersistentTableMutationStrategyGeneratedIdentityTest.java @@ -4,16 +4,30 @@ */ package org.hibernate.orm.test.bulkid; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.query.sqm.mutation.internal.temptable.PersistentTableInsertStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy; import org.hibernate.testing.orm.junit.DialectFeatureChecks; import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SettingProvider; @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsIdentityColumns.class) -public class PersistentTableMutationStrategyGeneratedIdentityTest extends AbstractMutationStrategyGeneratedIdentityTest { +@ServiceRegistry( + settingProviders = { + @SettingProvider( + settingName = AvailableSettings.QUERY_MULTI_TABLE_INSERT_STRATEGY, + provider = PersistentTableMutationStrategyGeneratedIdentityTest.QueryMultyTableInsertStrategyProvider.class + ) + } +) +public class PersistentTableMutationStrategyGeneratedIdentityTest + extends AbstractMutationStrategyGeneratedIdentityTest { - @Override - protected Class getMultiTableInsertStrategyClass() { - return PersistentTableInsertStrategy.class; + public static class QueryMultyTableInsertStrategyProvider + implements SettingProvider.Provider { + @Override + public String getSetting() { + return PersistentTableInsertStrategy.class.getName(); + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/PersistentTableMutationStrategyIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/PersistentTableMutationStrategyIdTest.java index a6b5c769240a..17ad9f2d997d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/PersistentTableMutationStrategyIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/PersistentTableMutationStrategyIdTest.java @@ -4,20 +4,39 @@ */ package org.hibernate.orm.test.bulkid; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.query.sqm.mutation.internal.temptable.PersistentTableInsertStrategy; import org.hibernate.query.sqm.mutation.internal.temptable.PersistentTableMutationStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy; -import org.hibernate.query.sqm.mutation.spi.SqmMultiTableMutationStrategy; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SettingProvider; +@ServiceRegistry( + settingProviders = { + @SettingProvider( + settingName = AvailableSettings.QUERY_MULTI_TABLE_MUTATION_STRATEGY, + provider = PersistentTableMutationStrategyIdTest.QueryMultyTableMutationStrategyProvider.class + ), + @SettingProvider( + settingName = AvailableSettings.QUERY_MULTI_TABLE_INSERT_STRATEGY, + provider = PersistentTableMutationStrategyIdTest.QueryMultyTableInsertStrategyProvider.class + ) + } +) public class PersistentTableMutationStrategyIdTest extends AbstractMutationStrategyIdTest { - @Override - protected Class getMultiTableMutationStrategyClass() { - return PersistentTableMutationStrategy.class; + public static class QueryMultyTableMutationStrategyProvider + implements SettingProvider.Provider { + @Override + public String getSetting() { + return PersistentTableMutationStrategy.class.getName(); + } } - @Override - protected Class getMultiTableInsertStrategyClass() { - return PersistentTableInsertStrategy.class; + public static class QueryMultyTableInsertStrategyProvider + implements SettingProvider.Provider { + @Override + public String getSetting() { + return PersistentTableInsertStrategy.class.getName(); + } } } 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..975064c619a6 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 @@ -5,24 +5,24 @@ package org.hibernate.orm.test.cache.cid; import jakarta.persistence.SharedCacheMode; - +import org.hibernate.SessionFactory; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.AvailableSettings; - +import org.hibernate.testing.orm.junit.BaseUnitTest; 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 { +@BaseUnitTest +public class NonAggregatedCompositeIdCachingTest { @Test - @JiraKey( value = "HHH-9913" ) + @JiraKey(value = "HHH-9913") public void testNonAggregatedCompositeId() { // HHH-9913 reports a NPE when bootstrapping a SF with non-aggregated composite identifiers // in org.hibernate.cache.internal.CacheDataDescriptionImpl#decode @@ -30,13 +30,12 @@ public void testNonAggregatedCompositeId() { .applySetting( AvailableSettings.USE_SECOND_LEVEL_CACHE, true ) .build(); - try { - new MetadataSources( ssr ) - .addAnnotatedClass( It.class ) - .getMetadataBuilder() - .applySharedCacheMode( SharedCacheMode.ENABLE_SELECTIVE ) - .build() - .buildSessionFactory(); + try (SessionFactory sf = new MetadataSources( ssr ) + .addAnnotatedClass( It.class ) + .getMetadataBuilder() + .applySharedCacheMode( SharedCacheMode.ENABLE_SELECTIVE ) + .build() + .buildSessionFactory()) { } finally { StandardServiceRegistryBuilder.destroy( ssr ); @@ -44,19 +43,18 @@ public void testNonAggregatedCompositeId() { } @Test - @JiraKey( value = "HHH-9913" ) + @JiraKey(value = "HHH-9913") public void testNonAggregatedCompositeIdWithPkClass() { // HHH-9913 reports a NPE when bootstrapping a SF with non-aggregated composite identifiers // in org.hibernate.cache.internal.CacheDataDescriptionImpl#decode StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry(); - try { - new MetadataSources( ssr ) - .addAnnotatedClass( ItWithPkClass.class ) - .getMetadataBuilder() - .applySharedCacheMode( SharedCacheMode.ENABLE_SELECTIVE ) - .build() - .buildSessionFactory(); + try (SessionFactory sf = new MetadataSources( ssr ) + .addAnnotatedClass( ItWithPkClass.class ) + .getMetadataBuilder() + .applySharedCacheMode( SharedCacheMode.ENABLE_SELECTIVE ) + .build() + .buildSessionFactory()) { } finally { StandardServiceRegistryBuilder.destroy( ssr ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cdi/lifecycle/ExtendedBeanManagerNoCallbackTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cdi/lifecycle/ExtendedBeanManagerNoCallbackTest.java index 71b45ab8d656..705efb74afde 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cdi/lifecycle/ExtendedBeanManagerNoCallbackTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cdi/lifecycle/ExtendedBeanManagerNoCallbackTest.java @@ -4,21 +4,20 @@ */ package org.hibernate.orm.test.cdi.lifecycle; +import jakarta.enterprise.inject.spi.BeanManager; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import org.hibernate.SessionFactory; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.AvailableSettings; import org.hibernate.resource.beans.container.spi.ExtendedBeanManager; - import org.hibernate.testing.util.ServiceRegistryUtil; import org.junit.jupiter.api.Test; -import jakarta.enterprise.inject.spi.BeanManager; -import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.Id; -import jakarta.persistence.Table; - /** * We pass an ExtendedBeanManager but never "initialize" it. This might happen when the * environment provides an ExtendedBeanManager but there is no CDI needed for the app @@ -30,12 +29,11 @@ public void tryIt() { .applySetting( AvailableSettings.JAKARTA_CDI_BEAN_MANAGER, new ExtendedBeanManagerImpl() ) .build(); - try { - // this will trigger trying to locate IdentifierGeneratorFactory as a managed-bean - new MetadataSources( ssr ) - .addAnnotatedClass( TheEntity.class ) - .buildMetadata() - .buildSessionFactory(); + // this will trigger trying to locate IdentifierGeneratorFactory as a managed-bean + try (SessionFactory sf = new MetadataSources( ssr ) + .addAnnotatedClass( TheEntity.class ) + .buildMetadata() + .buildSessionFactory()) { } finally { StandardServiceRegistryBuilder.destroy( ssr ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cdi/lifecycle/ExtendedBeanManagerNotAvailableDuringTypeResolutionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cdi/lifecycle/ExtendedBeanManagerNotAvailableDuringTypeResolutionTest.java index b3808d1ab0ae..674eda99ab1b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cdi/lifecycle/ExtendedBeanManagerNotAvailableDuringTypeResolutionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cdi/lifecycle/ExtendedBeanManagerNotAvailableDuringTypeResolutionTest.java @@ -9,6 +9,7 @@ import java.io.InputStream; import java.nio.charset.StandardCharsets; +import org.hibernate.SessionFactory; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; @@ -36,11 +37,12 @@ public void tryIt() throws IOException { try { // this will trigger trying to locate MyEnumType as a managed-bean try (InputStream mappingInputStream = - new ByteArrayInputStream( TheEntity.ENTITY_DEFINITION.getBytes( StandardCharsets.UTF_8 ) ) ) { - new MetadataSources( ssr ) + new ByteArrayInputStream( TheEntity.ENTITY_DEFINITION.getBytes( StandardCharsets.UTF_8 ) )) { + try (SessionFactory sf = new MetadataSources( ssr ) .addInputStream( mappingInputStream ) .buildMetadata() - .buildSessionFactory(); + .buildSessionFactory()) { + } } } finally { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/AnnotationBinderTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/AnnotationBinderTest.java index 48eadea75891..16223c64011f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/AnnotationBinderTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/AnnotationBinderTest.java @@ -10,31 +10,31 @@ import org.hibernate.AnnotationException; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; +import org.hibernate.testing.orm.junit.BaseUnitTest; 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 junit.framework.TestCase.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * @author Dominique Toupin */ @JiraKey(value = "HHH-10456") +@BaseUnitTest public class AnnotationBinderTest { @Test public void testInvalidPrimaryKeyJoinColumn() { - try (StandardServiceRegistry serviceRegistry = ServiceRegistryUtil.serviceRegistry()) { - try { + AnnotationException annotationException = assertThrows( AnnotationException.class, () -> { + try (StandardServiceRegistry serviceRegistry = ServiceRegistryUtil.serviceRegistry()) { new MetadataSources( serviceRegistry ) .addAnnotatedClass( InvalidPrimaryKeyJoinColumnAnnotationEntity.class ) .buildMetadata(); - fail(); } - catch (AnnotationException ae) { - // expected! - } - } + } ); + assertThat( annotationException.getMessage() ).contains( "InvalidPrimaryKeyJoinColumnAnnotationEntity" ); } @Entity diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/CfgFilePropertyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/CfgFilePropertyTest.java index 3542680887a3..fa17101e1d14 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/CfgFilePropertyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/CfgFilePropertyTest.java @@ -4,42 +4,42 @@ */ package org.hibernate.orm.test.cfg; +import jakarta.persistence.EntityManagerFactory; +import org.hibernate.cfg.AvailableSettings; +import org.hibernate.testing.orm.junit.BaseUnitTest; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.util.ServiceRegistryUtil; +import org.junit.jupiter.api.Test; + import java.io.IOException; import java.net.URL; import java.util.Collections; import java.util.Enumeration; import java.util.Properties; import java.util.concurrent.atomic.AtomicReference; -import jakarta.persistence.Persistence; - -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 static jakarta.persistence.Persistence.createEntityManagerFactory; +import static org.assertj.core.api.Assertions.assertThat; import static org.hibernate.internal.util.ConfigHelper.findAsResource; -import static org.junit.Assert.assertNull; /** * @author Vlad Mihalcea */ @JiraKey(value = "HHH-13227") -public class CfgFilePropertyTest extends BaseUnitTestCase { +@BaseUnitTest +public class CfgFilePropertyTest { @Test - public void test() throws InterruptedException { + public void test() throws Exception { final AtomicReference exceptionHolder = new AtomicReference<>(); Thread thread = new Thread( () -> { - try { - final Properties props = new Properties(); - props.setProperty( AvailableSettings.CFG_XML_FILE, "/org/hibernate/orm/test/boot/cfgXml/hibernate.cfg.xml" ); - ServiceRegistryUtil.applySettings( props ); - - Persistence.createEntityManagerFactory( "ExcludeUnlistedClassesTest1", props ); + final Properties props = new Properties(); + props.setProperty( AvailableSettings.CFG_XML_FILE, + "/org/hibernate/orm/test/boot/cfgXml/hibernate.cfg.xml" ); + ServiceRegistryUtil.applySettings( props ); + try (EntityManagerFactory emF = createEntityManagerFactory( "ExcludeUnlistedClassesTest1", props )) { } catch (Exception e) { exceptionHolder.set( e ); @@ -50,18 +50,19 @@ public void test() throws InterruptedException { @Override protected Enumeration findResources(String name) throws IOException { return name.equals( "META-INF/persistence.xml" ) ? - Collections.enumeration( - Collections.singletonList( - findAsResource( "org/hibernate/jpa/test/persistenceunit/META-INF/persistence.xml" ) - ) - ) : - Collections.emptyEnumeration(); + Collections.enumeration( + Collections.singletonList( + findAsResource( + "org/hibernate/jpa/test/persistenceunit/META-INF/persistence.xml" ) + ) + ) : + Collections.emptyEnumeration(); } - } ); + } ); thread.start(); thread.join(); - assertNull( exceptionHolder.get() ); + assertThat( exceptionHolder.get() ).isNull(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/cache/DefaultCacheConcurrencyPropertyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/cache/DefaultCacheConcurrencyPropertyTest.java index 6581c8bf5400..a9eacfa5aea1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/cache/DefaultCacheConcurrencyPropertyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/cache/DefaultCacheConcurrencyPropertyTest.java @@ -8,7 +8,6 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; - import org.hibernate.annotations.Immutable; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; @@ -19,57 +18,50 @@ import org.hibernate.engine.config.spi.ConfigurationService; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.persister.entity.EntityPersister; - +import org.hibernate.testing.orm.junit.BaseUnitTest; 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; + +import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; /** * @author Gail Badner */ -public class DefaultCacheConcurrencyPropertyTest extends BaseUnitTestCase { +@BaseUnitTest +public class DefaultCacheConcurrencyPropertyTest { @Test - @JiraKey( value = "HHH-9763" ) + @JiraKey(value = "HHH-9763") public void testExplicitDefault() { - - final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( AvailableSettings.DEFAULT_CACHE_CONCURRENCY_STRATEGY, "read-only" ) - .build(); + StandardServiceRegistry ssr = null; try { - assertEquals( - "read-only", - ssr.getService( ConfigurationService.class ).getSettings().get( - AvailableSettings.DEFAULT_CACHE_CONCURRENCY_STRATEGY - ) - ); + ssr = ServiceRegistryUtil.serviceRegistryBuilder() + .applySetting( AvailableSettings.DEFAULT_CACHE_CONCURRENCY_STRATEGY, "read-only" ) + .build(); + assertThat( ssr.getService( ConfigurationService.class ).getSettings() + .get( AvailableSettings.DEFAULT_CACHE_CONCURRENCY_STRATEGY ) ) + .isEqualTo( "read-only" ); final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( ssr ) .addAnnotatedClass( TheEntity.class ) .buildMetadata(); - assertEquals( - AccessType.READ_ONLY, - metadata.getMetadataBuildingOptions().getMappingDefaults().getImplicitCacheAccessType() - ); - final SessionFactoryImplementor sf = (SessionFactoryImplementor) metadata.buildSessionFactory(); - try { + assertThat( metadata.getMetadataBuildingOptions().getMappingDefaults().getImplicitCacheAccessType() ) + .isEqualTo( AccessType.READ_ONLY ); + + try (SessionFactoryImplementor sf = metadata.buildSessionFactory()) { final EntityPersister persister = sf.getRuntimeMetamodels() .getMappingMetamodel() .getEntityDescriptor( TheEntity.class.getName() ); - assertTrue( persister.canReadFromCache() ); - assertTrue( persister.canWriteToCache() ); - assertNotNull( persister.getCacheAccessStrategy() ); - } - finally { - sf.close(); + assertThat( persister.canReadFromCache() ).isTrue(); + assertThat( persister.canWriteToCache() ).isTrue(); + assertThat( persister.getCacheAccessStrategy() ).isNotNull(); } } finally { - StandardServiceRegistryBuilder.destroy( ssr ); + if ( ssr != null ) { + StandardServiceRegistryBuilder.destroy( ssr ); + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/cache/DirectReferenceCacheEntriesTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/cache/DirectReferenceCacheEntriesTest.java index 6ddd085f28c7..972830b48c18 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/cache/DirectReferenceCacheEntriesTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/cache/DirectReferenceCacheEntriesTest.java @@ -7,37 +7,35 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; - import org.hibernate.annotations.Immutable; import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; - +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 static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; +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.BeforeAll; +import org.junit.jupiter.api.Test; /** * @author Andrea Boriero */ @JiraKey(value = "HHH-13665") -public class DirectReferenceCacheEntriesTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { TheEntity.class }; - } - - @Override - protected void configure(Configuration configuration) { - configuration.setProperty( AvailableSettings.USE_DIRECT_REFERENCE_CACHE_ENTRIES, true ); - } +@DomainModel( + annotatedClasses = { + DirectReferenceCacheEntriesTest.TheEntity.class + } +) +@SessionFactory +@ServiceRegistry( + settings = @Setting(name = AvailableSettings.USE_DIRECT_REFERENCE_CACHE_ENTRIES, value = "true") +) +public class DirectReferenceCacheEntriesTest { - @Before - public void setUp() { - doInHibernate( this::sessionFactory, session -> { + @BeforeAll + public void setUp(SessionFactoryScope scope) { + scope.inTransaction( session -> { TheEntity theEntity = new TheEntity(); theEntity.setId( 1L ); session.persist( theEntity ); @@ -45,10 +43,10 @@ public void setUp() { } @Test - public void testSelectANonCachablenEntity() { - doInHibernate( this::sessionFactory, session -> { - session.createQuery( "select t from TheEntity t", TheEntity.class ).getResultList(); - } ); + public void testSelectANonCachablenEntity(SessionFactoryScope scope) { + scope.inTransaction( session -> + session.createQuery( "select t from TheEntity t", TheEntity.class ).getResultList() + ); } @Entity(name = "TheEntity") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/persister/PersisterClassProviderTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/persister/PersisterClassProviderTest.java index 9d0cef4fbe1b..82f8a23b44df 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/persister/PersisterClassProviderTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/persister/PersisterClassProviderTest.java @@ -11,22 +11,22 @@ import org.hibernate.internal.SessionFactoryRegistry; import org.hibernate.persister.spi.PersisterClassResolver; import org.hibernate.service.ServiceRegistry; - -import org.hibernate.testing.junit4.BaseUnitTestCase; +import org.hibernate.testing.orm.junit.BaseUnitTest; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Emmanuel Bernard */ -public class PersisterClassProviderTest extends BaseUnitTestCase { +@BaseUnitTest +public class PersisterClassProviderTest { + @Test public void testPersisterClassProvider() { - + org.hibernate.internal.SessionFactoryRegistry.INSTANCE.clearRegistrations(); Configuration cfg = new Configuration(); cfg.addAnnotatedClass( Gate.class ); ServiceRegistry serviceRegistry = ServiceRegistryUtil.serviceRegistryBuilder() @@ -51,9 +51,9 @@ public void testPersisterClassProvider() { try { sessionFactory = cfg.buildSessionFactory( serviceRegistry ); sessionFactory.close(); - fail("The entity persister should be overridden"); + fail( "The entity persister should be overridden" ); } - catch ( MappingException e ) { + catch (MappingException e) { // expected assertThat( e.getCause() ).isInstanceOf( GoofyException.class ); } @@ -61,7 +61,7 @@ public void testPersisterClassProvider() { StandardServiceRegistryBuilder.destroy( serviceRegistry ); } - assertFalse( SessionFactoryRegistry.INSTANCE.hasRegistrations() ); + assertThat( SessionFactoryRegistry.INSTANCE.hasRegistrations() ).isFalse(); cfg = new Configuration(); cfg.addAnnotatedClass( Portal.class ); @@ -73,9 +73,9 @@ public void testPersisterClassProvider() { try { sessionFactory = cfg.buildSessionFactory( serviceRegistry ); sessionFactory.close(); - fail("The collection persister should be overridden but not the entity persister"); + fail( "The collection persister should be overridden but not the entity persister" ); } - catch ( MappingException e ) { + catch (MappingException e) { // expected assertThat( e.getCause() ).isInstanceOf( GoofyException.class ); } @@ -94,9 +94,9 @@ public void testPersisterClassProvider() { try { sessionFactory = cfg.buildSessionFactory( serviceRegistry ); sessionFactory.close(); - fail("The entity persisters should be overridden in a class hierarchy"); + fail( "The entity persisters should be overridden in a class hierarchy" ); } - catch ( MappingException e ) { + catch (MappingException e) { // expected assertThat( e.getCause() ).isInstanceOf( GoofyException.class ); } @@ -104,6 +104,6 @@ public void testPersisterClassProvider() { StandardServiceRegistryBuilder.destroy( serviceRegistry ); } - assertFalse( SessionFactoryRegistry.INSTANCE.hasRegistrations() ); + assertThat( SessionFactoryRegistry.INSTANCE.hasRegistrations() ).isFalse(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/set/SetElementNullBasicTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/set/SetElementNullBasicTest.java index 9e1c988f3434..ad2f6ca46e40 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/set/SetElementNullBasicTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/set/SetElementNullBasicTest.java @@ -4,9 +4,6 @@ */ package org.hibernate.orm.test.collection.set; -import java.util.HashSet; -import java.util.List; -import java.util.Set; import jakarta.persistence.CollectionTable; import jakarta.persistence.ElementCollection; import jakarta.persistence.Entity; @@ -14,31 +11,34 @@ import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.Table; - +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.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; /** * @author Gail Badner */ -@JiraKey( value = "HHH-11881") -public class SetElementNullBasicTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - AnEntity.class - }; - } +@JiraKey(value = "HHH-11881") +@DomainModel( + annotatedClasses = { + SetElementNullBasicTest.AnEntity.class + + } +) +@SessionFactory +public class SetElementNullBasicTest { @Test - public void testPersistNullValue() { - int entityId = doInHibernate( - this::sessionFactory, session -> { + public void testPersistNullValue(SessionFactoryScope scope) { + int entityId = scope.fromTransaction( session -> { AnEntity e = new AnEntity(); e.aCollection.add( null ); session.persist( e ); @@ -46,49 +46,44 @@ public void testPersistNullValue() { } ); - doInHibernate( - this::sessionFactory, session -> { + scope.inTransaction( session -> { AnEntity e = session.get( AnEntity.class, entityId ); - assertEquals( 0, e.aCollection.size() ); - assertEquals( 0, getCollectionElementRows( entityId ).size() ); + assertThat( e.aCollection.size() ).isEqualTo( 0 ); + assertThat( getCollectionElementRows( entityId, scope ) ).hasSize( 0 ); session.remove( e ); } ); } @Test - public void addNullValue() { - int entityId = doInHibernate( - this::sessionFactory, session -> { + public void addNullValue(SessionFactoryScope scope) { + int entityId = scope.fromTransaction( session -> { AnEntity e = new AnEntity(); session.persist( e ); return e.id; } ); - doInHibernate( - this::sessionFactory, session -> { + scope.inTransaction( session -> { AnEntity e = session.get( AnEntity.class, entityId ); - assertEquals( 0, e.aCollection.size() ); - assertEquals( 0, getCollectionElementRows( entityId ).size() ); + assertThat( e.aCollection.size() ).isEqualTo( 0 ); + assertThat( getCollectionElementRows( entityId, scope ) ).hasSize( 0 ); e.aCollection.add( null ); } ); - doInHibernate( - this::sessionFactory, session -> { + scope.inTransaction( session -> { AnEntity e = session.get( AnEntity.class, entityId ); - assertEquals( 0, e.aCollection.size() ); - assertEquals( 0, getCollectionElementRows( entityId ).size() ); + assertThat( e.aCollection.size() ).isEqualTo( 0 ); + assertThat( getCollectionElementRows( entityId, scope ) ).hasSize( 0 ); session.remove( e ); } ); } @Test - public void testUpdateNonNullValueToNull() { - int entityId = doInHibernate( - this::sessionFactory, session -> { + public void testUpdateNonNullValueToNull(SessionFactoryScope scope) { + int entityId = scope.fromTransaction( session -> { AnEntity e = new AnEntity(); e.aCollection.add( "def" ); session.persist( e ); @@ -96,45 +91,41 @@ public void testUpdateNonNullValueToNull() { } ); - doInHibernate( - this::sessionFactory, session -> { + scope.inTransaction( session -> { AnEntity e = session.get( AnEntity.class, entityId ); - assertEquals( 1, e.aCollection.size() ); - assertEquals( 1, getCollectionElementRows( entityId ).size() ); + assertThat( e.aCollection.size() ).isEqualTo( 1 ); + assertThat( getCollectionElementRows( entityId, scope ) ).hasSize( 1 ); e.aCollection.remove( "def" ); e.aCollection.add( null ); } ); - doInHibernate( - this::sessionFactory, session -> { + scope.inTransaction( session -> { AnEntity e = session.get( AnEntity.class, entityId ); - assertEquals( 0, e.aCollection.size() ); - assertEquals( 0, getCollectionElementRows( entityId ).size() ); + assertThat( e.aCollection.size() ).isEqualTo( 0 ); + assertThat( getCollectionElementRows( entityId, scope ) ).hasSize( 0 ); session.remove( e ); } ); } - private List getCollectionElementRows(int id) { - return doInHibernate( - this::sessionFactory, session -> { - return session.createNativeQuery( - "SELECT aCollection FROM AnEntity_aCollection where AnEntity_id = " + id - ).list(); - } + private List getCollectionElementRows(int id, SessionFactoryScope scope) { + return scope.fromSession( session -> + session.createNativeQuery( + "SELECT aCollection FROM AnEntity_aCollection where AnEntity_id = " + id + ).list() ); } - @Entity(name="AnEntity") - @Table(name="AnEntity") + @Entity(name = "AnEntity") + @Table(name = "AnEntity") public static class AnEntity { @Id @GeneratedValue private int id; @ElementCollection - @CollectionTable(name = "AnEntity_aCollection", joinColumns = { @JoinColumn( name = "AnEntity_id" ) }) + @CollectionTable(name = "AnEntity_aCollection", joinColumns = {@JoinColumn(name = "AnEntity_id")}) private Set aCollection = new HashSet<>(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/comments/UseSqlCommentTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/comments/UseSqlCommentTest.java index 3a128c943b46..9d1dbad0b866 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/comments/UseSqlCommentTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/comments/UseSqlCommentTest.java @@ -4,8 +4,6 @@ */ package org.hibernate.orm.test.comments; -import java.util.List; -import java.util.Map; import jakarta.persistence.EntityManager; import jakarta.persistence.TypedQuery; import jakarta.persistence.criteria.CompoundSelection; @@ -13,36 +11,34 @@ import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Path; import jakarta.persistence.criteria.Root; - import org.hibernate.cfg.AvailableSettings; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -import org.junit.Before; -import org.junit.Test; +import java.util.List; -import static org.hamcrest.CoreMatchers.is; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Andrea Boriero */ -public class UseSqlCommentTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { TestEntity.class, TestEntity2.class }; - } - - @Override - protected void addMappings(Map settings) { - settings.put( AvailableSettings.USE_SQL_COMMENTS, "true" ); - settings.put( AvailableSettings.FORMAT_SQL, "false" ); - } - - @Before - public void setUp() { - doInJPA( this::entityManagerFactory, entityManager -> { +@Jpa( + annotatedClasses = { + TestEntity.class, TestEntity2.class + }, + properties = { + @Setting(name = AvailableSettings.USE_SQL_COMMENTS, value = "true"), + @Setting(name = AvailableSettings.FORMAT_SQL, value = "false"), + } +) +public class UseSqlCommentTest { + + @BeforeAll + public void setUp(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { TestEntity testEntity = new TestEntity(); testEntity.setId( "test1" ); testEntity.setValue( "value1" ); @@ -56,22 +52,22 @@ public void setUp() { } @Test - public void testIt() { + public void testIt(EntityManagerFactoryScope scope) { String appendLiteral = "*/select id as col_0_0_,value as col_1_0_ from testEntity2 where 1=1 or id=?--/*"; - doInJPA( this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { List result = findUsingQuery( "test1", appendLiteral, entityManager ); TestEntity test1 = result.get( 0 ); - assertThat( test1.getValue(), is( appendLiteral ) ); + assertThat( test1.getValue() ).isEqualTo( appendLiteral ); } ); - doInJPA( this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { List result = findUsingCriteria( "test1", appendLiteral, entityManager ); TestEntity test1 = result.get( 0 ); - assertThat( test1.getValue(), is( appendLiteral ) ); + assertThat( test1.getValue() ).isEqualTo( appendLiteral ); } ); } @@ -99,8 +95,8 @@ public List findUsingQuery(String id, String appendLiteral, EntityMa TypedQuery query = entityManager.createQuery( "select new " + TestEntity.class.getName() + "(id, '" - + appendLiteral.replace( "'", "''" ) - + "') from TestEntity where id=:where_id", + + appendLiteral.replace( "'", "''" ) + + "') from TestEntity where id=:where_id", TestEntity.class ); query.setParameter( "where_id", id ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/component/cascading/collection/CascadeToComponentCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/component/cascading/collection/CascadeToComponentCollectionTest.java index 953c80be339e..4105ffc72d5c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/component/cascading/collection/CascadeToComponentCollectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/component/cascading/collection/CascadeToComponentCollectionTest.java @@ -4,114 +4,103 @@ */ package org.hibernate.orm.test.component.cascading.collection; -import java.util.Locale; - -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.Test; -import org.hibernate.Session; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import java.util.Locale; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Steve Ebersole */ -public class CascadeToComponentCollectionTest extends BaseCoreFunctionalTestCase { - - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } - - @Override - public String[] getMappings() { - return new String[] { "component/cascading/collection/Mappings.hbm.xml" }; - } +@DomainModel( + xmlMappings = "org/hibernate/orm/test/component/cascading/collection/Mappings.hbm.xml" +) +@SessionFactory +public class CascadeToComponentCollectionTest { @Test - public void testMerging() { + public void testMerging(SessionFactoryScope scope) { // step1, we create a definition with one value - Session session = openSession(); - session.beginTransaction(); - Definition definition = new Definition(); - Value value1 = new Value( definition ); - value1.getLocalizedStrings().addString( new Locale( "en_US" ), "hello" ); - session.persist( definition ); - session.getTransaction().commit(); - session.close(); + Definition d = new Definition(); + + scope.inTransaction( session -> { + Value value1 = new Value( d ); + value1.getLocalizedStrings().addString( new Locale( "en_US" ), "hello" ); + session.persist( d ); + } + ); // step2, we verify that the definition has one value; then we detach it - session = openSession(); - session.beginTransaction(); - definition = ( Definition ) session.get( Definition.class, definition.getId() ); - assertEquals( 1, definition.getValues().size() ); - session.getTransaction().commit(); - session.close(); + Definition def = scope.fromTransaction( session -> { + Definition definition = session.find( Definition.class, d.getId() ); + assertThat( definition.getValues() ).hasSize( 1 ); + return definition; + } + ); // step3, we add a new value during detachment - Value value2 = new Value( definition ); + Value value2 = new Value( def ); value2.getLocalizedStrings().addString( new Locale( "es" ), "hola" ); // step4 we merge the definition - session = openSession(); - session.beginTransaction(); - session.merge( definition ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( session -> + session.merge( def ) + ); // step5, final test - session = openSession(); - session.beginTransaction(); - definition = ( Definition ) session.get( Definition.class, definition.getId() ); - assertEquals( 2, definition.getValues().size() ); - for ( Object o : definition.getValues() ) { - assertEquals( 1, ((Value) o).getLocalizedStrings().getStringsCopy().size() ); - } - session.getTransaction().commit(); - session.close(); + scope.inTransaction( session -> { + Definition definition = session.find( Definition.class, d.getId() ); + assertThat( definition.getValues() ).hasSize( 2 ); + for ( Value o : definition.getValues() ) { + assertThat( o.getLocalizedStrings().getStringsCopy() ).hasSize( 1 ); + } + } + ); } @SuppressWarnings("unused") @Test - public void testMergingOriginallyNullComponent() { + public void testMergingOriginallyNullComponent(SessionFactoryScope scope) { // step1, we create a definition with one value, but with a null component - Session session = openSession(); - session.beginTransaction(); - Definition definition = new Definition(); - Value value1 = new Value( definition ); - session.persist( definition ); - session.getTransaction().commit(); - session.close(); + Definition d = new Definition(); + scope.inTransaction( session -> { + Value value1 = new Value( d ); + session.persist( d ); + } + ); // step2, we verify that the definition has one value; then we detach it - session = openSession(); - session.beginTransaction(); - definition = ( Definition ) session.get( Definition.class, definition.getId() ); - assertEquals( 1, definition.getValues().size() ); - session.getTransaction().commit(); - session.close(); + Definition def = scope.fromTransaction( session -> { + Definition definition = session.find( Definition.class, d.getId() ); + assertThat( definition.getValues() ).hasSize( 1 ); + return definition; + } + ); // step3, we add a new value during detachment - ( ( Value ) definition.getValues().iterator().next() ).getLocalizedStrings().addString( new Locale( "en_US" ), "hello" ); - Value value2 = new Value( definition ); + def.getValues().iterator().next().getLocalizedStrings() + .addString( new Locale( "en_US" ), "hello" ); + Value value2 = new Value( def ); value2.getLocalizedStrings().addString( new Locale( "es" ), "hola" ); // step4 we merge the definition - session = openSession(); - session.beginTransaction(); - session.merge( definition ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( session -> + session.merge( def ) + ); // step5, final test - session = openSession(); - session.beginTransaction(); - definition = ( Definition ) session.get( Definition.class, definition.getId() ); - assertEquals( 2, definition.getValues().size() ); - for ( Object o : definition.getValues() ) { - assertEquals( 1, ((Value) o).getLocalizedStrings().getStringsCopy().size() ); - } - session.getTransaction().commit(); - session.close(); + scope.inTransaction( + session -> { + Definition definition = session.find( Definition.class, def.getId() ); + assertThat( definition.getValues().size() ).isEqualTo( 2 ); + for ( Value o : definition.getValues() ) { + assertThat( o.getLocalizedStrings().getStringsCopy() ).hasSize( 1 ); + } + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/component/cascading/collection/Definition.java b/hibernate-core/src/test/java/org/hibernate/orm/test/component/cascading/collection/Definition.java index 546b27977b6f..c48db96c605d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/component/cascading/collection/Definition.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/component/cascading/collection/Definition.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.component.cascading.collection; + import java.util.HashSet; import java.util.Set; @@ -13,7 +14,7 @@ */ public class Definition { private Long id; - private Set values = new HashSet(); + private Set values = new HashSet<>(); public Long getId() { return id; @@ -23,11 +24,11 @@ public void setId(Long id) { this.id = id; } - public Set getValues() { + public Set getValues() { return values; } - public void setValues(Set values) { + public void setValues(Set values) { this.values = values; } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/component/cascading/collection/LocalizedStrings.java b/hibernate-core/src/test/java/org/hibernate/orm/test/component/cascading/collection/LocalizedStrings.java index afc8277a15d7..88a4ebef91f4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/component/cascading/collection/LocalizedStrings.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/component/cascading/collection/LocalizedStrings.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.component.cascading.collection; + import java.util.HashMap; import java.util.Locale; import java.util.Map; @@ -13,7 +14,7 @@ * @author Steve Ebersole */ public class LocalizedStrings { - private Map strings = new HashMap(); + private Map strings = new HashMap<>(); public void addString(Locale locale, String value) { strings.put( locale, value ); @@ -23,7 +24,7 @@ public String getString(Locale locale) { return ( String ) strings.get( locale ); } - public Map getStringsCopy() { + public Map getStringsCopy() { return java.util.Collections.unmodifiableMap( strings ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/component/cascading/toone/CascadeToComponentAssociationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/component/cascading/toone/CascadeToComponentAssociationTest.java index 260a728baf1c..61ec1f98c9f2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/component/cascading/toone/CascadeToComponentAssociationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/component/cascading/toone/CascadeToComponentAssociationTest.java @@ -4,72 +4,62 @@ */ package org.hibernate.orm.test.component.cascading.toone; -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.Test; -import org.hibernate.Session; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Steve Ebersole */ -public class CascadeToComponentAssociationTest extends BaseCoreFunctionalTestCase { - - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } - - @Override - public String[] getMappings() { - return new String[] { "component/cascading/toone/Mappings.hbm.xml" }; - } +@DomainModel( + xmlMappings = "org/hibernate/orm/test/component/cascading/toone/Mappings.hbm.xml/" +) +@SessionFactory +public class CascadeToComponentAssociationTest { @Test - public void testMerging() { + public void testMerging(SessionFactoryScope scope) { // step1, we create a document with owner - Session session = openSession(); - session.beginTransaction(); - User user = new User(); - Document document = new Document(); - document.setOwner( user ); - session.persist( document ); - session.getTransaction().commit(); - session.close(); + Document doc = new Document(); + scope.inTransaction( session -> { + User user = new User(); + doc.setOwner( user ); + session.persist( doc ); + } + ); // step2, we verify that the document has owner and that owner has no personal-info; then we detach - session = openSession(); - session.beginTransaction(); - document = ( Document ) session.get( Document.class, document.getId() ); - assertNotNull( document.getOwner() ); - assertNull( document.getOwner().getPersonalInfo() ); - session.getTransaction().commit(); - session.close(); + Document d = scope.fromTransaction( session -> { + Document document = session.find( Document.class, doc.getId() ); + assertThat( document.getOwner() ).isNotNull(); + assertThat( document.getOwner().getPersonalInfo() ).isNull(); + return document; + } + ); // step3, try to specify the personal-info during detachment Address addr = new Address(); addr.setStreet1( "123 6th St" ); addr.setCity( "Austin" ); addr.setState( "TX" ); - document.getOwner().setPersonalInfo( new PersonalInfo( addr ) ); + d.getOwner().setPersonalInfo( new PersonalInfo( addr ) ); // step4 we merge the document - session = openSession(); - session.beginTransaction(); - session.merge( document ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( session -> + session.merge( d ) + ); // step5, final test - session = openSession(); - session.beginTransaction(); - document = ( Document ) session.get( Document.class, document.getId() ); - assertNotNull( document.getOwner() ); - assertNotNull( document.getOwner().getPersonalInfo() ); - assertNotNull( document.getOwner().getPersonalInfo().getHomeAddress() ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( + session -> { + Document document = session.find( Document.class, d.getId() ); + assertThat( document.getOwner() ).isNotNull(); + assertThat( document.getOwner().getPersonalInfo() ).isNotNull(); + assertThat( document.getOwner().getPersonalInfo().getHomeAddress() ).isNotNull(); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/compositeelement/Child.java b/hibernate-core/src/test/java/org/hibernate/orm/test/compositeelement/Child.java index 9312a335db74..08213fdfc38a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/compositeelement/Child.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/compositeelement/Child.java @@ -70,6 +70,6 @@ public int getBioLength() { return bioLength; } public void setBioLength(Integer bioLength) { - this.bioLength = bioLength==null ? 0 : bioLength.intValue(); + this.bioLength = bioLength==null ? 0 : bioLength; } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/compositeelement/CompositeElementTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/compositeelement/CompositeElementTest.java index 33412ea7875f..d9791e5d4cc2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/compositeelement/CompositeElementTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/compositeelement/CompositeElementTest.java @@ -4,94 +4,77 @@ */ package org.hibernate.orm.test.compositeelement; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.boot.Metadata; -import org.hibernate.mapping.Collection; -import org.hibernate.mapping.Component; -import org.hibernate.mapping.Formula; - -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; - import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Root; +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 static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Gavin King */ -public class CompositeElementTest extends BaseNonConfigCoreFunctionalTestCase { - - @Override - protected String getBaseForMappings() { - return ""; - } - - @Override - public String[] getMappings() { - return new String[] { "org/hibernate/orm/test/compositeelement/Parent.hbm.xml" }; - } - - @Override - protected void afterMetadataBuilt(Metadata metadata) { - Collection children = metadata.getCollectionBinding( Parent.class.getName() + ".children" ); - Component childComponents = ( Component ) children.getElement(); - Formula f = ( Formula ) childComponents.getProperty( "bioLength" ).getValue().getSelectables().get( 0 ); - -// SQLFunction lengthFunction = metadata.getDatabase().getJdbcEnvironment().getDialect().getFunctions().get( "length" ); -// if ( lengthFunction != null ) { -// ArrayList args = new ArrayList(); -// args.add( "bio" ); -// f.setFormula( lengthFunction.render( StandardBasicTypes.INTEGER, args, null ) ); -// } +@DomainModel( + xmlMappings = "org/hibernate/orm/test/compositeelement/Parent.hbm.xml" +) +@SessionFactory +public class CompositeElementTest { + + @AfterEach + public void tearDown(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Test - public void testHandSQL() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Child c = new Child( "Child One" ); - Parent p = new Parent( "Parent" ); - p.getChildren().add( c ); - c.setParent( p ); - s.persist( p ); - s.flush(); - - p.getChildren().remove( c ); - c.setParent( null ); - s.flush(); - - p.getChildren().add( c ); - c.setParent( p ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - s.createQuery( "select distinct p from Parent p join p.children c where c.name like 'Child%'" ).uniqueResult(); - s.clear(); - s.createQuery( "select new Child(c.name) from Parent p left outer join p.children c where c.name like 'Child%'" ) - .uniqueResult(); - s.clear(); - //s.createQuery("select c from Parent p left outer join p.children c where c.name like 'Child%'").uniqueResult(); //we really need to be able to do this! - s.clear(); - p = ( Parent ) s.createQuery( "from Parent p left join fetch p.children" ).uniqueResult(); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - s.remove( p ); - t.commit(); - s.close(); + public void testHandSQL(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Child c = new Child( "Child One" ); + Parent p = new Parent( "Parent" ); + p.getChildren().add( c ); + c.setParent( p ); + session.persist( p ); + session.flush(); + + p.getChildren().remove( c ); + c.setParent( null ); + session.flush(); + + p.getChildren().add( c ); + c.setParent( p ); + } + ); + + Parent parent = scope.fromTransaction( session -> { + session.createQuery( "select distinct p from Parent p join p.children c where c.name like 'Child%'", + Parent.class ) + .uniqueResult(); + session.clear(); + session.createQuery( + "select new Child(c.name) from Parent p left outer join p.children c where c.name like 'Child%'", + Child.class ) + .uniqueResult(); + session.clear(); + //s.createQuery("select c from Parent p left outer join p.children c where c.name like 'Child%'").uniqueResult(); //we really need to be able to do this! + session.clear(); + return session.createQuery( "from Parent p left join fetch p.children", Parent.class ) + .uniqueResult(); + } + ); + + scope.inTransaction( + session -> + session.remove( parent ) + ); } @Test - public void testCustomColumnReadAndWrite() { - inTransaction( s -> { + public void testCustomColumnReadAndWrite(SessionFactoryScope scope) { + scope.inTransaction( s -> { Child c = new Child( "Child One" ); c.setPosition( 1 ); Parent p = new Parent( "Parent" ); @@ -102,38 +85,38 @@ public void testCustomColumnReadAndWrite() { // Oracle returns BigDecimaal while other dialects return Integer; // casting to Number so it works on all dialects - Number sqlValue = ( (Number) s.createNativeQuery( - "select child_position from ParentChild c where c.name='Child One'" ) - .uniqueResult() ); - assertEquals( 0, sqlValue.intValue() ); + Number sqlValue = ((Number) s.createNativeQuery( + "select child_position from ParentChild c where c.name='Child One'" ) + .uniqueResult()); + assertThat( sqlValue.intValue() ).isEqualTo( 0 ); - Integer hqlValue = (Integer) s.createQuery( - "select c.position from Parent p join p.children c where p.name='Parent'" ) + Integer hqlValue = s.createQuery( + "select c.position from Parent p join p.children c where p.name='Parent'", Integer.class ) .uniqueResult(); - assertEquals( 1, hqlValue.intValue() ); + assertThat( hqlValue ).isEqualTo( 1 ); // p = (Parent) s.createCriteria( Parent.class ).add( Restrictions.eq( "name", "Parent" ) ).uniqueResult(); CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); CriteriaQuery criteria = criteriaBuilder.createQuery( Parent.class ); Root root = criteria.from( Parent.class ); - criteria.where( criteriaBuilder.equal( root.get( "name" ),"Parent" ) ); + criteria.where( criteriaBuilder.equal( root.get( "name" ), "Parent" ) ); p = s.createQuery( criteria ).uniqueResult(); - c = (Child) p.getChildren().iterator().next(); - assertEquals( 1, c.getPosition() ); + c = p.getChildren().iterator().next(); + assertThat( c.getPosition() ).isEqualTo( 1 ); p = s.createQuery( "from Parent p join p.children c where c.position = 1", Parent.class ).uniqueResult(); - c = (Child) p.getChildren().iterator().next(); - assertEquals( 1, c.getPosition() ); + c = p.getChildren().iterator().next(); + assertThat( c.getPosition() ).isEqualTo( 1 ); c.setPosition( 2 ); s.flush(); - sqlValue = ( (Number) s.createNativeQuery( - "select child_position from ParentChild c where c.name='Child One'" ) - .uniqueResult() ); - assertEquals( 1, sqlValue.intValue() ); + sqlValue = ((Number) s.createNativeQuery( + "select child_position from ParentChild c where c.name='Child One'" ) + .uniqueResult()); + assertThat( sqlValue.intValue() ).isEqualTo( 1 ); s.remove( p ); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/compositeelement/Parent.java b/hibernate-core/src/test/java/org/hibernate/orm/test/compositeelement/Parent.java index b7b6f60ec033..32cdb4818764 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/compositeelement/Parent.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/compositeelement/Parent.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.compositeelement; + import java.util.Collection; import java.util.HashSet; @@ -12,7 +13,7 @@ public class Parent { private Long id; private String name; - private Collection children = new HashSet(); + private Collection children = new HashSet<>(); Parent() {} public Parent(String name) { this.name = name; @@ -20,13 +21,13 @@ public Parent(String name) { /** * @return Returns the children. */ - public Collection getChildren() { + public Collection getChildren() { return children; } /** * @param children The children to set. */ - public void setChildren(Collection children) { + public void setChildren(Collection children) { this.children = children; } /** diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/connection/ConnectionCreatorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/connection/ConnectionCreatorTest.java index 9b6e70a3dbd6..46f895a039f6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/connection/ConnectionCreatorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/connection/ConnectionCreatorTest.java @@ -4,16 +4,9 @@ */ package org.hibernate.orm.test.connection; -import java.sql.Connection; -import java.sql.Driver; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - import org.hibernate.boot.registry.BootstrapServiceRegistry; import org.hibernate.boot.registry.StandardServiceInitiator; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.registry.internal.BootstrapServiceRegistryImpl; import org.hibernate.boot.registry.internal.StandardServiceRegistryImpl; import org.hibernate.dialect.H2Dialect; @@ -25,43 +18,58 @@ import org.hibernate.exception.JDBCConnectionException; import org.hibernate.service.Service; import org.hibernate.service.internal.ProvidedService; -import org.hibernate.testing.junit4.BaseUnitTestCase; +import org.hibernate.testing.orm.junit.BaseUnitTest; import org.hibernate.testing.orm.junit.JiraKey; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import java.sql.Connection; +import java.sql.Driver; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * @author Steve Ebersole */ -public class ConnectionCreatorTest extends BaseUnitTestCase { +@BaseUnitTest +public class ConnectionCreatorTest { + @Test - @JiraKey(value = "HHH-8621" ) + @JiraKey(value = "HHH-8621") public void testBadUrl() throws Exception { - DriverConnectionCreator connectionCreator = new DriverConnectionCreator( - (Driver) Class.forName( "org.h2.Driver" ).newInstance(), - CCTStandardServiceRegistryImpl.create( - true, - new BootstrapServiceRegistryImpl(), - Collections.emptyList(), - Collections.emptyList(), - Collections.emptyMap() - ), - "jdbc:h2:mem:test-bad-urls;nosuchparam=saywhat;DB_CLOSE_ON_EXIT=FALSE", - new Properties(), - false, - null, - null + CCTStandardServiceRegistryImpl serviceRegistry = CCTStandardServiceRegistryImpl.create( + true, + new BootstrapServiceRegistryImpl(), + Collections.emptyList(), + Collections.emptyList(), + Collections.emptyMap() ); - try { - Connection conn = connectionCreator.createConnection(); - conn.close(); - fail( "Expecting the bad Connection URL to cause an exception" ); + DriverConnectionCreator connectionCreator = new DriverConnectionCreator( + (Driver) Class.forName( "org.h2.Driver" ).newInstance(), + serviceRegistry, + "jdbc:h2:mem:test-bad-urls;nosuchparam=saywhat;DB_CLOSE_ON_EXIT=FALSE", + new Properties(), + false, + null, + null + ); + + assertThrows( JDBCConnectionException.class, () -> { + try (Connection conn = connectionCreator.createConnection()) { + + } + }, + "Expecting the bad Connection URL to cause an exception" ); } - catch (JDBCConnectionException expected) { + finally { + StandardServiceRegistryBuilder.destroy(serviceRegistry); } + } private final static class CCTStandardServiceRegistryImpl extends StandardServiceRegistryImpl { @@ -72,16 +80,17 @@ private CCTStandardServiceRegistryImpl( Map configurationValues) { super( autoCloseRegistry, bootstrapServiceRegistry, configurationValues ); } + @Override @SuppressWarnings("unchecked") public R getService(Class serviceRole) { if ( JdbcServices.class.equals( serviceRole ) ) { // return a new, not fully initialized JdbcServicesImpl - JdbcServicesImpl jdbcServices = new JdbcServicesImpl(this); + JdbcServicesImpl jdbcServices = new JdbcServicesImpl( this ); jdbcServices.configure( new HashMap<>() ); return (R) jdbcServices; } - if( JdbcEnvironment.class.equals( serviceRole ) ){ + if ( JdbcEnvironment.class.equals( serviceRole ) ) { return (R) new JdbcEnvironmentImpl( this, new H2Dialect() ); } return super.getService( serviceRole ); @@ -92,9 +101,10 @@ public static CCTStandardServiceRegistryImpl create( BootstrapServiceRegistry bootstrapServiceRegistry, List> serviceInitiators, List> providedServices, - Map configurationValues) { + Map configurationValues) { - CCTStandardServiceRegistryImpl instance = new CCTStandardServiceRegistryImpl( autoCloseRegistry, bootstrapServiceRegistry, configurationValues ); + CCTStandardServiceRegistryImpl instance = new CCTStandardServiceRegistryImpl( autoCloseRegistry, + bootstrapServiceRegistry, configurationValues ); instance.initialize(); instance.applyServiceRegistrations( serviceInitiators, providedServices ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/connections/AggressiveReleaseTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/connections/AggressiveReleaseTest.java index d71ad571dcb3..ef6b361349ad 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/connections/AggressiveReleaseTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/connections/AggressiveReleaseTest.java @@ -4,30 +4,33 @@ */ package org.hibernate.orm.test.connections; -import java.sql.Connection; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - import org.hibernate.ScrollableResults; import org.hibernate.Session; -import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Environment; import org.hibernate.dialect.H2Dialect; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; +import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.internal.util.SerializationHelper; import org.hibernate.resource.jdbc.spi.PhysicalConnectionHandlingMode; -import org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorBuilderImpl; import org.hibernate.stat.Statistics; - -import org.hibernate.testing.RequiresDialect; import org.hibernate.testing.jta.TestingJtaBootstrap; import org.hibernate.testing.jta.TestingJtaPlatformImpl; -import org.junit.Test; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.hibernate.testing.orm.junit.SettingConfiguration; +import org.hibernate.testing.orm.junit.SettingProvider; +import org.junit.jupiter.api.Test; + +import java.sql.Connection; +import java.util.ArrayList; +import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hibernate.cfg.TransactionSettings.ENABLE_LAZY_LOAD_NO_TRANS; +import static org.hibernate.cfg.TransactionSettings.TRANSACTION_COORDINATOR_STRATEGY; +import static org.junit.jupiter.api.Assertions.fail; /** * Implementation of AggressiveReleaseTest. @@ -35,22 +38,31 @@ * @author Steve Ebersole */ @RequiresDialect(H2Dialect.class) +@ServiceRegistry( + settings = { + @Setting(name = Environment.GENERATE_STATISTICS, value = "true"), + @Setting(name = Environment.STATEMENT_BATCH_SIZE, value = "0"), + @Setting(name = TRANSACTION_COORDINATOR_STRATEGY, value = "jta"), + @Setting(name = ENABLE_LAZY_LOAD_NO_TRANS, value = "true") + }, + settingProviders = @SettingProvider( + settingName = Environment.CONNECTION_HANDLING, + provider = AggressiveReleaseTest.ConnectionmHandlingProvider.class + ), + settingConfigurations = @SettingConfiguration(configurer = TestingJtaBootstrap.class) +) public class AggressiveReleaseTest extends ConnectionManagementTestCase { - @Override - protected void addSettings(Map settings) { - super.addSettings( settings ); - - TestingJtaBootstrap.prepare( settings ); -// settings.put( Environment.TRANSACTION_STRATEGY, CMTTransactionFactory.class.getName() ); - settings.put( AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY, JtaTransactionCoordinatorBuilderImpl.class.getName() ); - settings.put( Environment.CONNECTION_HANDLING, PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_RELEASE_AFTER_STATEMENT.toString() ); - settings.put( Environment.GENERATE_STATISTICS, "true" ); - settings.put( Environment.STATEMENT_BATCH_SIZE, "0" ); + + public static class ConnectionmHandlingProvider implements SettingProvider.Provider { + @Override + public String getSetting() { + return PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_RELEASE_AFTER_STATEMENT.toString(); + } } @Override - protected Session getSessionUnderTest() throws Throwable { - return openSession(); + protected Session getSessionUnderTest(SessionFactoryScope scope) { + return scope.getSessionFactory().openSession(); } @Override @@ -70,10 +82,11 @@ protected void done() throws Throwable { // Some additional tests specifically for the aggressive-release functionality... @Test - public void testSerializationOnAfterStatementAggressiveRelease() throws Throwable { + public void testSerializationOnAfterStatementAggressiveRelease(SessionFactoryScope scope) throws Throwable { prepare(); + Session s = null; try { - Session s = getSessionUnderTest(); + s = getSessionUnderTest( scope ); Silly silly = new Silly( "silly" ); s.persist( silly ); @@ -86,134 +99,157 @@ public void testSerializationOnAfterStatementAggressiveRelease() throws Throwabl s.remove( silly ); s.flush(); - release( s ); } finally { + release( s, scope ); done(); } } @Test - public void testSerializationFailsOnAfterStatementAggressiveReleaseWithOpenResources() throws Throwable { + public void testSerializationFailsOnAfterStatementAggressiveReleaseWithOpenResources(SessionFactoryScope scope) + throws Throwable { prepare(); - Session s = getSessionUnderTest(); + try (Session s = getSessionUnderTest( scope )) { - Silly silly = new Silly( "silly" ); - s.persist( silly ); - - // this should cause the CM to obtain a connection, and then release it - s.flush(); + Silly silly = new Silly( "silly" ); + s.persist( silly ); - // both scroll() and iterate() cause batching to hold on - // to resources, which should make aggressive-release not release - // the connection (and thus cause serialization to fail) - try (ScrollableResults sr = s.createQuery( "from Silly" ).scroll()) { - sr.next(); + // this should cause the CM to obtain a connection, and then release it + s.flush(); - try { - SerializationHelper.serialize( s ); - fail( "Serialization allowed on connected session; or aggressive release released connection with open resources" ); - } - catch (IllegalStateException e) { - // expected behavior + // both scroll() and iterate() cause batching to hold on + // to resources, which should make aggressive-release not release + // the connection (and thus cause serialization to fail) + try (ScrollableResults sr = s.createQuery( "from Silly", Silly.class ).scroll()) { + sr.next(); + + try { + SerializationHelper.serialize( s ); + fail( "Serialization allowed on connected session; or aggressive release released connection with open resources" ); + } + catch (IllegalStateException e) { + // expected behavior + } + + // getting the first row only because SybaseASE15Dialect throws NullPointerException + // if data is not read before closing the ResultSet + sr.next(); + + // Closing the ScrollableResults does currently force batching to + // aggressively release the connection } + SerializationHelper.serialize( s ); - // getting the first row only because SybaseASE15Dialect throws NullPointerException - // if data is not read before closing the ResultSet - sr.next(); - - // Closing the ScrollableResults does currently force batching to - // aggressively release the connection + s.remove( silly ); + s.flush(); } - SerializationHelper.serialize( s ); - - s.remove( silly ); - s.flush(); - - release( s ); done(); } @Test - public void testQueryScrolling() throws Throwable { + public void testQueryScrolling(SessionFactoryScope scope) throws Throwable { prepare(); - Session s = getSessionUnderTest(); - Silly silly = new Silly( "silly" ); - s.persist( silly ); - s.flush(); - - try (ScrollableResults sr = s.createQuery( "from Silly" ).scroll()) { - assertTrue( sr.next() ); - Silly silly2 = (Silly) sr.get(); - assertEquals( silly, silly2 ); - } + Session s = null; + try { + s = getSessionUnderTest(scope); + Silly silly = new Silly( "silly" ); + s.persist( silly ); + s.flush(); - try (ScrollableResults sr = s.createQuery( "from Silly" ).scroll(); - ScrollableResults sr2 = s.createQuery( "from Silly where name = 'silly'" ).scroll()) { - assertTrue( sr.next() ); - assertEquals( silly, sr.get() ); - assertTrue( sr2.next() ); - assertEquals( silly, sr2.get() ); - } + try (ScrollableResults sr = s.createQuery( "from Silly", Silly.class ).scroll()) { + assertThat( sr.next() ).isTrue(); + Silly silly2 = sr.get(); + assertThat( silly2 ).isEqualTo( silly ); + } - s.remove( silly ); - s.flush(); + try (ScrollableResults sr = s.createQuery( "from Silly", Silly.class ).scroll(); + ScrollableResults sr2 = s.createQuery( "from Silly where name = 'silly'", Silly.class ) + .scroll()) { + assertThat( sr.next() ).isTrue(); + assertThat( sr.get() ).isEqualTo( silly ); + assertThat( sr2.next() ).isTrue(); + assertThat( sr2.get() ).isEqualTo( silly ); + } - release( s ); - done(); + s.remove( silly ); + s.flush(); + } + finally { + release( s, scope ); + done(); + } } @Test - public void testSuppliedConnection() throws Throwable { + public void testSuppliedConnection(SessionFactoryScope scope) throws Throwable { + SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); prepare(); - Connection originalConnection = sessionFactory().getServiceRegistry().getService( ConnectionProvider.class ).getConnection(); - Session session = sessionFactory().withOptions().connection( originalConnection ).openSession(); - - Silly silly = new Silly( "silly" ); - session.persist( silly ); + Connection originalConnection = sessionFactory.getServiceRegistry().getService( ConnectionProvider.class ) + .getConnection(); + Session session = null; + try { + session = sessionFactory.withOptions().connection( originalConnection ).openSession(); - // this will cause the connection manager to cycle through the aggressive release logic; - // it should not release the connection since we explicitly suplied it ourselves. - session.flush(); - assertTrue( session.isConnected() ); + Silly silly = new Silly( "silly" ); + session.persist( silly ); - session.remove( silly ); - session.flush(); + // this will cause the connection manager to cycle through the aggressive release logic; + // it should not release the connection since we explicitly suplied it ourselves. + session.flush(); + assertThat( session.isConnected() ).isTrue(); - release( session ); - done(); + session.remove( silly ); + session.flush(); + } + finally { + release( session, scope ); + done(); + sessionFactory.getServiceRegistry().getService( ConnectionProvider.class ) + .closeConnection( originalConnection ); - sessionFactory().getServiceRegistry().getService( ConnectionProvider.class ).closeConnection( originalConnection ); + } } @Test - public void testConnectionMaintanenceDuringFlush() throws Throwable { - final Statistics statistics = sessionFactory().getStatistics(); + public void testConnectionMaintanenceDuringFlush(SessionFactoryScope scope) throws Throwable { + SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); + + final Statistics statistics = sessionFactory.getStatistics(); prepare(); - Session s = getSessionUnderTest(); - List entities = new ArrayList(); - for ( int i = 0; i < 10; i++ ) { - Other other = new Other( "other-" + i ); - Silly silly = new Silly( "silly-" + i, other ); - entities.add( silly ); - s.persist( silly ); - } - s.flush(); + Session s = null; + try { + s = getSessionUnderTest( scope ); + + List entities = new ArrayList<>(); + for ( int i = 0; i < 10; i++ ) { + Other other = new Other( "other-" + i ); + Silly silly = new Silly( "silly-" + i, other ); + entities.add( silly ); + s.persist( silly ); + } + s.flush(); - for ( Silly silly : entities ) { - silly.setName( "new-" + silly.getName() ); - silly.getOther().setName( "new-" + silly.getOther().getName() ); + for ( Silly silly : entities ) { + silly.setName( "new-" + silly.getName() ); + silly.getOther().setName( "new-" + silly.getOther().getName() ); + } + long initialCount = statistics.getConnectCount(); + s.flush(); + assertThat( statistics.getConnectCount() ) + .describedAs( "connection not maintained through flush" ) + .isEqualTo( initialCount + 1 ); + + s.createMutationQuery( "delete from Silly" ).executeUpdate(); + s.createMutationQuery( "delete from Other" ).executeUpdate(); + s.getTransaction().commit(); } - long initialCount = statistics.getConnectCount(); - s.flush(); - assertEquals( "connection not maintained through flush", initialCount + 1, statistics.getConnectCount() ); - - s.createQuery( "delete from Silly" ).executeUpdate(); - s.createQuery( "delete from Other" ).executeUpdate(); - s.getTransaction().commit(); - release( s ); - done(); + finally { + release( s, scope ); + done(); + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/connections/BasicConnectionProviderTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/connections/BasicConnectionProviderTest.java index 1882a63b940d..c0b672a4580b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/connections/BasicConnectionProviderTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/connections/BasicConnectionProviderTest.java @@ -4,14 +4,15 @@ */ package org.hibernate.orm.test.connections; -import java.util.Map; - import org.hibernate.Session; import org.hibernate.cfg.Environment; import org.hibernate.dialect.H2Dialect; import org.hibernate.resource.jdbc.spi.PhysicalConnectionHandlingMode; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.SettingProvider; -import org.hibernate.testing.RequiresDialect; /** * Implementation of BasicConnectionProviderTest. @@ -19,10 +20,24 @@ * @author Steve Ebersole */ @RequiresDialect(H2Dialect.class) +@ServiceRegistry( + settingProviders = @SettingProvider( + settingName = Environment.CONNECTION_HANDLING, + provider = BasicConnectionProviderTest.ConnectionmHandlingProvider.class + ) +) public class BasicConnectionProviderTest extends ConnectionManagementTestCase { + + public static class ConnectionmHandlingProvider implements SettingProvider.Provider { + @Override + public String getSetting() { + return PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_RELEASE_AFTER_STATEMENT.toString(); + } + } + @Override - protected Session getSessionUnderTest() { - Session session = openSession(); + protected Session getSessionUnderTest(SessionFactoryScope scope) { + Session session = scope.getSessionFactory().openSession(); session.beginTransaction(); return session; } @@ -30,10 +45,4 @@ protected Session getSessionUnderTest() { @Override protected void reconnect(Session session) { } - - @Override - protected void addSettings(Map settings) { - super.addSettings( settings ); - settings.put( Environment.CONNECTION_HANDLING, PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_HOLD.toString() ); - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/connections/ConnectionManagementTestCase.java b/hibernate-core/src/test/java/org/hibernate/orm/test/connections/ConnectionManagementTestCase.java index 8cb84c4963d0..9699327d2aa5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/connections/ConnectionManagementTestCase.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/connections/ConnectionManagementTestCase.java @@ -9,13 +9,13 @@ import org.hibernate.Transaction; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.internal.util.SerializationHelper; +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.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.fail; /** * Common test cases relating to session management and how the sessions @@ -30,17 +30,11 @@ * @author Steve Ebersole */ -public abstract class ConnectionManagementTestCase extends BaseNonConfigCoreFunctionalTestCase { - - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } - - @Override - public final String[] getMappings() { - return new String[] { "connections/Silly.hbm.xml" }; - } +@DomainModel( + xmlMappings = "org/hibernate/orm/test/connections/Silly.hbm.xml" +) +@SessionFactory +public abstract class ConnectionManagementTestCase { // hooks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -70,7 +64,7 @@ protected void done() throws Throwable { * @return The session to be used in testing. * @throws Throwable Indicates problems building a test session fixture. */ - protected abstract Session getSessionUnderTest() throws Throwable; + protected abstract Session getSessionUnderTest(SessionFactoryScope scope) throws Throwable; /** * Used to release a {@link #getSessionUnderTest fixture session}. @@ -79,18 +73,18 @@ protected void done() throws Throwable { * * @param session The session to be released. */ - protected void release(Session session) { + protected void release(Session session, SessionFactoryScope scope) { if ( session != null && session.isOpen() ) { try { session.close(); } - catch( Throwable ignore ) { + catch (Throwable ignore) { } } } - protected void disconnect(Session session) throws Throwable { - ((SessionImplementor)session).getJdbcCoordinator().getLogicalConnection().manualDisconnect(); + protected void disconnect(Session session) { + ((SessionImplementor) session).getJdbcCoordinator().getLogicalConnection().manualDisconnect(); } /** @@ -127,12 +121,12 @@ protected void checkDeserializedState(Session session) { * be allowed to serialize. */ @Test - public final void testConnectedSerialization() throws Throwable { + public final void testConnectedSerialization(SessionFactoryScope scope) throws Throwable { prepare(); - Session sessionUnderTest = getSessionUnderTest(); + Session sessionUnderTest = getSessionUnderTest( scope ); // force the connection to be retained - try (ScrollableResults sr = sessionUnderTest.createQuery( "from Silly" ).scroll()) { + try (ScrollableResults sr = sessionUnderTest.createQuery( "from Silly", Silly.class ).scroll()) { sr.next(); try { @@ -144,7 +138,7 @@ public final void testConnectedSerialization() throws Throwable { // expected behaviour } finally { - release( sessionUnderTest ); + release( sessionUnderTest, scope ); done(); } } @@ -155,37 +149,43 @@ public final void testConnectedSerialization() throws Throwable { * be allowed to serialize. */ @Test - public final void testEnabledFilterSerialization() throws Throwable { + public final void testEnabledFilterSerialization(SessionFactoryScope scope) throws Throwable { prepare(); - Session sessionUnderTest = getSessionUnderTest(); - - sessionUnderTest.enableFilter( "nameIsNull" ); - assertNotNull( sessionUnderTest.getEnabledFilter( "nameIsNull" ) ); - disconnect( sessionUnderTest ); - assertNotNull( sessionUnderTest.getEnabledFilter( "nameIsNull" ) ); - - byte[] bytes = SerializationHelper.serialize( sessionUnderTest ); - checkSerializedState( sessionUnderTest ); - assertNotNull( sessionUnderTest.getEnabledFilter( "nameIsNull" ) ); - reconnect( sessionUnderTest ); - assertNotNull( sessionUnderTest.getEnabledFilter( "nameIsNull" ) ); - disconnect( sessionUnderTest ); - assertNotNull( sessionUnderTest.getEnabledFilter( "nameIsNull" ) ); - - Session s2 = ( Session ) SerializationHelper.deserialize( bytes ); - checkDeserializedState( s2 ); - assertNotNull( sessionUnderTest.getEnabledFilter( "nameIsNull" ) ); - reconnect( s2 ); - assertNotNull( sessionUnderTest.getEnabledFilter( "nameIsNull" ) ); - - disconnect( s2 ); - assertNotNull( sessionUnderTest.getEnabledFilter( "nameIsNull" ) ); - reconnect( s2 ); - assertNotNull( sessionUnderTest.getEnabledFilter( "nameIsNull" ) ); - - release( sessionUnderTest ); - release( s2 ); - done(); + Session sessionUnderTest = null; + Session s2 = null; + try { + sessionUnderTest = getSessionUnderTest( scope ); + + sessionUnderTest.enableFilter( "nameIsNull" ); + assertThat( sessionUnderTest.getEnabledFilter( "nameIsNull" ) ).isNotNull(); + disconnect( sessionUnderTest ); + assertThat( sessionUnderTest.getEnabledFilter( "nameIsNull" ) ).isNotNull(); + + byte[] bytes = SerializationHelper.serialize( sessionUnderTest ); + checkSerializedState( sessionUnderTest ); + assertThat( sessionUnderTest.getEnabledFilter( "nameIsNull" ) ).isNotNull(); + reconnect( sessionUnderTest ); + assertThat( sessionUnderTest.getEnabledFilter( "nameIsNull" ) ).isNotNull(); + disconnect( sessionUnderTest ); + assertThat( sessionUnderTest.getEnabledFilter( "nameIsNull" ) ).isNotNull(); + + s2 = (Session) SerializationHelper.deserialize( bytes ); + checkDeserializedState( s2 ); + assertThat( sessionUnderTest.getEnabledFilter( "nameIsNull" ) ).isNotNull(); + reconnect( s2 ); + assertThat( sessionUnderTest.getEnabledFilter( "nameIsNull" ) ).isNotNull(); + + disconnect( s2 ); + assertThat( sessionUnderTest.getEnabledFilter( "nameIsNull" ) ).isNotNull(); + reconnect( s2 ); + assertThat( sessionUnderTest.getEnabledFilter( "nameIsNull" ) ).isNotNull(); + + } + finally { + release( sessionUnderTest, scope ); + release( s2, scope ); + done(); + } } /** @@ -193,17 +193,21 @@ public final void testEnabledFilterSerialization() throws Throwable { * to serialize. */ @Test - public final void testManualDisconnectedSerialization() throws Throwable { + public final void testManualDisconnectedSerialization(SessionFactoryScope scope) throws Throwable { prepare(); - Session sessionUnderTest = getSessionUnderTest(); - - disconnect( sessionUnderTest ); + Session sessionUnderTest = null; + try { + sessionUnderTest = getSessionUnderTest( scope ); - SerializationHelper.serialize( sessionUnderTest ); - checkSerializedState( sessionUnderTest ); + disconnect( sessionUnderTest ); - release( sessionUnderTest ); - done(); + SerializationHelper.serialize( sessionUnderTest ); + checkSerializedState( sessionUnderTest ); + } + finally { + release( sessionUnderTest, scope ); + done(); + } } /** @@ -211,25 +215,31 @@ public final void testManualDisconnectedSerialization() throws Throwable { * expected in the given environment. */ @Test - public final void testManualDisconnectChain() throws Throwable { + public final void testManualDisconnectChain(SessionFactoryScope scope) throws Throwable { prepare(); - Session sessionUnderTest = getSessionUnderTest(); + Session sessionUnderTest = null; + Session s2 = null; + try { + sessionUnderTest = getSessionUnderTest( scope ); - disconnect( sessionUnderTest ); + disconnect( sessionUnderTest ); - byte[] bytes = SerializationHelper.serialize( sessionUnderTest ); - checkSerializedState( sessionUnderTest ); - Session s2 = ( Session ) SerializationHelper.deserialize( bytes ); - checkDeserializedState( s2 ); + byte[] bytes = SerializationHelper.serialize( sessionUnderTest ); + checkSerializedState( sessionUnderTest ); + s2 = (Session) SerializationHelper.deserialize( bytes ); + checkDeserializedState( s2 ); - reconnect( s2 ); + reconnect( s2 ); - disconnect( s2 ); - reconnect( s2 ); + disconnect( s2 ); + reconnect( s2 ); + } + finally { + release( sessionUnderTest, scope ); + release( s2, scope ); + done(); + } - release( sessionUnderTest ); - release( s2 ); - done(); } /** @@ -239,25 +249,30 @@ public final void testManualDisconnectChain() throws Throwable { * prior to disconnecting. */ @Test - public final void testManualDisconnectWithOpenResources() throws Throwable { + public final void testManualDisconnectWithOpenResources(SessionFactoryScope scope) throws Throwable { prepare(); - Session sessionUnderTest = getSessionUnderTest(); + Session sessionUnderTest = null; + try { + sessionUnderTest = getSessionUnderTest( scope ); - Silly silly = new Silly( "tester" ); - sessionUnderTest.persist( silly ); - sessionUnderTest.flush(); + Silly silly = new Silly( "tester" ); + sessionUnderTest.persist( silly ); + sessionUnderTest.flush(); - try (ScrollableResults sr = sessionUnderTest.createQuery( "from Silly" ).scroll()) { + try (ScrollableResults sr = sessionUnderTest.createQuery( "from Silly", Silly.class ).scroll()) { - disconnect( sessionUnderTest ); - SerializationHelper.serialize( sessionUnderTest ); - checkSerializedState( sessionUnderTest ); + disconnect( sessionUnderTest ); + SerializationHelper.serialize( sessionUnderTest ); + checkSerializedState( sessionUnderTest ); - reconnect( sessionUnderTest ); - sessionUnderTest.remove( silly ); - sessionUnderTest.flush(); + reconnect( sessionUnderTest ); + sessionUnderTest.remove( silly ); + sessionUnderTest.flush(); - release( sessionUnderTest ); + } + } + finally { + release( sessionUnderTest, scope ); done(); } } @@ -267,22 +282,22 @@ public final void testManualDisconnectWithOpenResources() throws Throwable { * scenarios. */ @Test - public void testBasicSessionUsage() throws Throwable { + public void testBasicSessionUsage(SessionFactoryScope scope) throws Throwable { prepare(); Session s = null; Transaction txn = null; try { - s = getSessionUnderTest(); + s = getSessionUnderTest( scope ); txn = s.beginTransaction(); - s.createQuery( "from Silly" ).list(); + s.createQuery( "from Silly", Silly.class ).list(); txn.commit(); } - catch( Throwable t ) { + catch (Throwable t) { if ( txn != null ) { try { txn.rollback(); } - catch( Throwable ignore ) { + catch (Throwable ignore) { } } } @@ -291,7 +306,7 @@ public void testBasicSessionUsage() throws Throwable { try { s.close(); } - catch( Throwable ignore ) { + catch (Throwable ignore) { } } } @@ -302,15 +317,15 @@ public void testBasicSessionUsage() throws Throwable { * Test that session-closed protections work properly in all environments. */ @Test - public void testSessionClosedProtections() throws Throwable { + public void testSessionClosedProtections(SessionFactoryScope scope) throws Throwable { prepare(); - Session s = getSessionUnderTest(); - release( s ); + Session s = getSessionUnderTest( scope ); + release( s, scope ); done(); - assertFalse( s.isOpen() ); - assertFalse( s.isConnected() ); - assertNotNull( s.getStatistics() ); - assertNotNull( s.toString() ); + assertThat( s.isOpen() ).isFalse(); + assertThat( s.isConnected() ).isFalse(); + assertThat( s.getStatistics() ).isNotNull(); + assertThat( s.toString() ).isNotNull(); try { s.createQuery( "from Silly" ).list(); @@ -325,7 +340,7 @@ public void testSessionClosedProtections() throws Throwable { // you should be able to access the transaction on a closed EM. that is a change from what we used to do. we changed it // to better align with JPA. Transaction tran = s.getTransaction(); - assertNotNull( tran ); + assertThat( tran ).isNotNull(); // Session implements both AutoCloseable and Closeable // Closable requires an idempotent behaviour, a closed resource must not throw an Exception diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/connections/CurrentSessionConnectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/connections/CurrentSessionConnectionTest.java index f697140d23a5..f0ce652242ef 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/connections/CurrentSessionConnectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/connections/CurrentSessionConnectionTest.java @@ -6,8 +6,8 @@ import org.hibernate.Session; import org.hibernate.dialect.H2Dialect; - -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.SessionFactoryScope; /** * Implementation of CurrentSessionConnectionTest. @@ -17,12 +17,12 @@ @RequiresDialect(H2Dialect.class) public class CurrentSessionConnectionTest extends AggressiveReleaseTest { @Override - protected Session getSessionUnderTest() throws Throwable { - return sessionFactory().getCurrentSession(); + protected Session getSessionUnderTest(SessionFactoryScope scope) { + return scope.getSessionFactory().getCurrentSession(); } @Override - protected void release(Session session) { + protected void release(Session session, SessionFactoryScope scope) { // do nothing, txn synch should release session as part of current-session definition } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/connections/SuppliedConnectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/connections/SuppliedConnectionTest.java index b698765a2946..53b00027908f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/connections/SuppliedConnectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/connections/SuppliedConnectionTest.java @@ -4,28 +4,31 @@ */ package org.hibernate.orm.test.connections; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Map; - import org.hibernate.Session; import org.hibernate.cfg.Environment; import org.hibernate.dialect.H2Dialect; import org.hibernate.engine.jdbc.connections.internal.UserSuppliedConnectionProviderImpl; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.hibernate.engine.spi.SessionImplementor; +import org.hibernate.orm.test.util.DdlTransactionIsolatorTestingImpl; import org.hibernate.resource.jdbc.spi.PhysicalConnectionHandlingMode; +import org.hibernate.service.spi.ServiceRegistryImplementor; import org.hibernate.service.spi.Stoppable; +import org.hibernate.testing.env.ConnectionProviderBuilder; +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.SettingProvider; import org.hibernate.tool.schema.internal.SchemaCreatorImpl; import org.hibernate.tool.schema.internal.SchemaDropperImpl; import org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; -import org.hibernate.testing.AfterClassOnce; -import org.hibernate.testing.BeforeClassOnce; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.env.ConnectionProviderBuilder; -import org.hibernate.orm.test.util.DdlTransactionIsolatorTestingImpl; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; /** * Implementation of SuppliedConnectionTest. @@ -33,93 +36,76 @@ * @author Steve Ebersole */ @RequiresDialect(H2Dialect.class) +@SessionFactory( + exportSchema = false +) +@ServiceRegistry( + settingProviders = { + @SettingProvider( + settingName = Environment.CONNECTION_HANDLING, + provider = SuppliedConnectionTest.ConnectionHandlingProvider.class + ), + @SettingProvider( + settingName = Environment.CONNECTION_PROVIDER, + provider = SuppliedConnectionTest.ConnectionProviderProvider.class + ), + @SettingProvider( + settingName = Environment.USE_SCROLLABLE_RESULTSET, + provider = SuppliedConnectionTest.UseScrollableResultSetProvider.class + ), + } +) public class SuppliedConnectionTest extends ConnectionManagementTestCase { - private ConnectionProvider cp; + private static ConnectionProvider cp = ConnectionProviderBuilder.buildConnectionProvider(); private Connection connectionUnderTest; - @BeforeClassOnce - @SuppressWarnings("unused") - private void prepareConnectionProvider() { - cp = ConnectionProviderBuilder.buildConnectionProvider(); - } - - @AfterClassOnce - @SuppressWarnings("unused") - private void releaseConnectionProvider() { - try { - if ( cp instanceof Stoppable ) { - ( ( Stoppable ) cp ).stop(); - } - cp = null; - } - catch( Throwable ignore ) { + public static class ConnectionHandlingProvider implements SettingProvider.Provider { + @Override + public String getSetting() { + return PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_HOLD.toString(); } } - @Override - protected Session getSessionUnderTest() throws Throwable { - connectionUnderTest = cp.getConnection(); - Session session = sessionFactory().withOptions().connection( connectionUnderTest ).openSession(); - session.beginTransaction(); - return session; - } - - @Override - protected void reconnect(Session session) { - ((SessionImplementor)session).getJdbcCoordinator().getLogicalConnection().manualReconnect( connectionUnderTest ); - } - - @Override - protected void done() throws Throwable { - cp.closeConnection( connectionUnderTest ); + public static class ConnectionProviderProvider implements SettingProvider.Provider { + @Override + public String getSetting() { + return UserSuppliedConnectionProviderImpl.class.getName(); + } } - @Override - protected void addSettings(Map settings) { - super.addSettings( settings ); - - settings.put( Environment.CONNECTION_HANDLING, PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_HOLD.toString() ); - settings.put( Environment.CONNECTION_PROVIDER, UserSuppliedConnectionProviderImpl.class.getName() ); - - Connection connection; - try { - connection = cp.getConnection(); + public static class UseScrollableResultSetProvider implements SettingProvider.Provider { + @Override + public Boolean getSetting() { try { - boolean supportsScroll = connection.getMetaData().supportsResultSetType( ResultSet.TYPE_SCROLL_INSENSITIVE ); - settings.put( Environment.USE_SCROLLABLE_RESULTSET, "" + supportsScroll ); + Connection connection = cp.getConnection(); + try { + return connection.getMetaData() + .supportsResultSetType( ResultSet.TYPE_SCROLL_INSENSITIVE ); + } + finally { + cp.closeConnection( connection ); + } } - finally { - cp.closeConnection( connection ); + catch (SQLException e) { + throw new RuntimeException( e ); } } - catch (SQLException ignore) { - } - } - - @Override - public boolean createSchema() { - return false; - } - - @Override - public boolean rebuildSessionFactoryOnError() { - return false; } - @Override - protected void prepareTest() throws Exception { - super.prepareTest(); + @BeforeAll + protected void prepareTest(SessionFactoryScope scope) throws Exception { try { Connection conn = cp.getConnection(); + ServiceRegistryImplementor serviceRegistry = scope.getSessionFactory().getServiceRegistry(); try { final GenerationTargetToDatabase target = new GenerationTargetToDatabase( - new DdlTransactionIsolatorTestingImpl( serviceRegistry(), conn ), + new DdlTransactionIsolatorTestingImpl( serviceRegistry, conn ), true ); - new SchemaCreatorImpl( serviceRegistry() ).doCreation( - metadata(), + new SchemaCreatorImpl( serviceRegistry ).doCreation( + scope.getMetadataImplementor(), false, target ); @@ -128,33 +114,61 @@ protected void prepareTest() throws Exception { cp.closeConnection( conn ); } } - catch( Throwable ignore ) { + catch (Throwable ignore) { } - } - @Override - protected void cleanupTest() throws Exception { + + @AfterAll + @SuppressWarnings("unused") + private void releaseConnectionProvider(SessionFactoryScope scope) { try { Connection conn = cp.getConnection(); + ServiceRegistryImplementor serviceRegistry = scope.getSessionFactory().getServiceRegistry(); try { final GenerationTargetToDatabase target = new GenerationTargetToDatabase( new DdlTransactionIsolatorTestingImpl( - serviceRegistry(), + serviceRegistry, conn ), true ); - new SchemaDropperImpl( serviceRegistry() ).doDrop( metadata(), false, target ); + new SchemaDropperImpl( serviceRegistry ).doDrop( scope.getMetadataImplementor(), false, target ); } finally { cp.closeConnection( conn ); } } - catch( Throwable ignore ) { + catch (Throwable ignore) { + } + try { + if ( cp instanceof Stoppable ) { + ((Stoppable) cp).stop(); + } + cp = null; + } + catch (Throwable ignore) { } + } + + @Override + protected Session getSessionUnderTest(SessionFactoryScope scope) throws Throwable { + connectionUnderTest = cp.getConnection(); + Session session = scope.getSessionFactory().withOptions().connection( connectionUnderTest ).openSession(); + session.beginTransaction(); + return session; + } - super.cleanupTest(); + @Override + protected void reconnect(Session session) { + ((SessionImplementor) session).getJdbcCoordinator().getLogicalConnection() + .manualReconnect( connectionUnderTest ); } + + @Override + protected void done() throws Throwable { + cp.closeConnection( connectionUnderTest ); + } + } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/connections/ThreadLocalCurrentSessionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/connections/ThreadLocalCurrentSessionTest.java index fb740c2392e7..11ecbc1b49f9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/connections/ThreadLocalCurrentSessionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/connections/ThreadLocalCurrentSessionTest.java @@ -4,8 +4,6 @@ */ package org.hibernate.orm.test.connections; -import java.util.Map; - import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.Environment; @@ -13,100 +11,147 @@ import org.hibernate.dialect.H2Dialect; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.resource.transaction.spi.TransactionStatus; - -import org.hibernate.testing.RequiresDialect; import org.hibernate.testing.orm.junit.JiraKey; -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.SettingProvider; +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.assertThat; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Steve Ebersole */ @RequiresDialect(H2Dialect.class) +@ServiceRegistry( + settingProviders = @SettingProvider( + settingName = Environment.CURRENT_SESSION_CONTEXT_CLASS, + provider = ThreadLocalCurrentSessionTest.CurrentSessionContextClassProvider.class + + ) +) +@SessionFactory( + generateStatistics = true +) public class ThreadLocalCurrentSessionTest extends ConnectionManagementTestCase { - @Override - protected void addSettings(Map settings) { - super.addSettings( settings ); - settings.put( Environment.CURRENT_SESSION_CONTEXT_CLASS, TestableThreadLocalContext.class.getName() ); - settings.put( Environment.GENERATE_STATISTICS, "true" ); + public static class CurrentSessionContextClassProvider implements SettingProvider.Provider { + @Override + public String getSetting() { + return TestableThreadLocalContext.class.getName(); + } } + @Override - protected Session getSessionUnderTest() throws Throwable { - Session session = sessionFactory().getCurrentSession(); + protected Session getSessionUnderTest(SessionFactoryScope scope) { + Session session = scope.getSessionFactory().getCurrentSession(); session.beginTransaction(); return session; } @Override - protected void release(Session session) { + protected void release(Session session, SessionFactoryScope scope) { + SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); if ( session.getTransaction().getStatus() != TransactionStatus.ACTIVE ) { - TestableThreadLocalContext.unbind( sessionFactory() ); + TestableThreadLocalContext.unbind( sessionFactory ); return; } - long initialCount = sessionFactory().getStatistics().getSessionCloseCount(); + long initialCount = sessionFactory.getStatistics().getSessionCloseCount(); session.getTransaction().commit(); - long subsequentCount = sessionFactory().getStatistics().getSessionCloseCount(); - assertEquals( "Session still open after commit", initialCount + 1, subsequentCount ); + long subsequentCount = sessionFactory.getStatistics().getSessionCloseCount(); + assertThat( subsequentCount ) + .describedAs( "Session still open after commit" ) + .isEqualTo( initialCount + 1 ); // also make sure it was cleaned up from the internal ThreadLocal... - assertFalse( "session still bound to internal ThreadLocal", TestableThreadLocalContext.hasBind() ); + assertThat( TestableThreadLocalContext.hasBind() ) + .describedAs( "session still bound to internal ThreadLocal" ) + .isFalse(); } @Override - protected void reconnect(Session session) throws Throwable { + protected void reconnect(Session session) { } @Override protected void checkSerializedState(Session session) { - assertFalse( "session still bound after serialize", TestableThreadLocalContext.isSessionBound( session ) ); + assertThat( TestableThreadLocalContext.isSessionBound( session ) ) + .describedAs( "session still bound after serialize" ) + .isFalse(); } @Override protected void checkDeserializedState(Session session) { - assertTrue( "session not bound after deserialize", TestableThreadLocalContext.isSessionBound( session ) ); + assertThat( TestableThreadLocalContext.isSessionBound( session ) ) + .describedAs( "session not bound after deserialize" ) + .isTrue(); } @Test @JiraKey(value = "HHH-11067") - public void testEqualityChecking() { - Session session1 = sessionFactory().getCurrentSession(); - Session session2 = sessionFactory().getCurrentSession(); - - assertSame( "== check", session1, session2 ); - assertEquals( "#equals check", session1, session2 ); + public void testEqualityChecking(SessionFactoryScope scope) { + SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); + Session session1 = null; + Session session2 = null; + try { + session1 = sessionFactory.getCurrentSession(); + session2 = sessionFactory.getCurrentSession(); + assertThat( session1 ).isSameAs( session2 ); + assertThat( session1 ).isEqualTo( session2 ); + } + finally { + release( session1, scope ); + release( session2, scope ); + } } @Test - public void testTransactionProtection() { - Session session = sessionFactory().getCurrentSession(); - try { + public void testTransactionProtection(SessionFactoryScope scope) { + try (Session session = scope.getSessionFactory().getCurrentSession()) { + session.createQuery( "from Silly" ); fail( "method other than beginTransaction() allowed" ); } - catch ( HibernateException e ) { + catch (HibernateException e) { // ok } } @Test - public void testContextCleanup() { - Session session = sessionFactory().getCurrentSession(); - session.beginTransaction(); - session.getTransaction().commit(); - assertFalse( "session open after txn completion", session.isOpen() ); - assertFalse( "session still bound after txn completion", TestableThreadLocalContext.isSessionBound( session ) ); - - Session session2 = sessionFactory().getCurrentSession(); - assertFalse( "same session returned after txn completion", session == session2 ); - session2.close(); - assertFalse( "session open after closing", session2.isOpen() ); - assertFalse( "session still bound after closing", TestableThreadLocalContext.isSessionBound( session2 ) ); + public void testContextCleanup(SessionFactoryScope scope) { + SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); + Session session = null; + Session session2 = null; + try { + session = sessionFactory.getCurrentSession(); + session.beginTransaction(); + session.getTransaction().commit(); + assertThat( session.isOpen() ) + .describedAs( "session open after txn completion" ) + .isFalse(); + assertThat( TestableThreadLocalContext.isSessionBound( session ) ) + .describedAs( "session still bound after txn completion" ) + .isFalse(); + + session2 = sessionFactory.getCurrentSession(); + assertThat( session == session2 ) + .describedAs( "same session returned after txn completion" ) + .isFalse(); + session2.close(); + assertThat( session2.isOpen() ) + .describedAs( "session open after closing" ) + .isFalse(); + assertThat( TestableThreadLocalContext.isSessionBound( session2 ) ) + .describedAs( "session still bound after closing" ) + .isFalse(); + } + finally { + release( session, scope ); + release( session2, scope ); + } } public static class TestableThreadLocalContext extends ThreadLocalSessionContext { @@ -119,7 +164,7 @@ public TestableThreadLocalContext(SessionFactoryImplementor factory) { public static boolean isSessionBound(Session session) { return sessionMap() != null && sessionMap().containsKey( me.factory() ) - && sessionMap().get( me.factory() ) == session; + && sessionMap().get( me.factory() ) == session; } public static boolean hasBind() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/constraint/ConstraintTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/constraint/ConstraintTest.java index a2aacbc56d2e..59ca8ea899db 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/constraint/ConstraintTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/constraint/ConstraintTest.java @@ -11,24 +11,30 @@ import jakarta.persistence.OneToOne; import jakarta.persistence.Table; import jakarta.persistence.UniqueConstraint; - import org.hibernate.boot.model.relational.Namespace; +import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.mapping.Column; import org.hibernate.mapping.ForeignKey; import org.hibernate.mapping.UniqueKey; - +import org.hibernate.testing.orm.junit.DomainModel; 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.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Brett Meyer */ -public class ConstraintTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + ConstraintTest.DataPoint.class, + ConstraintTest.DataPoint2.class + } +) +@SessionFactory +public class ConstraintTest { private static final int MAX_NAME_LENGTH = 30; @@ -38,91 +44,91 @@ public class ConstraintTest extends BaseNonConfigCoreFunctionalTestCase { private static final String EXPLICIT_UK_NAME = "uk_explicit"; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { DataPoint.class, DataPoint2.class }; - } - @Test - @JiraKey( value = "HHH-7797" ) - public void testUniqueConstraints() { - Column column = (Column) metadata().getEntityBinding( DataPoint.class.getName() ) + @JiraKey(value = "HHH-7797") + public void testUniqueConstraints(SessionFactoryScope scope) { + MetadataImplementor metadata = scope.getMetadataImplementor(); + Column column = (Column) metadata.getEntityBinding( DataPoint.class.getName() ) .getProperty( "foo1" ).getSelectables().get( 0 ); - assertFalse( column.isNullable() ); - assertTrue( column.isUnique() ); + assertThat( column.isNullable() ).isFalse(); + assertThat( column.isUnique() ).isTrue(); - column = (Column) metadata().getEntityBinding( DataPoint.class.getName() ) + column = (Column) metadata.getEntityBinding( DataPoint.class.getName() ) .getProperty( "foo2" ).getSelectables().get( 0 ); - assertTrue( column.isNullable() ); - assertTrue( column.isUnique() ); + assertThat( column.isNullable() ).isTrue(); + assertThat( column.isUnique() ).isTrue(); - column = (Column) metadata().getEntityBinding( DataPoint.class.getName() ) + column = (Column) metadata.getEntityBinding( DataPoint.class.getName() ) .getProperty( "id" ).getSelectables().get( 0 ); - assertFalse( column.isNullable() ); - assertTrue( column.isUnique() ); + assertThat( column.isNullable() ).isFalse(); + assertThat( column.isUnique() ).isTrue(); } @Test - @JiraKey( value = "HHH-1904" ) - public void testConstraintNameLength() { + @JiraKey(value = "HHH-1904") + public void testConstraintNameLength(SessionFactoryScope scope) { + MetadataImplementor metadata = scope.getMetadataImplementor(); + int foundCount = 0; - for ( Namespace namespace : metadata().getDatabase().getNamespaces() ) { + for ( Namespace namespace : metadata.getDatabase().getNamespaces() ) { for ( org.hibernate.mapping.Table table : namespace.getTables() ) { for ( ForeignKey fk : table.getForeignKeyCollection() ) { - assertTrue( fk.getName().length() <= MAX_NAME_LENGTH ); + assertThat( fk.getName().length() ).isLessThanOrEqualTo( MAX_NAME_LENGTH ); // ensure the randomly generated constraint name doesn't // happen if explicitly given Column column = fk.getColumn( 0 ); if ( column.getName().equals( "explicit_native" ) ) { foundCount++; - assertEquals( EXPLICIT_FK_NAME_NATIVE, fk.getName() ); + assertThat( fk.getName() ).isEqualTo( EXPLICIT_FK_NAME_NATIVE ); } else if ( column.getName().equals( "explicit_jpa" ) ) { foundCount++; - assertEquals( EXPLICIT_FK_NAME_JPA, fk.getName() ); + assertThat( fk.getName() ).isEqualTo( EXPLICIT_FK_NAME_JPA ); } } for ( UniqueKey uk : table.getUniqueKeys().values() ) { - assertTrue( uk.getName().length() <= MAX_NAME_LENGTH ); + assertThat( uk.getName().length() ).isLessThanOrEqualTo( MAX_NAME_LENGTH ); // ensure the randomly generated constraint name doesn't // happen if explicitly given Column column = uk.getColumn( 0 ); if ( column.getName().equals( "explicit" ) ) { foundCount++; - assertEquals( EXPLICIT_UK_NAME, uk.getName() ); + assertThat( uk.getName() ).isEqualTo( EXPLICIT_UK_NAME ); } } } } - assertEquals("Could not find the necessary columns.", 3, foundCount); + assertThat( foundCount ) + .describedAs( "Could not find the necessary columns." ) + .isEqualTo( 3 ); } @Entity - @Table( name = "DataPoint", uniqueConstraints = { - @UniqueConstraint( name = EXPLICIT_UK_NAME, columnNames = { "explicit" } ) - } ) + @Table(name = "DataPoint", uniqueConstraints = { + @UniqueConstraint(name = EXPLICIT_UK_NAME, columnNames = {"explicit"}) + }) public static class DataPoint { @Id @GeneratedValue - @jakarta.persistence.Column( nullable = false, unique = true) + @jakarta.persistence.Column(nullable = false, unique = true) public long id; - @jakarta.persistence.Column( nullable = false, unique = true) + @jakarta.persistence.Column(nullable = false, unique = true) public String foo1; - @jakarta.persistence.Column( nullable = true, unique = true) + @jakarta.persistence.Column(unique = true) public String foo2; public String explicit; } @Entity - @Table( name = "DataPoint2" ) + @Table(name = "DataPoint2") public static class DataPoint2 { @Id @GeneratedValue diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/constraint/ForeignKeyConstraintMapsIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/constraint/ForeignKeyConstraintMapsIdTest.java index ea72722e2059..c3f76de55c36 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/constraint/ForeignKeyConstraintMapsIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/constraint/ForeignKeyConstraintMapsIdTest.java @@ -11,22 +11,50 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.MapsId; import jakarta.persistence.OneToOne; - import org.hibernate.boot.model.relational.Namespace; +import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.mapping.Table; - +import org.hibernate.testing.orm.junit.DomainModel; 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.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.fail; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; /** * @author Chris Cranford */ @JiraKey(value = "HHH-12320") -public class ForeignKeyConstraintMapsIdTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + ForeignKeyConstraintMapsIdTest.Post.class, + ForeignKeyConstraintMapsIdTest.PostDetails.class + } +) +@SessionFactory +public class ForeignKeyConstraintMapsIdTest { + + @Test + public void testForeignKeyNameSetForMapsIdJoinColumn(SessionFactoryScope scope) { + MetadataImplementor metadata = scope.getMetadataImplementor(); + for ( Namespace namespace : metadata.getDatabase().getNamespaces() ) { + for ( Table table : namespace.getTables() ) { + if ( table.getName().equals( "Post" ) ) { + for ( var foreignKey : table.getForeignKeyCollection() ) { + if ( foreignKey.getColumn( 0 ).getName().equals( "PD_ID" ) ) { + assertThat( foreignKey.getName() ).isEqualTo( "FK_PD" ); + return; + } + } + } + } + } + fail( "Expected to find a Foreign Key mapped to column PD_ID but failed to locate it" ); + } + @Entity(name = "Post") public static class Post { @Id @@ -76,26 +104,4 @@ public void setUserName(String userName) { this.userName = userName; } } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Post.class, PostDetails.class }; - } - - @Test - public void testForeignKeyNameSetForMapsIdJoinColumn() { - for ( Namespace namespace : metadata().getDatabase().getNamespaces() ) { - for ( Table table : namespace.getTables() ) { - if ( table.getName().equals( "Post" ) ) { - for ( var foreignKey : table.getForeignKeyCollection() ) { - if ( foreignKey.getColumn( 0 ).getName().equals( "PD_ID" ) ) { - assertEquals( "FK_PD", foreignKey.getName() ); - return; - } - } - } - } - } - fail( "Expected to find a Foreign Key mapped to column PD_ID but failed to locate it" ); - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/constraint/ForeignKeyNoConstraintTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/constraint/ForeignKeyNoConstraintTest.java index be7e246d6a36..0b72eacd4a57 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/constraint/ForeignKeyNoConstraintTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/constraint/ForeignKeyNoConstraintTest.java @@ -13,37 +13,37 @@ import jakarta.persistence.MapsId; import jakarta.persistence.OneToOne; import jakarta.persistence.PrimaryKeyJoinColumn; - import org.hibernate.boot.model.relational.Namespace; import org.hibernate.mapping.Table; - +import org.hibernate.testing.orm.junit.DomainModel; 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.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Chris Cranford */ -public class ForeignKeyNoConstraintTest extends BaseNonConfigCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Car.class, - VehicleNumber.class, - Post.class, - PostDetails.class - }; - } +@DomainModel( + annotatedClasses = { + ForeignKeyNoConstraintTest.Car.class, + ForeignKeyNoConstraintTest.VehicleNumber.class, + ForeignKeyNoConstraintTest.Post.class, + ForeignKeyNoConstraintTest.PostDetails.class + } +) +@SessionFactory +public class ForeignKeyNoConstraintTest { @Test @JiraKey(value = "HHH-12975") - public void testPrimaryKeyJoinColumnForeignKeyNoConstraint() { - for ( Namespace namespace : metadata().getDatabase().getNamespaces() ) { + public void testPrimaryKeyJoinColumnForeignKeyNoConstraint(SessionFactoryScope scope) { + for ( Namespace namespace : scope.getMetadataImplementor().getDatabase().getNamespaces() ) { for ( Table table : namespace.getTables() ) { if ( "Car".equals( table.getName() ) ) { - assertEquals( 0, table.getForeignKeyCollection().size() ); + assertThat( table.getForeignKeyCollection() ).hasSize( 0 ); } } } @@ -51,11 +51,11 @@ public void testPrimaryKeyJoinColumnForeignKeyNoConstraint() { @Test @JiraKey(value = "HHH-12975") - public void testMapsIdJoinColumnForeignKeyNoConstraint() { - for ( Namespace namespace : metadata().getDatabase().getNamespaces() ) { + public void testMapsIdJoinColumnForeignKeyNoConstraint(SessionFactoryScope scope) { + for ( Namespace namespace : scope.getMetadataImplementor().getDatabase().getNamespaces() ) { for ( Table table : namespace.getTables() ) { if ( "Post".equals( table.getName() ) ) { - assertEquals( 0, table.getForeignKeyCollection().size() ); + assertThat( table.getForeignKeyCollection() ).hasSize( 0 ); } } } @@ -68,7 +68,7 @@ public static class Car { @PrimaryKeyJoinColumn @OneToOne(optional = false) - @JoinColumn(name = "V_ID", foreignKey = @ForeignKey( ConstraintMode.NO_CONSTRAINT ) ) + @JoinColumn(name = "V_ID", foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) private VehicleNumber vehicleNumber; public Integer getId() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/customstructures/IdentityMapTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/customstructures/IdentityMapTest.java index 393b6cfffcdf..7cdb992d06dd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/customstructures/IdentityMapTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/customstructures/IdentityMapTest.java @@ -4,13 +4,13 @@ */ package org.hibernate.orm.test.customstructures; +import org.hibernate.internal.util.collections.IdentityMap; +import org.junit.jupiter.api.Test; + import java.util.Iterator; import java.util.Objects; -import org.hibernate.internal.util.collections.IdentityMap; - -import org.junit.Assert; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; public class IdentityMapTest { @@ -19,16 +19,16 @@ public void basicIdentityMapFunctionality() { final IdentityMap map = IdentityMap.instantiateSequenced( 10 ); Holder k1 = new Holder( "k", 1 ); Holder s2 = new Holder( "s", 2 ); - map.put( k1, "k1" ); + map.put( k1, "k1" ); map.put( s2, "s2" ); map.put( k1, "K1!" ); - Assert.assertEquals( 2, map.size() ); + assertThat( map ).hasSize( 2 ); k1.name = "p"; - Assert.assertEquals( 2, map.size() ); - Assert.assertEquals( "K1!", map.get( k1 ) ); + assertThat( map ).hasSize( 2 ); + assertThat( map.get( k1 ) ).isEqualTo( "K1!" ); Holder k1similar = new Holder( "p", 1 ); map.put( k1similar, "notk1" ); - Assert.assertEquals( "K1!", map.get( k1 ) ); + assertThat( map.get( k1 ) ).isEqualTo( "K1!" ); IdentityMap.onEachKey( map, k -> k.value = 10 ); @@ -36,11 +36,11 @@ public void basicIdentityMapFunctionality() { int count = 0; while ( keyIterator.hasNext() ) { final Holder key = keyIterator.next(); - Assert.assertNotNull( key ); + assertThat( key ).isNotNull(); count++; - Assert.assertEquals( 10, key.value ); + assertThat( key.value ).isEqualTo( 10 ); } - Assert.assertEquals( 3, count ); + assertThat( count ).isEqualTo( 3 ); } private static class Holder { @@ -64,7 +64,7 @@ public boolean equals(Object o) { } Holder holder = (Holder) o; return value == holder.value && - name.equals( holder.name ); + name.equals( holder.name ); } @Override diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/customstructures/JdbcParameterListTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/customstructures/JdbcParameterListTest.java index ff6cab955f27..2bc100b9b0ef 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/customstructures/JdbcParameterListTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/customstructures/JdbcParameterListTest.java @@ -7,9 +7,11 @@ import org.hibernate.sql.ast.tree.expression.JdbcParameter; import org.hibernate.sql.exec.internal.JdbcParameterImpl; import org.hibernate.sql.exec.spi.JdbcParametersList; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; -import org.junit.Assert; -import org.junit.Test; /** * Unit tests for JdbcParametersList @@ -27,7 +29,7 @@ public void singleton() { final JdbcParameterImpl element = makeJdbcParameterElement(); final JdbcParametersList singleton = JdbcParametersList.singleton( element ); expectsSize( 1, singleton ); - Assert.assertSame( element, singleton.get( 0 ) ); + assertThat( singleton.get( 0 ) ).isSameAs( element ); } @Test @@ -55,7 +57,7 @@ private void verifyAsSingletonBuilder(JdbcParametersList.Builder builder) { builder.add( element ); final JdbcParametersList built = builder.build(); expectsSize( 1, built ); - Assert.assertSame( element, built.get( 0 ) ); + assertThat( element ).isSameAs( built.get( 0 ) ); } @Test @@ -95,7 +97,7 @@ private void verifyNparamBuilder(final int size, final JdbcParametersList.Builde final JdbcParametersList built = builder.build(); expectsSize( size, built ); for ( int i = 0; i < size; i++ ) { - Assert.assertSame( elements[i], built.get( i ) ); + assertThat( built.get( i ) ).isSameAs( elements[i] ); } } @@ -104,17 +106,17 @@ private static void expectsEmpty(JdbcParametersList empty) { } private static void expectsSize(int size, JdbcParametersList list) { - Assert.assertEquals( size, list.size() ); + assertThat( list.size() ).isEqualTo( size ); for ( int i = 0; i < size; i++ ) { - Assert.assertNotNull( list.get( i ) ); + assertThat( list.get( i ) ).isNotNull(); } if ( size == 0 ) { - Assert.assertSame( JdbcParametersList.empty(), list ); + assertThat( list ).isSameAs( JdbcParametersList.empty() ); } else if ( size == 1 ) { - Assert.assertTrue( list instanceof JdbcParametersList.JdbcParametersListSingleton ); + assertThat( list ).isInstanceOf( JdbcParametersList.JdbcParametersListSingleton.class ); } - Assert.assertThrows( ArrayIndexOutOfBoundsException.class, () -> list.get( size ) ); + assertThrows( ArrayIndexOutOfBoundsException.class, () -> list.get( size ) ); } private static JdbcParameterImpl makeJdbcParameterElement() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SequenceInformationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SequenceInformationTest.java index 60bc9fa9e36b..809144179140 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SequenceInformationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SequenceInformationTest.java @@ -4,34 +4,33 @@ */ package org.hibernate.orm.test.dialect.functional; -import java.util.EnumSet; -import java.util.List; -import java.util.Map; import jakarta.persistence.Entity; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.SequenceGenerator; - import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.cfg.AvailableSettings; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.service.ServiceRegistry; -import org.hibernate.tool.hbm2ddl.SchemaExport; -import org.hibernate.tool.schema.TargetType; -import org.hibernate.tool.schema.extract.spi.SequenceInformation; - import org.hibernate.testing.orm.junit.DialectFeatureChecks; -import org.hibernate.testing.orm.junit.RequiresDialectFeature; -import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.orm.junit.EntityManagerFactoryBasedFunctionalTest; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialectFeature; import org.hibernate.testing.util.ServiceRegistryUtil; +import org.hibernate.tool.hbm2ddl.SchemaExport; +import org.hibernate.tool.schema.TargetType; +import org.hibernate.tool.schema.extract.spi.SequenceInformation; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; +import java.util.EnumSet; +import java.util.List; +import java.util.Map; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -45,6 +44,7 @@ public class SequenceInformationTest extends protected ServiceRegistry serviceRegistry; protected MetadataImplementor metadata; + protected EntityManagerFactory entityManagerFactory; @Override public EntityManagerFactory produceEntityManagerFactory() { @@ -56,13 +56,17 @@ public EntityManagerFactory produceEntityManagerFactory() { new SchemaExport().drop( EnumSet.of( TargetType.DATABASE ), metadata ); new SchemaExport().create( EnumSet.of( TargetType.DATABASE ), metadata ); - return super.produceEntityManagerFactory(); + entityManagerFactory = super.produceEntityManagerFactory(); + return entityManagerFactory; } @AfterAll public void releaseResources() { new SchemaExport().drop( EnumSet.of( TargetType.DATABASE ), metadata ); StandardServiceRegistryBuilder.destroy( serviceRegistry ); + if ( entityManagerFactory != null ) { + entityManagerFactory.close(); + } } @Override @@ -73,16 +77,18 @@ protected void addConfigOptions(Map options) { @Test public void test() { - SequenceInformation productSequenceInfo = sequenceInformation("product_sequence"); + SequenceInformation productSequenceInfo = sequenceInformation( "product_sequence" ); assertNotNull( productSequenceInfo ); - assertEquals( "product_sequence", productSequenceInfo.getSequenceName().getSequenceName().getText().toLowerCase() ); + assertEquals( "product_sequence", + productSequenceInfo.getSequenceName().getSequenceName().getText().toLowerCase() ); assertProductSequence( productSequenceInfo ); - SequenceInformation vehicleSequenceInfo = sequenceInformation("vehicle_sequence"); + SequenceInformation vehicleSequenceInfo = sequenceInformation( "vehicle_sequence" ); assertNotNull( vehicleSequenceInfo ); - assertEquals( "vehicle_sequence", vehicleSequenceInfo.getSequenceName().getSequenceName().getText().toLowerCase() ); + assertEquals( "vehicle_sequence", + vehicleSequenceInfo.getSequenceName().getSequenceName().getText().toLowerCase() ); assertVehicleSequenceInfo( vehicleSequenceInfo ); } @@ -95,10 +101,13 @@ protected void assertVehicleSequenceInfo(SequenceInformation vehicleSequenceInfo } private SequenceInformation sequenceInformation(String sequenceName) { - List sequenceInformationList = entityManagerFactory().unwrap( SessionFactoryImplementor.class ).getJdbcServices().getExtractedMetaDataSupport().getSequenceInformationList(); + List sequenceInformationList = entityManagerFactory().unwrap( + SessionFactoryImplementor.class ).getJdbcServices().getExtractedMetaDataSupport() + .getSequenceInformationList(); return sequenceInformationList.stream().filter( - sequenceInformation -> sequenceName.equalsIgnoreCase( sequenceInformation.getSequenceName().getSequenceName().getText() ) + sequenceInformation -> sequenceName.equalsIgnoreCase( + sequenceInformation.getSequenceName().getSequenceName().getText() ) ).findFirst().orElse( null ); } @@ -107,7 +116,8 @@ public static class Product { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "product_sequence") - @SequenceGenerator( name = "product_sequence", sequenceName = "product_sequence", initialValue = 1, allocationSize = 10) + @SequenceGenerator(name = "product_sequence", sequenceName = "product_sequence", initialValue = 1, + allocationSize = 10) private Long id; private String name; @@ -118,7 +128,8 @@ public static class Vehicle { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "vehicle_sequence") - @SequenceGenerator( name = "vehicle_sequence", sequenceName = "vehicle_sequence", initialValue = 1, allocationSize = 1) + @SequenceGenerator(name = "vehicle_sequence", sequenceName = "vehicle_sequence", initialValue = 1, + allocationSize = 1) private Long id; private String name; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/engine/spi/EntityEntryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/engine/spi/EntityEntryTest.java index 21615b0c8057..345101e3d191 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/engine/spi/EntityEntryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/engine/spi/EntityEntryTest.java @@ -4,25 +4,21 @@ */ package org.hibernate.orm.test.engine.spi; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; - import org.hibernate.LockMode; import org.hibernate.engine.internal.EntityEntryImpl; import org.hibernate.engine.spi.EntityEntry; import org.hibernate.engine.spi.PersistenceContext; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.engine.spi.Status; +import org.junit.jupiter.api.Test; -import org.junit.Assert; -import org.junit.Test; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -36,27 +32,27 @@ public class EntityEntryTest { @Test public void packedAttributesAreSetByConstructor() { EntityEntry entityEntry = createEntityEntry(); - assertEquals( LockMode.OPTIMISTIC, entityEntry.getLockMode() ); - Assert.assertEquals( Status.MANAGED, entityEntry.getStatus() ); - assertTrue( entityEntry.isExistsInDatabase() ); - assertTrue( entityEntry.isBeingReplicated() ); + assertThat( entityEntry.getLockMode() ).isEqualTo( LockMode.OPTIMISTIC ); + assertThat( entityEntry.getStatus() ).isEqualTo( Status.MANAGED ); + assertThat( entityEntry.isExistsInDatabase() ).isTrue(); + assertThat( entityEntry.isBeingReplicated() ).isTrue(); } @Test public void testLockModeCanBeSetAndDoesNotAffectOtherPackedAttributes() { // Given EntityEntry entityEntry = createEntityEntry(); - assertEquals( LockMode.OPTIMISTIC, entityEntry.getLockMode() ); - assertEquals( Status.MANAGED, entityEntry.getStatus() ); - assertTrue( entityEntry.isExistsInDatabase() ); - assertTrue( entityEntry.isBeingReplicated() ); + assertThat( entityEntry.getLockMode() ).isEqualTo( LockMode.OPTIMISTIC ); + assertThat( entityEntry.getStatus() ).isEqualTo( Status.MANAGED ); + assertThat( entityEntry.isExistsInDatabase() ).isTrue(); + assertThat( entityEntry.isBeingReplicated() ).isTrue(); // When entityEntry.setLockMode( LockMode.PESSIMISTIC_READ ); // Then - assertEquals( LockMode.PESSIMISTIC_READ, entityEntry.getLockMode() ); - assertEquals( Status.MANAGED, entityEntry.getStatus() ); - assertTrue( entityEntry.isExistsInDatabase() ); - assertTrue( entityEntry.isBeingReplicated() ); + assertThat( entityEntry.getLockMode() ).isEqualTo( LockMode.PESSIMISTIC_READ ); + assertThat( entityEntry.getStatus() ).isEqualTo( Status.MANAGED ); + assertThat( entityEntry.isExistsInDatabase() ).isTrue(); + assertThat( entityEntry.isBeingReplicated() ).isTrue(); } @Test @@ -66,10 +62,10 @@ public void testStatusCanBeSetAndDoesNotAffectOtherPackedAttributes() { // When entityEntry.setStatus( Status.DELETED ); // Then - assertEquals( LockMode.OPTIMISTIC, entityEntry.getLockMode() ); - assertEquals( Status.DELETED, entityEntry.getStatus() ); - assertTrue( entityEntry.isExistsInDatabase() ); - assertTrue( entityEntry.isBeingReplicated() ); + assertThat( entityEntry.getLockMode() ).isEqualTo( LockMode.OPTIMISTIC ); + assertThat( entityEntry.getStatus() ).isEqualTo( Status.DELETED ); + assertThat( entityEntry.isExistsInDatabase() ).isTrue(); + assertThat( entityEntry.isBeingReplicated() ).isTrue(); } @Test @@ -79,10 +75,10 @@ public void testPostDeleteSetsStatusAndExistsInDatabaseWithoutAffectingOtherPack // When entityEntry.postDelete(); // Then - assertEquals( LockMode.OPTIMISTIC, entityEntry.getLockMode() ); - assertEquals( Status.GONE, entityEntry.getStatus() ); - assertFalse( entityEntry.isExistsInDatabase() ); - assertTrue( entityEntry.isBeingReplicated() ); + assertThat( entityEntry.getLockMode() ).isEqualTo( LockMode.OPTIMISTIC ); + assertThat( entityEntry.getStatus() ).isEqualTo( Status.GONE ); + assertThat( entityEntry.isExistsInDatabase() ).isFalse(); + assertThat( entityEntry.isBeingReplicated() ).isTrue(); } @Test @@ -91,7 +87,7 @@ public void testSerializationAndDeserializationKeepCorrectPackedAttributes() thr ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream( baos ); - entityEntry.serialize(oos); + entityEntry.serialize( oos ); oos.flush(); InputStream is = new ByteArrayInputStream( baos.toByteArray() ); @@ -99,31 +95,22 @@ public void testSerializationAndDeserializationKeepCorrectPackedAttributes() thr EntityEntryImpl.deserialize( new ObjectInputStream( is ), getPersistenceContextMock() ); - assertEquals( LockMode.OPTIMISTIC, deserializedEntry.getLockMode() ); - assertEquals( Status.MANAGED, deserializedEntry.getStatus() ); - assertTrue( deserializedEntry.isExistsInDatabase() ); - assertTrue( deserializedEntry.isBeingReplicated() ); + assertThat( deserializedEntry.getLockMode() ).isEqualTo( LockMode.OPTIMISTIC ); + assertThat( deserializedEntry.getStatus() ).isEqualTo( Status.MANAGED ); + assertThat( deserializedEntry.isExistsInDatabase() ).isTrue(); + assertThat( deserializedEntry.isBeingReplicated() ).isTrue(); } private EntityEntry createEntityEntry() { return new EntityEntryImpl( - // status Status.MANAGED, - // loadedState - new Object[]{}, - // rowId + new Object[] {}, 1L, - // id 42L, - // version 23L, - // lockMode LockMode.OPTIMISTIC, - // existsInDatabase true, - // persister null, - // disableVersionIncrement true, getPersistenceContextMock() ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/mappedbyid/LoadGraphFindByIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/mappedbyid/LoadGraphFindByIdTest.java index d32581d1f618..faf9745fd00f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/mappedbyid/LoadGraphFindByIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/mappedbyid/LoadGraphFindByIdTest.java @@ -4,8 +4,6 @@ */ package org.hibernate.orm.test.entitygraph.mappedbyid; -import java.util.HashMap; -import java.util.Map; import jakarta.persistence.Entity; import jakarta.persistence.EntityGraph; import jakarta.persistence.EntityManager; @@ -18,31 +16,31 @@ import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Root; - -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Assert; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.Map; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Oliver Breidenbach */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class LoadGraphFindByIdTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] {User.class, UserStatistic.class}; - } - - @Override - protected void afterEntityManagerFactoryBuilt() { - doInJPA( this::entityManagerFactory, em -> { +@Jpa( + annotatedClasses = { + LoadGraphFindByIdTest.User.class, + LoadGraphFindByIdTest.UserStatistic.class + } +) +public class LoadGraphFindByIdTest { + + @BeforeAll + protected void setUp(EntityManagerFactoryScope scope) { + scope.inTransaction( em -> { UserStatistic statistic = new UserStatistic(); statistic.id = 1L; statistic.commentCount = 7; @@ -57,19 +55,19 @@ protected void afterEntityManagerFactoryBuilt() { @Test @JiraKey(value = "HHH-10842") - public void findByPrimaryKeyWithId() { - doInJPA( this::entityManagerFactory, em -> { + public void findByPrimaryKeyWithId(EntityManagerFactoryScope scope) { + scope.inTransaction( em -> { User result = em.find( User.class, 1L, createProperties( em ) ); - Assert.assertNotNull( result.userStatistic.commentCount ); + assertThat( result.userStatistic.commentCount ).isNotNull(); } ); } @Test @JiraKey(value = "HHH-10842") - public void findByPrimaryKeyWithQuery() { - doInJPA( this::entityManagerFactory, em -> { + public void findByPrimaryKeyWithQuery(EntityManagerFactoryScope scope) { + scope.inTransaction( em -> { User result = createTypedQuery( em ).getSingleResult(); - Assert.assertNotNull( result.userStatistic.commentCount ); + assertThat( result.userStatistic.commentCount ).isNotNull(); } ); } @@ -85,7 +83,7 @@ private TypedQuery createTypedQuery(EntityManager em) { } private Map createProperties(EntityManager em) { - Map properties = new HashMap(); + Map properties = new HashMap<>(); properties.put( "javax.persistence.loadgraph", createEntityGraph( em ) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/parser/AbstractEntityGraphTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/parser/AbstractEntityGraphTest.java index 0f7893062549..ca7e9a2d6eab 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/parser/AbstractEntityGraphTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/parser/AbstractEntityGraphTest.java @@ -4,30 +4,29 @@ */ package org.hibernate.orm.test.entitygraph.parser; -import jakarta.persistence.EntityManager; - import org.hibernate.graph.GraphParser; import org.hibernate.graph.spi.RootGraphImplementor; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -public abstract class AbstractEntityGraphTest extends BaseEntityManagerFunctionalTestCase { - - public AbstractEntityGraphTest() { - super(); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ GraphParsingTestEntity.class, GraphParsingTestSubEntity.class }; - } - - protected RootGraphImplementor parseGraph(Class entityType, String graphString) { - EntityManager entityManager = getOrCreateEntityManager(); - return (RootGraphImplementor) GraphParser.parse( entityType, graphString, entityManager ); +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; + +@Jpa( + annotatedClasses = { + GraphParsingTestEntity.class, + GraphParsingTestSubEntity.class + } +) +public abstract class AbstractEntityGraphTest { + + protected RootGraphImplementor parseGraph(Class entityType, String graphString, EntityManagerFactoryScope scope) { + return scope.fromEntityManager( + entityManager -> { + return (RootGraphImplementor) GraphParser.parse( entityType, graphString, entityManager ); + } + ); } - protected RootGraphImplementor parseGraph(String graphString) { - return parseGraph( GraphParsingTestEntity.class, graphString ); + protected RootGraphImplementor parseGraph(String graphString, EntityManagerFactoryScope scope) { + return parseGraph( GraphParsingTestEntity.class, graphString, scope ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/parser/AssertionHelper.java b/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/parser/AssertionHelper.java index a61b61f11f76..4275bbc60e9b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/parser/AssertionHelper.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/parser/AssertionHelper.java @@ -7,45 +7,47 @@ import jakarta.persistence.AttributeNode; import jakarta.persistence.EntityGraph; import jakarta.persistence.Subgraph; -import org.junit.Assert; import java.util.Collection; import java.util.List; import java.util.Map; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.fail; + /** * @author Steve Ebersole */ public class AssertionHelper { static > void assertNullOrEmpty(C collection) { if ( collection != null ) { - Assert.assertEquals( 0, collection.size() ); + assertThat( collection ).hasSize( 0 ); } } public static > void assertNullOrEmpty(M map) { if ( map != null ) { - Assert.assertEquals( 0, map.size() ); + assertThat( map.size() ).isEqualTo( 0 ); } } public static void assertBasicAttributes(EntityGraph graph, String... names) { - Assert.assertNotNull( graph ); + assertThat( graph ).isNotNull(); assertBasicAttributes( graph.getAttributeNodes(), names ); } public static void assertBasicAttributes(Subgraph graph, String... names) { - Assert.assertNotNull( graph ); + assertThat( graph ).isNotNull(); assertBasicAttributes( graph.getAttributeNodes(), names ); } public static void assertBasicAttributes(List> attrs, String... names) { - if ( ( names == null ) || ( names.length == 0 ) ) { + if ( (names == null) || (names.length == 0) ) { assertNullOrEmpty( attrs ); } else { - Assert.assertNotNull( attrs ); - Assert.assertTrue( names.length <= attrs.size() ); + assertThat( attrs ).isNotNull(); + assertThat( names.length ).isLessThanOrEqualTo( attrs.size() ); for ( String name : names ) { AttributeNode node = null; @@ -55,7 +57,7 @@ public static void assertBasicAttributes(List> attrs, String... break; } } - Assert.assertNotNull( node ); + assertThat( node ).isNotNull(); assertNullOrEmpty( node.getKeySubgraphs() ); assertNullOrEmpty( node.getSubgraphs() ); } @@ -72,11 +74,13 @@ public static AttributeNode getAttributeNodeByName(Subgraph graph, String public static AttributeNode getAttributeNodeByName(List> attrs, String name, boolean required) { for ( AttributeNode attr : attrs ) { - if ( name.equals( attr.getAttributeName() ) ) + if ( name.equals( attr.getAttributeName() ) ) { return attr; + } + } + if ( required ) { + fail( "Required attribute not found." ); } - if ( required ) - Assert.fail( "Required attribute not found." ); return null; } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/parser/EntityGraphParserTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/parser/EntityGraphParserTest.java index d53bbd42882e..863ebcb4505f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/parser/EntityGraphParserTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/parser/EntityGraphParserTest.java @@ -4,25 +4,21 @@ */ package org.hibernate.orm.test.entitygraph.parser; -import java.util.List; -import java.util.Map; - import jakarta.persistence.AttributeNode; import jakarta.persistence.EntityGraph; -import jakarta.persistence.EntityManager; import jakarta.persistence.Subgraph; - import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.graph.GraphParser; import org.hibernate.graph.spi.AttributeNodeImplementor; import org.hibernate.graph.spi.RootGraphImplementor; import org.hibernate.graph.spi.SubGraphImplementor; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.junit.jupiter.api.Test; -import org.junit.Assert; -import org.junit.Test; +import java.util.List; +import java.util.Map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; /** * A unit test of {@link GraphParser}. @@ -32,33 +28,35 @@ public class EntityGraphParserTest extends AbstractEntityGraphTest { @Test - public void testNullParsing() { - EntityGraph graph = parseGraph( (String) null ); - Assert.assertNull( graph ); + public void testNullParsing(EntityManagerFactoryScope scope) { + EntityGraph graph = parseGraph( null, scope ); + assertThat( graph ).isNull(); } @Test - public void testOneBasicAttributeParsing() { - EntityGraph graph = parseGraph( "name" ); + public void testOneBasicAttributeParsing(EntityManagerFactoryScope scope) { + EntityGraph graph = parseGraph( "name", scope ); AssertionHelper.assertBasicAttributes( graph, "name" ); } @Test - public void testTwoBasicAttributesParsing() { - EntityGraph graph = parseGraph( "name, description" ); + public void testTwoBasicAttributesParsing(EntityManagerFactoryScope scope) { + EntityGraph graph = parseGraph( "name, description", scope ); AssertionHelper.assertBasicAttributes( graph, "name", "description" ); } @Test - public void testLinkParsing() { - EntityGraph graph = parseGraph( "linkToOne(name, description)" ); - assertNotNull( graph ); + public void testLinkParsing(EntityManagerFactoryScope scope) { + EntityGraph graph = parseGraph( "linkToOne(name, description)", scope ); + assertThat( graph ).isNotNull(); + List> attrs = graph.getAttributeNodes(); - assertNotNull( attrs ); - assertEquals( 1, attrs.size() ); + assertThat( attrs ).isNotNull(); + + assertThat( attrs.size() ).isEqualTo( 1 ); AttributeNode node = attrs.get( 0 ); - assertNotNull( node ); - assertEquals( "linkToOne", node.getAttributeName() ); + assertThat( node ).isNotNull(); + assertThat( node.getAttributeName() ).isEqualTo( "linkToOne" ); AssertionHelper.assertNullOrEmpty( node.getKeySubgraphs() ); @SuppressWarnings("rawtypes") Map sub = node.getSubgraphs(); @@ -66,15 +64,15 @@ public void testLinkParsing() { } @Test - public void testMapKeyParsing() { - EntityGraph graph = parseGraph( "map.key(name, description)" ); - assertNotNull( graph ); + public void testMapKeyParsing(EntityManagerFactoryScope scope) { + EntityGraph graph = parseGraph( "map.key(name, description)", scope ); + assertThat( graph ).isNotNull(); List> attrs = graph.getAttributeNodes(); - assertNotNull( attrs ); - assertEquals( 1, attrs.size() ); + assertThat( attrs ).isNotNull(); + assertThat( attrs.size() ).isEqualTo( 1 ); AttributeNode node = attrs.get( 0 ); - assertNotNull( node ); - assertEquals( "map", node.getAttributeName() ); + assertThat( node ).isNotNull(); + assertThat( node.getAttributeName() ).isEqualTo( "map" ); AssertionHelper.assertNullOrEmpty( node.getSubgraphs() ); @SuppressWarnings("rawtypes") Map sub = node.getKeySubgraphs(); @@ -82,15 +80,15 @@ public void testMapKeyParsing() { } @Test - public void testMapValueParsing() { - EntityGraph graph = parseGraph( "map.value(name, description)" ); - assertNotNull( graph ); + public void testMapValueParsing(EntityManagerFactoryScope scope) { + EntityGraph graph = parseGraph( "map.value(name, description)", scope ); + assertThat( graph ).isNotNull(); List> attrs = graph.getAttributeNodes(); - assertNotNull( attrs ); - assertEquals( 1, attrs.size() ); + assertThat( attrs ).isNotNull(); + assertThat( attrs.size() ).isEqualTo( 1 ); AttributeNode node = attrs.get( 0 ); - assertNotNull( node ); - assertEquals( "map", node.getAttributeName() ); + assertThat( node ).isNotNull(); + assertThat( node.getAttributeName() ).isEqualTo( "map" ); AssertionHelper.assertNullOrEmpty( node.getKeySubgraphs() ); @SuppressWarnings("rawtypes") Map sub = node.getSubgraphs(); @@ -98,11 +96,11 @@ public void testMapValueParsing() { } @Test - public void testMixParsingWithMaps() { + public void testMixParsingWithMaps(EntityManagerFactoryScope scope) { String g = " name , linkToOne ( description, map . key ( name ) , map . value ( description ) , name ) , description , map . key ( name , description ) , map . value ( description ) "; g = g.replace( " ", " " ); for ( int i = 1; i <= 2; i++, g = g.replace( " ", "" ) ) { - EntityGraph graph = parseGraph( g ); + EntityGraph graph = parseGraph( g, scope ); AssertionHelper.assertBasicAttributes( graph, "name", "description" ); AttributeNode linkToOne = AssertionHelper.getAttributeNodeByName( graph, "linkToOne", true ); @@ -140,11 +138,11 @@ public void testMixParsingWithMaps() { } @Test - public void testMixParsingWithSimplifiedMaps() { + public void testMixParsingWithSimplifiedMaps(EntityManagerFactoryScope scope) { String g = " name , linkToOne ( description, map . key ( name ) , name ) , description , map . value ( description, name ) "; g = g.replace( " ", " " ); for ( int i = 1; i <= 2; i++, g = g.replace( " ", "" ) ) { - EntityGraph graph = parseGraph( g ); + EntityGraph graph = parseGraph( g, scope ); AssertionHelper.assertBasicAttributes( graph, "name", "description" ); AttributeNode linkToOne = AssertionHelper.getAttributeNodeByName( graph, "linkToOne", true ); @@ -172,56 +170,68 @@ public void testMixParsingWithSimplifiedMaps() { } @Test - public void testLinkSubtypeParsing() { - RootGraphImplementor graph = parseGraph( "linkToOne(name, description), linkToOne(GraphParsingTestSubEntity: sub)" ); - assertNotNull( graph ); + public void testLinkSubtypeParsing(EntityManagerFactoryScope scope) { + RootGraphImplementor graph = parseGraph( + "linkToOne(name, description), linkToOne(GraphParsingTestSubEntity: sub)", scope ); + assertThat( graph ).isNotNull(); - List> attrs = graph.getAttributeNodeList(); - assertNotNull( attrs ); - assertEquals( 1, attrs.size() ); + List> attrs = graph.getAttributeNodeList(); + assertThat( attrs ).isNotNull(); + assertThat( attrs.size() ).isEqualTo( 1 ); - AttributeNodeImplementor linkToOneNode = attrs.get( 0 ); - assertNotNull( linkToOneNode ); - assertEquals( "linkToOne", linkToOneNode.getAttributeName() ); + AttributeNodeImplementor linkToOneNode = attrs.get( 0 ); + assertThat( linkToOneNode ).isNotNull(); + assertThat( linkToOneNode.getAttributeName() ).isEqualTo( "linkToOne" ); AssertionHelper.assertNullOrEmpty( linkToOneNode.getKeySubgraphs() ); final SubGraphImplementor subgraph = linkToOneNode.getSubGraphs().get( GraphParsingTestSubEntity.class ); - assertNotNull( subgraph ); + assertThat( subgraph ).isNotNull(); AssertionHelper.assertBasicAttributes( subgraph, "sub" ); } @Test - public void testHHH10378IsNotFixedYet() { - EntityManager entityManager = getOrCreateEntityManager(); - RootGraphImplementor graph = ( (SessionImplementor) entityManager ).createEntityGraph( - GraphParsingTestEntity.class ); - final SubGraphImplementor subGraph = graph.addSubGraph( - "linkToOne", - GraphParsingTestSubEntity.class + public void testHHH10378IsNotFixedYet(EntityManagerFactoryScope scope) { + scope.inEntityManager( + entityManager -> { + RootGraphImplementor graph = ((SessionImplementor) entityManager) + .createEntityGraph( GraphParsingTestEntity.class ); + final SubGraphImplementor subGraph = graph.addSubGraph( + "linkToOne", + GraphParsingTestSubEntity.class + ); + + assertThat( GraphParsingTestSubEntity.class ).isEqualTo( subGraph.getGraphedType().getJavaType() ); + + final AttributeNodeImplementor subTypeAttrNode = subGraph.findOrCreateAttributeNode( + "sub" ); + assert subTypeAttrNode != null; + } ); - assertEquals( subGraph.getGraphedType().getJavaType(), GraphParsingTestSubEntity.class ); - - final AttributeNodeImplementor subTypeAttrNode = subGraph.findOrCreateAttributeNode( "sub" ); - assert subTypeAttrNode != null; } @Test - public void testHHH12696MapSubgraphsKeyFirst() { - - EntityManager entityManager = getOrCreateEntityManager(); - EntityGraph graph = entityManager.createEntityGraph( GraphParsingTestEntity.class ); - - final String mapAttributeName = "map"; - Subgraph keySubgraph = graph.addKeySubgraph( mapAttributeName ); - Subgraph valueSubgraph = graph.addSubgraph( mapAttributeName ); - - checkMapKeyAndValueSubgraphs( graph, mapAttributeName, keySubgraph, valueSubgraph ); + public void testHHH12696MapSubgraphsKeyFirst(EntityManagerFactoryScope scope) { + scope.inEntityManager( + entityManager -> { + EntityGraph graph = entityManager + .createEntityGraph( GraphParsingTestEntity.class ); + + final String mapAttributeName = "map"; + Subgraph keySubgraph = graph.addKeySubgraph( mapAttributeName ); + Subgraph valueSubgraph = graph.addSubgraph( mapAttributeName ); + + checkMapKeyAndValueSubgraphs( graph, mapAttributeName, keySubgraph, valueSubgraph ); + } + ); } - private void checkMapKeyAndValueSubgraphs(EntityGraph graph, final String mapAttributeName, Subgraph keySubgraph, + private void checkMapKeyAndValueSubgraphs( + EntityGraph graph, + final String mapAttributeName, + Subgraph keySubgraph, Subgraph valueSubgraph) { int count = 0; for ( AttributeNode node : graph.getAttributeNodes() ) { @@ -229,27 +239,35 @@ private void checkMapKeyAndValueSubgraphs(EntityGraph gr count++; @SuppressWarnings("rawtypes") Map keySubgraphs = node.getKeySubgraphs(); - Assert.assertTrue( "Missing the key subgraph", !keySubgraphs.isEmpty() ); - Assert.assertSame( keySubgraph, keySubgraphs.get( GraphParsingTestEntity.class ) ); + assertThat( !keySubgraphs.isEmpty() ) + .describedAs( "Missing the key subgraph" ) + .isTrue(); + assertThat( keySubgraphs.get( GraphParsingTestEntity.class ) ).isSameAs( keySubgraph ); @SuppressWarnings("rawtypes") Map valueSubgraphs = node.getSubgraphs(); - Assert.assertTrue( "Missing the value subgraph", !valueSubgraphs.isEmpty() ); - Assert.assertSame( valueSubgraph, valueSubgraphs.get( GraphParsingTestEntity.class ) ); + assertThat( !valueSubgraphs.isEmpty() ) + .describedAs( "Missing the value subgraph" ) + .isTrue(); + assertThat( valueSubgraphs.get( GraphParsingTestEntity.class ) ).isSameAs( valueSubgraph ); } } - assertEquals( 1, count ); + assertThat( count ).isEqualTo( 1 ); } @Test - public void testHHH12696MapSubgraphsValueFirst() { - EntityManager entityManager = getOrCreateEntityManager(); - EntityGraph graph = entityManager.createEntityGraph( GraphParsingTestEntity.class ); - - final String mapAttributeName = "map"; - Subgraph valueSubgraph = graph.addSubgraph( mapAttributeName ); - Subgraph keySubgraph = graph.addKeySubgraph( mapAttributeName ); - - checkMapKeyAndValueSubgraphs( graph, mapAttributeName, keySubgraph, valueSubgraph ); + public void testHHH12696MapSubgraphsValueFirst(EntityManagerFactoryScope scope) { + scope.inEntityManager( + entityManager -> { + EntityGraph graph = entityManager + .createEntityGraph( GraphParsingTestEntity.class ); + + final String mapAttributeName = "map"; + Subgraph valueSubgraph = graph.addSubgraph( mapAttributeName ); + Subgraph keySubgraph = graph.addKeySubgraph( mapAttributeName ); + + checkMapKeyAndValueSubgraphs( graph, mapAttributeName, keySubgraph, valueSubgraph ); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/parser/EntityGraphsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/parser/EntityGraphsTest.java index f8759df34717..934be0bb8743 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/parser/EntityGraphsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/parser/EntityGraphsTest.java @@ -5,186 +5,195 @@ package org.hibernate.orm.test.entitygraph.parser; import jakarta.persistence.EntityGraph; -import jakarta.persistence.EntityManager; - import org.hibernate.graph.EntityGraphs; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.junit.jupiter.api.Test; -import org.junit.Assert; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; public class EntityGraphsTest extends AbstractEntityGraphTest { @SafeVarargs - private void checkMerge(Class rootType, EntityGraph expected, EntityGraph... graphs) { - EntityManager entityManager = getOrCreateEntityManager(); - EntityGraph actual = EntityGraphs.merge( entityManager, rootType, graphs ); - Assert.assertTrue( EntityGraphs.areEqual( expected, actual ) ); + private void checkMerge(Class rootType, EntityGraph expected, EntityManagerFactoryScope scope, EntityGraph... graphs) { + scope.inEntityManager( + entityManager -> { + EntityGraph actual = EntityGraphs.merge( entityManager, rootType, graphs ); + assertThat( EntityGraphs.areEqual( expected, actual ) ).isTrue(); + } + ); } @SafeVarargs - private void checkMerge(EntityGraph expected, EntityGraph... graphs) { - checkMerge( GraphParsingTestEntity.class, expected, graphs ); + private void checkMerge(EntityGraph expected, EntityManagerFactoryScope scope, EntityGraph... graphs) { + checkMerge( GraphParsingTestEntity.class, expected, scope, graphs ); } @Test - public void testSameBasicsEqual() { - EntityGraph g = parseGraph( "name, description " ); - Assert.assertTrue( EntityGraphs.areEqual( g, g ) ); + public void testSameBasicsEqual(EntityManagerFactoryScope scope) { + EntityGraph g = parseGraph( "name, description ", scope ); + assertThat( EntityGraphs.areEqual( g, g ) ).isTrue(); } @Test - public void testEqualBasicsEqual() { - EntityGraph a = parseGraph( "name, description " ); - EntityGraph b = parseGraph( "description, name " ); - Assert.assertTrue( EntityGraphs.areEqual( a, b ) ); + public void testEqualBasicsEqual(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( "name, description ", scope ); + EntityGraph b = parseGraph( "description, name ", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isTrue(); } @Test - public void testDifferentBasicsEqual1() { - EntityGraph a = parseGraph( "name, description " ); - EntityGraph b = parseGraph( "description " ); - Assert.assertFalse( EntityGraphs.areEqual( a, b ) ); + public void testDifferentBasicsEqual1(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( "name, description ", scope ); + EntityGraph b = parseGraph( "description ", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isFalse(); } @Test - public void testDifferentBasicsEqual2() { - EntityGraph a = parseGraph( "name " ); - EntityGraph b = parseGraph( "description " ); - Assert.assertFalse( EntityGraphs.areEqual( a, b ) ); + public void testDifferentBasicsEqual2(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( "name ", scope ); + EntityGraph b = parseGraph( "description ", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isFalse(); } @Test - public void testEqualLinksEqual1() { - EntityGraph a = parseGraph( "linkToOne(name, description)" ); - EntityGraph b = parseGraph( "linkToOne(description, name)" ); - Assert.assertTrue( EntityGraphs.areEqual( a, b ) ); + public void testEqualLinksEqual1(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( "linkToOne(name, description)", scope ); + EntityGraph b = parseGraph( "linkToOne(description, name)", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isTrue(); } @Test - public void testEqualLinksWithSubclassesEqual() { - EntityGraph a = parseGraph( "linkToOne(name), linkToOne(GraphParsingTestSubEntity: description)" ); - EntityGraph b = parseGraph( "linkToOne(GraphParsingTestSubEntity: description), linkToOne(name)" ); - Assert.assertTrue( EntityGraphs.areEqual( a, b ) ); + public void testEqualLinksWithSubclassesEqual(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( + "linkToOne(name), linkToOne(GraphParsingTestSubEntity: description)", scope ); + EntityGraph b = parseGraph( + "linkToOne(GraphParsingTestSubEntity: description), linkToOne(name)", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isTrue(); } @Test - public void testDifferentLinksEqual1() { - EntityGraph a = parseGraph( "linkToOne(name, description)" ); - EntityGraph b = parseGraph( "linkToOne(description)" ); - Assert.assertFalse( EntityGraphs.areEqual( a, b ) ); + public void testDifferentLinksEqual1(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( "linkToOne(name, description)", scope ); + EntityGraph b = parseGraph( "linkToOne(description)", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isFalse(); } @Test - public void testDifferentLinksEqual2() { - EntityGraph a = parseGraph( "linkToOne(name)" ); - EntityGraph b = parseGraph( "linkToOne(description)" ); - Assert.assertFalse( EntityGraphs.areEqual( a, b ) ); + public void testDifferentLinksEqual2(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( "linkToOne(name)", scope ); + EntityGraph b = parseGraph( "linkToOne(description)", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isFalse(); } @Test - public void testDifferentLinksEqual3() { - EntityGraph a = parseGraph( "linkToOne(name), linkToOne(GraphParsingTestSubEntity: description)" ); - EntityGraph b = parseGraph( "linkToOne(name, description)" ); - Assert.assertFalse( EntityGraphs.areEqual( a, b ) ); + public void testDifferentLinksEqual3(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( + "linkToOne(name), linkToOne(GraphParsingTestSubEntity: description)", scope ); + EntityGraph b = parseGraph( "linkToOne(name, description)", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isFalse(); } @Test - public void testEqualMapKeysEqual() { - EntityGraph a = parseGraph( "map.key(name, description)" ); - EntityGraph b = parseGraph( "map.key(description, name)" ); - Assert.assertTrue( EntityGraphs.areEqual( a, b ) ); + public void testEqualMapKeysEqual(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( "map.key(name, description)", scope ); + EntityGraph b = parseGraph( "map.key(description, name)", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isTrue(); } @Test - public void testDifferentMapKeysEqual1() { - EntityGraph a = parseGraph( "map.key(name, description)" ); - EntityGraph b = parseGraph( "map.key(description)" ); - Assert.assertFalse( EntityGraphs.areEqual( a, b ) ); + public void testDifferentMapKeysEqual1(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( "map.key(name, description)", scope ); + EntityGraph b = parseGraph( "map.key(description)", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isFalse(); } @Test - public void testDifferentMapKeysEqual2() { - EntityGraph a = parseGraph( "map.key(name)" ); - EntityGraph b = parseGraph( "map.key(description)" ); - Assert.assertFalse( EntityGraphs.areEqual( a, b ) ); + public void testDifferentMapKeysEqual2(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( "map.key(name)", scope ); + EntityGraph b = parseGraph( "map.key(description)", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isFalse(); } @Test - public void testEqualMapValuesEqual() { - EntityGraph a = parseGraph( "map.value(name, description)" ); - EntityGraph b = parseGraph( "map.value(description, name)" ); - Assert.assertTrue( EntityGraphs.areEqual( a, b ) ); + public void testEqualMapValuesEqual(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( "map.value(name, description)", scope ); + EntityGraph b = parseGraph( "map.value(description, name)", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isTrue(); } @Test - public void testDifferentMapValuesEqual1() { - EntityGraph a = parseGraph( "map.value(name, description)" ); - EntityGraph b = parseGraph( "map.value(description)" ); - Assert.assertFalse( EntityGraphs.areEqual( a, b ) ); + public void testDifferentMapValuesEqual1(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( "map.value(name, description)", scope ); + EntityGraph b = parseGraph( "map.value(description)", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isFalse(); } @Test - public void testDifferentMapValuesEqual2() { - EntityGraph a = parseGraph( "map.value(name)" ); - EntityGraph b = parseGraph( "map.value(description)" ); - Assert.assertFalse( EntityGraphs.areEqual( a, b ) ); + public void testDifferentMapValuesEqual2(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( "map.value(name)", scope ); + EntityGraph b = parseGraph( "map.value(description)", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isFalse(); } @Test - public void testEqualComplexGraphsEqual() { - EntityGraph a = parseGraph( "map.key(name, description), name, linkToOne(description), description" ); - EntityGraph b = parseGraph( "description, map.key(description, name), name, linkToOne(description)" ); - Assert.assertTrue( EntityGraphs.areEqual( a, b ) ); + public void testEqualComplexGraphsEqual(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( + "map.key(name, description), name, linkToOne(description), description", scope ); + EntityGraph b = parseGraph( + "description, map.key(description, name), name, linkToOne(description)", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isTrue(); } @Test - public void testDifferentComplexGraphsEqual() { - EntityGraph a = parseGraph( "map.key(name, description), name, linkToOne(description), description" ); - EntityGraph b = parseGraph( "description, map.value(description, name), name, linkToOne(description)" ); - Assert.assertFalse( EntityGraphs.areEqual( a, b ) ); + public void testDifferentComplexGraphsEqual(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( + "map.key(name, description), name, linkToOne(description), description", scope ); + EntityGraph b = parseGraph( + "description, map.value(description, name), name, linkToOne(description)", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isFalse(); } @Test public void testNullsEqual() { - Assert.assertTrue( EntityGraphs.areEqual( (EntityGraph) null, (EntityGraph) null ) ); + assertThat( EntityGraphs.areEqual( null, (EntityGraph) null ) ).isTrue(); } @Test - public void testNullAndNonNullEqual() { - EntityGraph graph = parseGraph( "name " ); - Assert.assertFalse( EntityGraphs.areEqual( graph, (EntityGraph) null ) ); - Assert.assertFalse( EntityGraphs.areEqual( (EntityGraph) null, graph ) ); + public void testNullAndNonNullEqual(EntityManagerFactoryScope scope) { + EntityGraph graph = parseGraph( "name ", scope ); + assertThat( EntityGraphs.areEqual( graph, null ) ).isFalse(); + assertThat( EntityGraphs.areEqual( null, graph ) ).isFalse(); } @Test - public void testBasicMerge() { - EntityGraph g1 = parseGraph( "name" ); - EntityGraph g2 = parseGraph( "description" ); - EntityGraph expected = parseGraph( "name, description " ); - checkMerge( expected, g1, g2 ); + public void testBasicMerge(EntityManagerFactoryScope scope) { + EntityGraph g1 = parseGraph( "name", scope ); + EntityGraph g2 = parseGraph( "description", scope ); + EntityGraph expected = parseGraph( "name, description ", scope ); + checkMerge( expected, scope, g1, g2 ); } @Test - public void testLinkMerge() { - EntityGraph g1 = parseGraph( "linkToOne(name)" ); - EntityGraph g2 = parseGraph( "linkToOne(description)" ); - EntityGraph expected = parseGraph( "linkToOne(name, description) " ); - checkMerge( expected, g1, g2 ); + public void testLinkMerge(EntityManagerFactoryScope scope) { + EntityGraph g1 = parseGraph( "linkToOne(name)", scope ); + EntityGraph g2 = parseGraph( "linkToOne(description)", scope ); + EntityGraph expected = parseGraph( "linkToOne(name, description) ", scope ); + checkMerge( expected, scope, g1, g2 ); } @Test - public void testMapKeyMerge() { - EntityGraph g1 = parseGraph( "map.key(name)" ); - EntityGraph g2 = parseGraph( "map.key(description)" ); - EntityGraph expected = parseGraph( "map.key(name, description) " ); - checkMerge( expected, g1, g2 ); + public void testMapKeyMerge(EntityManagerFactoryScope scope) { + EntityGraph g1 = parseGraph( "map.key(name)", scope ); + EntityGraph g2 = parseGraph( "map.key(description)", scope ); + EntityGraph expected = parseGraph( "map.key(name, description) ", scope ); + checkMerge( expected, scope, g1, g2 ); } @Test - public void testMapValueMerge() { - EntityGraph g1 = parseGraph( "map.value(name)" ); - EntityGraph g2 = parseGraph( "map.value(description)" ); - EntityGraph expected = parseGraph( "map.value(name, description) " ); - checkMerge( expected, g1, g2 ); + public void testMapValueMerge(EntityManagerFactoryScope scope) { + EntityGraph g1 = parseGraph( "map.value(name)", scope ); + EntityGraph g2 = parseGraph( "map.value(description)", scope ); + EntityGraph expected = parseGraph( "map.value(name, description) ", scope ); + checkMerge( expected, scope, g1, g2 ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/entitymode/dom4j/DeprecationLoggingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/entitymode/dom4j/DeprecationLoggingTest.java index f66f4ea85963..aa7644f57f9a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/entitymode/dom4j/DeprecationLoggingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/entitymode/dom4j/DeprecationLoggingTest.java @@ -9,12 +9,11 @@ import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; import org.hibernate.internal.log.DeprecationLogger; import org.hibernate.service.ServiceRegistry; - -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.hibernate.testing.logger.LoggerInspectionRule; +import org.hibernate.testing.orm.junit.BaseUnitTest; +import org.hibernate.testing.orm.logger.LoggerInspectionExtension; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; /** * Tests that {@code hbm.xml} mappings that do not specify dom4j entity-mode information @@ -22,23 +21,24 @@ * * @author Steve Ebersole */ -public class DeprecationLoggingTest extends BaseUnitTestCase { - - @Rule - public LoggerInspectionRule logInspection = new LoggerInspectionRule( DeprecationLogger.DEPRECATION_LOGGER ); +@BaseUnitTest +public class DeprecationLoggingTest { + @RegisterExtension + public LoggerInspectionExtension logInspection = LoggerInspectionExtension.builder() + .setLogger( DeprecationLogger.DEPRECATION_LOGGER ).build(); @Test public void basicTest() { logInspection.registerListener( LogListenerImpl.INSTANCE ); MetadataSources metadataSources = new MetadataSources( ServiceRegistryUtil.serviceRegistry() ) - .addResource( "org/hibernate/orm/test/entitymode/dom4j/Car.hbm.xml" ); + .addResource( "org/hibernate/orm/test/entitymode/dom4j/Car.hbm.xml" ); try { metadataSources.buildMetadata(); } finally { ServiceRegistry metaServiceRegistry = metadataSources.getServiceRegistry(); - if(metaServiceRegistry instanceof BootstrapServiceRegistry ) { + if ( metaServiceRegistry instanceof BootstrapServiceRegistry ) { BootstrapServiceRegistryBuilder.destroy( metaServiceRegistry ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/foreignkeys/HHH14230.java b/hibernate-core/src/test/java/org/hibernate/orm/test/foreignkeys/HHH14230.java index c84834482bc7..811ee78407c2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/foreignkeys/HHH14230.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/foreignkeys/HHH14230.java @@ -4,24 +4,21 @@ */ package org.hibernate.orm.test.foreignkeys; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.stream.StreamSupport; - import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; - import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.mapping.Table; import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import java.util.stream.StreamSupport; + +import static org.assertj.core.api.Assertions.assertThat; /** * @author Yanming Zhou @@ -40,11 +37,11 @@ public void test() { Table table = StreamSupport.stream( metadata.getDatabase().getNamespaces().spliterator(), false ) .flatMap( namespace -> namespace.getTables().stream() ) .filter( t -> t.getName().equals( TABLE_NAME ) ).findFirst().orElse( null ); - assertNotNull( table ); - assertEquals( 1, table.getForeignKeyCollection().size() ); + assertThat( table ).isNotNull(); + assertThat( table.getForeignKeyCollection() ).hasSize( 1 ); // ClassCastException before HHH-14230 - assertTrue( table.getForeignKeys().keySet().iterator().next().toString().contains( JOIN_COLUMN_NAME ) ); + assertThat( table.getForeignKeys().keySet().iterator().next().toString() ).contains( JOIN_COLUMN_NAME ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/foreignkeys/disabled/DefaultConstraintModeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/foreignkeys/disabled/DefaultConstraintModeTest.java index 59865c18f5eb..04f11229c3f4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/foreignkeys/disabled/DefaultConstraintModeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/foreignkeys/disabled/DefaultConstraintModeTest.java @@ -4,20 +4,6 @@ */ package org.hibernate.orm.test.foreignkeys.disabled; -import java.util.List; -import java.util.stream.StreamSupport; - -import org.hibernate.boot.Metadata; -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.cfg.Environment; -import org.hibernate.mapping.Table; - -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.hibernate.testing.orm.junit.Jira; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; - import jakarta.persistence.ElementCollection; import jakarta.persistence.Entity; import jakarta.persistence.Id; @@ -27,16 +13,29 @@ import jakarta.persistence.ManyToMany; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistry; +import org.hibernate.cfg.Environment; +import org.hibernate.mapping.Table; +import org.hibernate.testing.orm.junit.BaseUnitTest; +import org.hibernate.testing.orm.junit.Jira; +import org.hibernate.testing.util.ServiceRegistryUtil; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.stream.StreamSupport; + +import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; /** * @author Yanming Zhou */ -@Jira( "https://hibernate.atlassian.net/browse/HHH-14253" ) -@Jira( "https://hibernate.atlassian.net/browse/HHH-17550" ) -public class DefaultConstraintModeTest extends BaseUnitTestCase { +@Jira("https://hibernate.atlassian.net/browse/HHH-14253") +@Jira("https://hibernate.atlassian.net/browse/HHH-17550") +@BaseUnitTest +public class DefaultConstraintModeTest { @Test public void testForeignKeyShouldNotBeCreated() { testForeignKeyCreation( false ); @@ -51,9 +50,12 @@ private void testForeignKeyCreation(boolean created) { try (StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder() .applySetting( Environment.HBM2DDL_DEFAULT_CONSTRAINT_MODE, created ? "CONSTRAINT" : "NO_CONSTRAINT" ) .build()) { - Metadata metadata = new MetadataSources( ssr ).addAnnotatedClasses( TestEntity.class, ChildEntity.class ).buildMetadata(); - assertThat( findTable( metadata, "TestEntity" ).getForeignKeyCollection().isEmpty(), is( !created ) ); - assertThat( findTable( metadata, "ChildEntity" ).getForeignKeyCollection().isEmpty(), is( !created ) ); + Metadata metadata = new MetadataSources( ssr ).addAnnotatedClasses( TestEntity.class, ChildEntity.class ) + .buildMetadata(); + assertThat( findTable( metadata, "TestEntity" ).getForeignKeyCollection().isEmpty() ) + .isEqualTo( !created ); + assertThat( findTable( metadata, "ChildEntity" ).getForeignKeyCollection().isEmpty() ) + .isEqualTo( !created ); } } @@ -63,9 +65,9 @@ private static Table findTable(Metadata metadata, String tableName) { .findFirst().orElse( null ); } - @Entity( name = "TestEntity" ) - @jakarta.persistence.Table( name = "TestEntity" ) - @Inheritance( strategy = InheritanceType.JOINED ) + @Entity(name = "TestEntity") + @jakarta.persistence.Table(name = "TestEntity") + @Inheritance(strategy = InheritanceType.JOINED) public static class TestEntity { @Id @@ -85,8 +87,8 @@ public static class TestEntity { private List elements; } - @Entity( name = "ChildEntity" ) - @jakarta.persistence.Table( name = "ChildEntity" ) + @Entity(name = "ChildEntity") + @jakarta.persistence.Table(name = "ChildEntity") public static class ChildEntity extends TestEntity { private String childName; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/foreignkeys/disabled/DisabledForeignKeyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/foreignkeys/disabled/DisabledForeignKeyTest.java index e48c0a873b48..e74dbaeb445d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/foreignkeys/disabled/DisabledForeignKeyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/foreignkeys/disabled/DisabledForeignKeyTest.java @@ -4,32 +4,32 @@ */ package org.hibernate.orm.test.foreignkeys.disabled; -import java.util.EnumSet; - import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.mapping.Table; +import org.hibernate.testing.orm.junit.BaseUnitTest; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.util.ServiceRegistryUtil; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.hbm2ddl.SchemaUpdate; import org.hibernate.tool.schema.TargetType; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import java.util.EnumSet; + +import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; /** * @author Steve Ebersole */ -public class DisabledForeignKeyTest extends BaseUnitTestCase { +@BaseUnitTest +public class DisabledForeignKeyTest { @Test - @JiraKey( value = "HHH-9704" ) + @JiraKey(value = "HHH-9704") public void basicTests() { StandardServiceRegistry standardRegistry = ServiceRegistryUtil.serviceRegistry(); try { @@ -51,17 +51,18 @@ public void basicTests() { int fkCount = 0; for ( Table table : metadata.collectTableMappings() ) { for ( var entry : table.getForeignKeys().entrySet() ) { - assertFalse( - "Creation for ForeignKey [" + entry.getKey() + "] was not disabled", - entry.getValue().isCreationEnabled() - ); + assertThat( entry.getValue().isCreationEnabled() ) + .describedAs( "Creation for ForeignKey [" + entry.getKey() + "] was not disabled" ) + .isFalse(); fkCount++; } } // ultimately I want to actually create the ForeignKet reference, but simply disable its creation // via ForeignKet#disableCreation() - assertEquals( "Was expecting 4 FKs", 0, fkCount ); + assertThat( fkCount ) + .describedAs( "Was expecting 4 FKs" ) + .isEqualTo( 0 ); } finally { StandardServiceRegistryBuilder.destroy( standardRegistry ); @@ -69,7 +70,7 @@ public void basicTests() { } @Test - @JiraKey( value = "HHH-9704" ) + @JiraKey(value = "HHH-9704") public void expandedTests() { StandardServiceRegistry standardRegistry = ServiceRegistryUtil.serviceRegistry(); try { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/foreignkeys/disabled/InheritanceManyToManyForeignKeyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/foreignkeys/disabled/InheritanceManyToManyForeignKeyTest.java index 0787a34c0680..06e494142569 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/foreignkeys/disabled/InheritanceManyToManyForeignKeyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/foreignkeys/disabled/InheritanceManyToManyForeignKeyTest.java @@ -4,9 +4,6 @@ */ package org.hibernate.orm.test.foreignkeys.disabled; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.List; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; @@ -16,74 +13,72 @@ import jakarta.persistence.InheritanceType; import jakarta.persistence.ManyToMany; import jakarta.persistence.MappedSuperclass; - -import org.hibernate.Session; -import org.hibernate.Transaction; import org.hibernate.dialect.SybaseDialect; - -import org.hibernate.testing.SkipForDialect; +import org.hibernate.testing.orm.junit.DomainModel; 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.hibernate.testing.orm.junit.SkipForDialect; +import org.junit.jupiter.api.Test; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Vlad Mihalcea */ @JiraKey(value = "HHH-9306") -public class InheritanceManyToManyForeignKeyTest extends BaseNonConfigCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - LocalDateEvent.class, - UserEvents.class, - ApplicationEvents.class - }; - } - - @Test - @SkipForDialect(value = SybaseDialect.class, comment = "Only dates between January 1, 1753 and December 31, 9999 are accepted.") - public void testForeignKeyNameUnicity() { - Session session = openSession(); - Transaction transaction = session.beginTransaction(); +@DomainModel( + annotatedClasses = {InheritanceManyToManyForeignKeyTest.LocalDateEvent.class, + InheritanceManyToManyForeignKeyTest.UserEvents.class, + InheritanceManyToManyForeignKeyTest.ApplicationEvents.class - LocalDateEvent event1 = new LocalDateEvent(); - event1.startDate = LocalDate.of(1, 1, 1); - session.persist(event1); - - LocalDateEvent event2 = new LocalDateEvent(); - event2.startDate = LocalDate.of(1, 1, 2); - session.persist(event2); - - LocalDateEvent event3 = new LocalDateEvent(); - event3.startDate = LocalDate.of(1, 1, 3); - session.persist(event3); + } +) +@SessionFactory +public class InheritanceManyToManyForeignKeyTest { + @Test + @SkipForDialect(dialectClass = SybaseDialect.class, matchSubTypes = true, + reason = "Only dates between January 1, 1753 and December 31, 9999 are accepted.") + public void testForeignKeyNameUnicity(SessionFactoryScope scope) { UserEvents userEvents = new UserEvents(); - session.persist( userEvents ); - userEvents.getEvents().add( event1 ); - session.flush(); - userEvents.getEvents().add( event2 ); - session.flush(); - - ApplicationEvents applicationEvents = new ApplicationEvents(); - session.persist( applicationEvents ); - applicationEvents.getEvents().add( event3 ); - - transaction.commit(); - session.close(); - - session = openSession(); - transaction = session.beginTransaction(); - - assertEquals(2, session.get( UserEvents.class, userEvents.id ).getEvents().size()); - assertEquals(1, session.get( ApplicationEvents.class, applicationEvents.id ).getEvents().size()); - - transaction.commit(); - session.close(); + scope.inTransaction( + session -> { + LocalDateEvent event1 = new LocalDateEvent(); + event1.startDate = LocalDate.of( 1, 1, 1 ); + session.persist( event1 ); + + LocalDateEvent event2 = new LocalDateEvent(); + event2.startDate = LocalDate.of( 1, 1, 2 ); + session.persist( event2 ); + + LocalDateEvent event3 = new LocalDateEvent(); + event3.startDate = LocalDate.of( 1, 1, 3 ); + session.persist( event3 ); + + + session.persist( userEvents ); + userEvents.getEvents().add( event1 ); + session.flush(); + userEvents.getEvents().add( event2 ); + session.flush(); + + session.persist( applicationEvents ); + applicationEvents.getEvents().add( event3 ); + } + ); + + scope.inTransaction( + session -> { + assertThat( session.get( UserEvents.class, userEvents.id ).getEvents() ).hasSize( 2 ); + assertThat( session.get( ApplicationEvents.class, applicationEvents.id ).getEvents() ).hasSize( 1 ); + } + ); } @Entity(name = "LDE") @@ -100,8 +95,8 @@ public static class LocalDateEvent { @MappedSuperclass public static abstract class AbstractEventsEntityModel { - @ManyToMany(fetch = FetchType.LAZY ) - private List events = new ArrayList<>( ); + @ManyToMany(fetch = FetchType.LAZY) + private List events = new ArrayList<>(); public List getEvents() { return events; @@ -125,6 +120,5 @@ public static class ApplicationEvents extends AbstractEventsEntityModel { @Id @GeneratedValue private Long id; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/foreignkeys/disabled/OneToManyBidirectionalForeignKeyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/foreignkeys/disabled/OneToManyBidirectionalForeignKeyTest.java index a6d3f4f5200d..b2d7b2f82db4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/foreignkeys/disabled/OneToManyBidirectionalForeignKeyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/foreignkeys/disabled/OneToManyBidirectionalForeignKeyTest.java @@ -4,13 +4,6 @@ */ package org.hibernate.orm.test.foreignkeys.disabled; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.stream.StreamSupport; - import jakarta.persistence.CascadeType; import jakarta.persistence.ConstraintMode; import jakarta.persistence.Entity; @@ -19,7 +12,6 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; - import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; import org.hibernate.boot.Metadata; @@ -28,7 +20,14 @@ import org.hibernate.mapping.Table; import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.stream.StreamSupport; + +import static org.assertj.core.api.Assertions.assertThat; + /** * {@inheritDoc} @@ -47,15 +46,17 @@ public void testForeignKeyShouldNotBeCreated() { Metadata metadata = new MetadataSources( serviceRegistry ) .addAnnotatedClass( PlainTreeEntity.class ).addAnnotatedClass( TreeEntityWithOnDelete.class ) .buildMetadata(); - assertTrue( findTable( metadata, TABLE_NAME_PLAIN ).getForeignKeyCollection().isEmpty() ); - assertFalse( findTable( metadata, TABLE_NAME_WITH_ON_DELETE ).getForeignKeyCollection().isEmpty() ); + assertThat( findTable( metadata, TABLE_NAME_PLAIN ).getForeignKeyCollection().isEmpty() ) + .isTrue(); + assertThat( findTable( metadata, TABLE_NAME_WITH_ON_DELETE ).getForeignKeyCollection().isEmpty() ) + .isFalse(); } } private static Table findTable(Metadata metadata, String tableName) { - return StreamSupport.stream(metadata.getDatabase().getNamespaces().spliterator(), false) - .flatMap(namespace -> namespace.getTables().stream()).filter(t -> t.getName().equals(tableName)) - .findFirst().orElse(null); + return StreamSupport.stream( metadata.getDatabase().getNamespaces().spliterator(), false ) + .flatMap( namespace -> namespace.getTables().stream() ).filter( t -> t.getName().equals( tableName ) ) + .findFirst().orElse( null ); } @Entity @@ -72,7 +73,7 @@ public static class PlainTreeEntity { @OneToMany(mappedBy = "parent") // workaround // @org.hibernate.annotations.ForeignKey(name = "none") - private Collection children = new ArrayList<>(0); + private Collection children = new ArrayList<>( 0 ); } @Entity @@ -88,7 +89,7 @@ public static class TreeEntityWithOnDelete { @OneToMany(mappedBy = "parent", cascade = CascadeType.REMOVE) @OnDelete(action = OnDeleteAction.CASCADE) - private Collection children = new ArrayList<>(0); + private Collection children = new ArrayList<>( 0 ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/formulajoin/Detail.java b/hibernate-core/src/test/java/org/hibernate/orm/test/formulajoin/Detail.java index c6327ee7431c..4c13c0ac4748 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/formulajoin/Detail.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/formulajoin/Detail.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.formulajoin; + import java.io.Serializable; /** diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/formulajoin/FormulaJoinTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/formulajoin/FormulaJoinTest.java index 9f6c525f460b..9abfa35e6b83 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/formulajoin/FormulaJoinTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/formulajoin/FormulaJoinTest.java @@ -4,115 +4,114 @@ */ package org.hibernate.orm.test.formulajoin; -import java.util.List; - -import org.hibernate.Session; -import org.hibernate.Transaction; import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; import org.hibernate.dialect.PostgreSQLDialect; +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 java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Gavin King */ -public class FormulaJoinTest extends BaseCoreFunctionalTestCase { - - @Override - public String[] getMappings() { - return new String[] { "formulajoin/Root.hbm.xml" }; - } - - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - configuration.setProperty( AvailableSettings.JPA_METAMODEL_POPULATION, "enabled" ); - } +@DomainModel( + xmlMappings = "org/hibernate/orm/test/formulajoin/Root.hbm.xml" +) +@SessionFactory +@ServiceRegistry( + settings = @Setting(name = AvailableSettings.JPA_METAMODEL_POPULATION, value = "enabled") +) +public class FormulaJoinTest { @Test - public void testFormulaJoin() { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Root root = new Root(); - root.setName("root 1"); - Detail current = new Detail(); - current.setCurrentVersion(true); - current.setVersion(2); - current.setDetails("details of root 1 blah blah"); - current.setRoot( root ); - root.setDetail(current); - Detail past = new Detail(); - past.setCurrentVersion(false); - past.setVersion(1); - past.setDetails("old details of root 1 yada yada"); - past.setRoot( root ); - s.persist( root ); - s.persist(past); - s.persist(current); - tx.commit(); - s.close(); - - if ( getDialect() instanceof PostgreSQLDialect ) return; - - s = openSession(); - tx = s.beginTransaction(); - List l = s.createQuery("from Root m left join m.detail d", Object[].class).list(); - assertEquals( l.size(), 1 ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - l = s.createQuery("from Root m left join fetch m.detail").list(); - assertEquals( l.size(), 1 ); - Root m = (Root) l.get(0); - assertEquals( "root 1", m.getDetail().getRoot().getName() ); - assertTrue( m==m.getDetail().getRoot() ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - l = s.createQuery("from Root m join fetch m.detail").list(); - assertEquals( l.size(), 1 ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - l = s.createQuery("from Detail d join fetch d.currentRoot.root").list(); - assertEquals( l.size(), 2 ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - l = s.createQuery("from Detail d join fetch d.root").list(); - assertEquals( l.size(), 2 ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - l = s.createQuery("from Detail d join fetch d.currentRoot.root m join fetch m.detail").list(); - assertEquals( l.size(), 2 ); - tx.commit(); - - s = openSession(); - tx = s.beginTransaction(); - l = s.createQuery("from Detail d join fetch d.root m join fetch m.detail").list(); - assertEquals( l.size(), 2 ); - - s.createQuery("delete from Detail").executeUpdate(); - s.createQuery("delete from Root").executeUpdate(); - - tx.commit(); - s.close(); - + public void testFormulaJoin(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Root root = new Root(); + root.setName( "root 1" ); + Detail current = new Detail(); + current.setCurrentVersion( true ); + current.setVersion( 2 ); + current.setDetails( "details of root 1 blah blah" ); + current.setRoot( root ); + root.setDetail( current ); + Detail past = new Detail(); + past.setCurrentVersion( false ); + past.setVersion( 1 ); + past.setDetails( "old details of root 1 yada yada" ); + past.setRoot( root ); + session.persist( root ); + session.persist( past ); + session.persist( current ); + } + ); + + if ( scope.getSessionFactory().getJdbcServices().getDialect() instanceof PostgreSQLDialect ) { + return; + } + + scope.inTransaction( + session -> { + List l = session.createQuery( "from Root m left join m.detail d", Object[].class ).list(); + assertThat( l ).hasSize( 1 ); + } + ); + + scope.inTransaction( + session -> { + List l = session.createQuery( "from Root m left join fetch m.detail", Root.class ).list(); + assertThat( l ).hasSize( 1 ); + Root m = l.get( 0 ); + assertThat( m.getDetail().getRoot().getName() ).isEqualTo( "root 1" ); + assertThat( m.getDetail().getRoot() ).isEqualTo( m ); + } + ); + + scope.inTransaction( + session -> { + List l = session.createQuery( "from Root m join fetch m.detail", Root.class ).list(); + assertThat( l ).hasSize( 1 ); + } + ); + + scope.inTransaction( + session -> { + List l = session.createQuery( "from Detail d join fetch d.currentRoot.root", Detail.class ) + .list(); + assertThat( l ).hasSize( 2 ); + } + ); + + scope.inTransaction( + session -> { + List l = session.createQuery( "from Detail d join fetch d.root", Detail.class ).list(); + assertThat( l ).hasSize( 2 ); + } + ); + + scope.inTransaction( + session -> { + List l = session.createQuery( "from Detail d join fetch d.currentRoot.root m join fetch m.detail", + Detail.class ).list(); + assertThat( l ).hasSize( 2 ); + } + ); + + scope.inTransaction( + session -> { + List l = session.createQuery( "from Detail d join fetch d.root m join fetch m.detail", + Detail.class ).list(); + assertThat( l ).hasSize( 2 ); + + session.createMutationQuery( "delete from Detail" ).executeUpdate(); + session.createMutationQuery( "delete from Root" ).executeUpdate(); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/generatedkeys/identity/IdentityGeneratedKeysTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/generatedkeys/identity/IdentityGeneratedKeysTest.java index 5403dd91a429..f08a31778b30 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/generatedkeys/identity/IdentityGeneratedKeysTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/generatedkeys/identity/IdentityGeneratedKeysTest.java @@ -4,171 +4,169 @@ */ package org.hibernate.orm.test.generatedkeys.identity; -import jakarta.persistence.PersistenceException; import jakarta.persistence.TransactionRequiredException; +import org.hibernate.stat.spi.StatisticsImplementor; +import org.hibernate.testing.orm.junit.DialectFeatureChecks; +import org.hibernate.testing.orm.junit.DomainModel; +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 org.junit.Test; - -import org.hibernate.Session; -import org.hibernate.cfg.Configuration; -import org.hibernate.cfg.Environment; -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; - -import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; -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 static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Steve Ebersole */ -@RequiresDialectFeature( DialectChecks.SupportsIdentityColumns.class ) -public class IdentityGeneratedKeysTest extends BaseCoreFunctionalTestCase { +@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsIdentityColumns.class) +@DomainModel( + xmlMappings = "org/hibernate/orm/test/generatedkeys/identity/MyEntity.hbm.xml" +) +@SessionFactory( + generateStatistics = true +) +public class IdentityGeneratedKeysTest { - @Override - public void configure(Configuration cfg) { - super.configure( cfg ); - cfg.setProperty( Environment.GENERATE_STATISTICS, true ); + @Test + public void testIdentityColumnGeneratedIds(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + MyEntity myEntity = new MyEntity( "test" ); + session.persist( myEntity ); + assertThat( myEntity.getId() ) + .describedAs( "identity column did not force immediate insert" ) + .isNotNull(); + session.remove( myEntity ); + } + ); } - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } + @Test + public void testPersistOutsideTransaction(SessionFactoryScope scope) { + scope.inSession( + session -> { + try { + StatisticsImplementor statistics = scope.getSessionFactory().getStatistics(); + long initialInsertCount = statistics.getEntityInsertCount(); + MyEntity myEntity2 = new MyEntity( "test-persist" ); + session.persist( myEntity2 ); + assertThat( statistics.getEntityInsertCount() ) + .describedAs( "persist on identity column not delayed" ) + .isEqualTo( initialInsertCount ); + assertThat( myEntity2.getId() ).isNull(); - @Override - public String[] getMappings() { - return new String[] { "generatedkeys/identity/MyEntity.hbm.xml" }; + // an explicit flush should cause execution of the delayed insertion + session.flush(); + fail( "TransactionRequiredException required upon flush" ); + } + catch (TransactionRequiredException ex) { + // expected + } + } + ); } @Test - public void testIdentityColumnGeneratedIds() { - Session s = openSession(); - s.beginTransaction(); - MyEntity myEntity = new MyEntity( "test" ); - s.persist(myEntity); - assertNotNull( "identity column did not force immediate insert", myEntity.getId() ); - s.remove( myEntity ); - s.getTransaction().commit(); - s.close(); + public void testPersistOutsideTransactionCascadedToNonInverseCollection(SessionFactoryScope scope) { + StatisticsImplementor statistics = scope.getSessionFactory().getStatistics(); + + long initialInsertCount = statistics.getEntityInsertCount(); + scope.inSession( + session -> { + try { + MyEntity myEntity = new MyEntity( "test-persist" ); + myEntity.getNonInverseChildren().add( new MyChild( "test-child-persist-non-inverse" ) ); + session.persist( myEntity ); + assertThat( statistics.getEntityInsertCount() ) + .describedAs( "persist on identity column not delayed" ) + .isEqualTo( initialInsertCount ); + assertThat( myEntity.getId() ).isNull(); + session.flush(); + fail( "TransactionRequiredException required upon flush" ); + } + catch (TransactionRequiredException ex) { + // expected + } + } + ); } @Test - public void testPersistOutsideTransaction() { - Session s = openSession(); - try { - long initialInsertCount = sessionFactory().getStatistics().getEntityInsertCount(); - MyEntity myEntity2 = new MyEntity( "test-persist" ); - s.persist( myEntity2 ); - assertEquals( "persist on identity column not delayed", initialInsertCount, sessionFactory().getStatistics().getEntityInsertCount() ); - assertNull( myEntity2.getId() ); + public void testPersistOutsideTransactionCascadedToInverseCollection(SessionFactoryScope scope) { + StatisticsImplementor statistics = scope.getSessionFactory().getStatistics(); - // an explicit flush should cause execution of the delayed insertion - s.flush(); - fail( "TransactionRequiredException required upon flush" ); - } - catch ( PersistenceException ex ) { - // expected - assertTyping( TransactionRequiredException.class, ex ); - } - finally { - s.close(); - } + long initialInsertCount = statistics.getEntityInsertCount(); + scope.inSession( + session -> { + try { + MyEntity myEntity2 = new MyEntity( "test-persist-2" ); + MyChild child = new MyChild( "test-child-persist-inverse" ); + myEntity2.getInverseChildren().add( child ); + child.setInverseParent( myEntity2 ); + session.persist( myEntity2 ); + assertThat( statistics.getEntityInsertCount() ) + .describedAs( "persist on identity column not delayed" ) + .isEqualTo( initialInsertCount ); + assertThat( myEntity2.getId() ).isNull(); + session.flush(); + fail( "TransactionRequiredException expected upon flush." ); + } + catch (TransactionRequiredException ex) { + // expected + } + } + ); } @Test - @SuppressWarnings( {"unchecked"}) - public void testPersistOutsideTransactionCascadedToNonInverseCollection() { - long initialInsertCount = sessionFactory().getStatistics().getEntityInsertCount(); - Session s = openSession(); - try { - MyEntity myEntity = new MyEntity( "test-persist" ); - myEntity.getNonInverseChildren().add( new MyChild( "test-child-persist-non-inverse" ) ); - s.persist( myEntity ); - assertEquals( "persist on identity column not delayed", initialInsertCount, sessionFactory().getStatistics().getEntityInsertCount() ); - assertNull( myEntity.getId() ); - s.flush(); - fail( "TransactionRequiredException required upon flush" ); - } - catch ( PersistenceException ex ) { - // expected - assertTyping( TransactionRequiredException.class, ex ); - } - finally { - s.close(); - } - } + public void testPersistOutsideTransactionCascadedToManyToOne(SessionFactoryScope scope) { + StatisticsImplementor statistics = scope.getSessionFactory().getStatistics(); - @Test - @SuppressWarnings( {"unchecked"}) - public void testPersistOutsideTransactionCascadedToInverseCollection() { - long initialInsertCount = sessionFactory().getStatistics().getEntityInsertCount(); - Session s = openSession(); - try { - MyEntity myEntity2 = new MyEntity( "test-persist-2" ); - MyChild child = new MyChild( "test-child-persist-inverse" ); - myEntity2.getInverseChildren().add( child ); - child.setInverseParent( myEntity2 ); - s.persist( myEntity2 ); - assertEquals( "persist on identity column not delayed", initialInsertCount, sessionFactory().getStatistics().getEntityInsertCount() ); - assertNull( myEntity2.getId() ); - s.flush(); - fail( "TransactionRequiredException expected upon flush." ); - } - catch ( PersistenceException ex ) { - // expected - assertTyping( TransactionRequiredException.class, ex ); - } - finally { - s.close(); - } + long initialInsertCount = statistics.getEntityInsertCount(); + scope.inSession( + session -> { + try { + MyEntity myEntity = new MyEntity( "test-persist" ); + myEntity.setSibling( new MySibling( "test-persist-sibling-out" ) ); + session.persist( myEntity ); + assertThat( statistics.getEntityInsertCount() ) + .describedAs( "persist on identity column not delayed" ) + .isEqualTo( initialInsertCount ); + assertThat( myEntity.getId() ).isNull(); + session.flush(); + fail( "TransactionRequiredException expected upon flush." ); + } + catch (TransactionRequiredException ex) { + // expected + } + } + ); } @Test - public void testPersistOutsideTransactionCascadedToManyToOne() { - long initialInsertCount = sessionFactory().getStatistics().getEntityInsertCount(); - Session s = openSession(); - try { - MyEntity myEntity = new MyEntity( "test-persist" ); - myEntity.setSibling( new MySibling( "test-persist-sibling-out" ) ); - s.persist( myEntity ); - assertEquals( "persist on identity column not delayed", initialInsertCount, sessionFactory().getStatistics().getEntityInsertCount() ); - assertNull( myEntity.getId() ); - s.flush(); - fail( "TransactionRequiredException expected upon flush." ); - } - catch ( PersistenceException ex ) { - // expected - assertTyping( TransactionRequiredException.class, ex ); - } - finally { - s.close(); - } - } + public void testPersistOutsideTransactionCascadedFromManyToOne(SessionFactoryScope scope) { + StatisticsImplementor statistics = scope.getSessionFactory().getStatistics(); - @Test - public void testPersistOutsideTransactionCascadedFromManyToOne() { - long initialInsertCount = sessionFactory().getStatistics().getEntityInsertCount(); - Session s = openSession(); - try { - MyEntity myEntity2 = new MyEntity( "test-persist-2" ); - MySibling sibling = new MySibling( "test-persist-sibling-in" ); - sibling.setEntity( myEntity2 ); - s.persist( sibling ); - assertEquals( "persist on identity column not delayed", initialInsertCount, sessionFactory().getStatistics().getEntityInsertCount() ); - assertNull( myEntity2.getId() ); - s.flush(); - fail( "TransactionRequiredException expected upon flush." ); - } - catch ( PersistenceException ex ) { - // expected - assertTyping( TransactionRequiredException.class, ex ); - } - finally { - s.close(); - } + long initialInsertCount = statistics.getEntityInsertCount(); + scope.inSession( + session -> { + try { + MyEntity myEntity2 = new MyEntity( "test-persist-2" ); + MySibling sibling = new MySibling( "test-persist-sibling-in" ); + sibling.setEntity( myEntity2 ); + session.persist( sibling ); + assertThat( statistics.getEntityInsertCount() ) + .describedAs( "persist on identity column not delayed" ) + .isEqualTo( initialInsertCount ); + assertThat( myEntity2.getId() ).isNull(); + session.flush(); + fail( "TransactionRequiredException expected upon flush." ); + } + catch (TransactionRequiredException ex) { + // expected + } + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/generatedkeys/identity/MyEntity.java b/hibernate-core/src/test/java/org/hibernate/orm/test/generatedkeys/identity/MyEntity.java index e19d39f8a4d1..bea4dc26792a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/generatedkeys/identity/MyEntity.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/generatedkeys/identity/MyEntity.java @@ -13,8 +13,8 @@ public class MyEntity { private Long id; private String name; private MySibling sibling; - private Set nonInverseChildren = new HashSet(); - private Set inverseChildren = new HashSet(); + private Set nonInverseChildren = new HashSet<>(); + private Set inverseChildren = new HashSet<>(); public MyEntity() { } @@ -47,19 +47,19 @@ public void setSibling(MySibling sibling) { this.sibling = sibling; } - public Set getNonInverseChildren() { + public Set getNonInverseChildren() { return nonInverseChildren; } - public void setNonInverseChildren(Set nonInverseChildren) { + public void setNonInverseChildren(Set nonInverseChildren) { this.nonInverseChildren = nonInverseChildren; } - public Set getInverseChildren() { + public Set getInverseChildren() { return inverseChildren; } - public void setInverseChildren(Set inverseChildren) { + public void setInverseChildren(Set inverseChildren) { this.inverseChildren = inverseChildren; } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/graph/AbstractEntityGraphTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/graph/AbstractEntityGraphTest.java index 15657c04266f..f25b1fe047e9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/graph/AbstractEntityGraphTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/graph/AbstractEntityGraphTest.java @@ -4,69 +4,69 @@ */ package org.hibernate.orm.test.graph; -import java.util.Collection; -import java.util.List; -import java.util.Map; import jakarta.persistence.AttributeNode; import jakarta.persistence.EntityGraph; -import jakarta.persistence.EntityManager; import jakarta.persistence.Subgraph; - import org.hibernate.graph.GraphParser; import org.hibernate.graph.spi.RootGraphImplementor; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; -import org.junit.Assert; +import java.util.Collection; +import java.util.List; +import java.util.Map; -public abstract class AbstractEntityGraphTest extends BaseEntityManagerFunctionalTestCase { +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.fail; - public AbstractEntityGraphTest() { - super(); - } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ GraphParsingTestEntity.class, GraphParsingTestSubentity.class }; - } +@Jpa( + annotatedClasses = { + GraphParsingTestEntity.class, + GraphParsingTestSubentity.class + } +) +public abstract class AbstractEntityGraphTest { - protected RootGraphImplementor parseGraph(Class entityType, String graphString) { - EntityManager entityManager = getOrCreateEntityManager(); - return (RootGraphImplementor) GraphParser.parse( entityType, graphString, entityManager ); + protected RootGraphImplementor parseGraph(Class entityType, String graphString, EntityManagerFactoryScope scope) { + return scope.fromEntityManager( entityManager -> + (RootGraphImplementor) GraphParser.parse( entityType, graphString, entityManager ) + ); } - protected RootGraphImplementor parseGraph(String graphString) { - return parseGraph( GraphParsingTestEntity.class, graphString ); + protected RootGraphImplementor parseGraph(String graphString, EntityManagerFactoryScope scope) { + return parseGraph( GraphParsingTestEntity.class, graphString, scope ); } private > void assertNullOrEmpty(C collection) { if ( collection != null ) { - Assert.assertEquals( 0, collection.size() ); + assertThat( collection).hasSize( 0 ); } } protected > void assertNullOrEmpty(M map) { if ( map != null ) { - Assert.assertEquals( 0, map.size() ); + assertThat( map.size()).isEqualTo( 0 ); } } protected void assertBasicAttributes(EntityGraph graph, String... names) { - Assert.assertNotNull( graph ); + assertThat( graph ).isNotNull(); assertBasicAttributes( graph.getAttributeNodes(), names ); } protected void assertBasicAttributes(Subgraph graph, String... names) { - Assert.assertNotNull( graph ); + assertThat( graph ).isNotNull(); assertBasicAttributes( graph.getAttributeNodes(), names ); } private void assertBasicAttributes(List> attrs, String... names) { - if ( ( names == null ) || ( names.length == 0 ) ) { + if ( (names == null) || (names.length == 0) ) { assertNullOrEmpty( attrs ); } else { - Assert.assertNotNull( attrs ); - Assert.assertTrue( names.length <= attrs.size() ); + assertThat( attrs ).isNotNull(); + assertThat( names.length).isLessThanOrEqualTo( attrs.size() ); for ( String name : names ) { AttributeNode node = null; @@ -76,7 +76,7 @@ private void assertBasicAttributes(List> attrs, String... names break; } } - Assert.assertNotNull( node ); + assertThat( node ).isNotNull(); assertNullOrEmpty( node.getKeySubgraphs() ); assertNullOrEmpty( node.getSubgraphs() ); } @@ -93,11 +93,13 @@ protected AttributeNode getAttributeNodeByName(Subgraph graph, String name private AttributeNode getAttributeNodeByName(List> attrs, String name, boolean required) { for ( AttributeNode attr : attrs ) { - if ( name.equals( attr.getAttributeName() ) ) + if ( name.equals( attr.getAttributeName() ) ) { return attr; + } + } + if ( required ) { + fail( "Required attribute not found." ); } - if ( required ) - Assert.fail( "Required attribute not found." ); return null; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/graph/EntityGraphsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/graph/EntityGraphsTest.java index c0296786bab0..f4d919fae75c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/graph/EntityGraphsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/graph/EntityGraphsTest.java @@ -5,196 +5,209 @@ package org.hibernate.orm.test.graph; import jakarta.persistence.EntityGraph; -import jakarta.persistence.EntityManager; - +import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.graph.EntityGraphs; import org.hibernate.graph.spi.RootGraphImplementor; - import org.hibernate.metamodel.model.domain.EntityDomainType; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; public class EntityGraphsTest extends AbstractEntityGraphTest { - private void checkMerge(Class rootType, EntityGraph expected, EntityGraph... graphs) { - EntityManager entityManager = getOrCreateEntityManager(); - EntityGraph actual = EntityGraphs.merge( entityManager, rootType, graphs ); - Assert.assertTrue( EntityGraphs.areEqual( expected, actual ) ); + private void checkMerge(EntityManagerFactoryScope scope, Class rootType, EntityGraph expected, EntityGraph... graphs) { + scope.inEntityManager( + entityManager -> { + EntityGraph actual = EntityGraphs.merge( entityManager, rootType, graphs ); + assertThat( EntityGraphs.areEqual( expected, actual ) ).isTrue(); + } + ); } @SafeVarargs - private void checkMerge(EntityGraph expected, EntityGraph... graphs) { - checkMerge( GraphParsingTestEntity.class, expected, graphs ); + private void checkMerge(EntityManagerFactoryScope scope, EntityGraph expected, EntityGraph... graphs) { + checkMerge( scope, GraphParsingTestEntity.class, expected, graphs ); } @Test - public void testSameBasicsEqual() { - EntityGraph g = parseGraph( "name, description " ); - Assert.assertTrue( EntityGraphs.areEqual( g, g ) ); + public void testSameBasicsEqual(EntityManagerFactoryScope scope) { + EntityGraph g = parseGraph( "name, description ", scope ); + assertThat( EntityGraphs.areEqual( g, g ) ).isTrue(); } @Test - public void testEqualBasicsEqual() { - EntityGraph a = parseGraph( "name, description " ); - EntityGraph b = parseGraph( "description, name " ); - Assert.assertTrue( EntityGraphs.areEqual( a, b ) ); + public void testEqualBasicsEqual(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( "name, description ", scope ); + EntityGraph b = parseGraph( "description, name ", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isTrue(); } @Test - public void testDifferentBasicsEqual1() { - EntityGraph a = parseGraph( "name, description " ); - EntityGraph b = parseGraph( "description " ); - Assert.assertFalse( EntityGraphs.areEqual( a, b ) ); + public void testDifferentBasicsEqual1(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( "name, description ", scope ); + EntityGraph b = parseGraph( "description ", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isFalse(); } @Test - public void testDifferentBasicsEqual2() { - EntityGraph a = parseGraph( "name " ); - EntityGraph b = parseGraph( "description " ); - Assert.assertFalse( EntityGraphs.areEqual( a, b ) ); + public void testDifferentBasicsEqual2(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( "name ", scope ); + EntityGraph b = parseGraph( "description ", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isFalse(); } @Test - public void testEqualLinksEqual1() { - EntityGraph a = parseGraph( "linkToOne(name, description)" ); - EntityGraph b = parseGraph( "linkToOne(description, name)" ); - Assert.assertTrue( EntityGraphs.areEqual( a, b ) ); + public void testEqualLinksEqual1(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( "linkToOne(name, description)", scope ); + EntityGraph b = parseGraph( "linkToOne(description, name)", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isTrue(); } @Test - public void testEqualLinksWithSubclassesEqual() { - EntityGraph a = parseGraph( "linkToOne(name), linkToOne(GraphParsingTestSubentity:description)" ); - EntityGraph b = parseGraph( "linkToOne(GraphParsingTestSubentity:description), linkToOne(name)" ); - Assert.assertTrue( EntityGraphs.areEqual( a, b ) ); + public void testEqualLinksWithSubclassesEqual(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( + "linkToOne(name), linkToOne(GraphParsingTestSubentity:description)", scope ); + EntityGraph b = parseGraph( + "linkToOne(GraphParsingTestSubentity:description), linkToOne(name)", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isTrue(); } @Test - public void testDifferentLinksEqual1() { - EntityGraph a = parseGraph( "linkToOne(name, description)" ); - EntityGraph b = parseGraph( "linkToOne(description)" ); - Assert.assertFalse( EntityGraphs.areEqual( a, b ) ); + public void testDifferentLinksEqual1(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( "linkToOne(name, description)", scope ); + EntityGraph b = parseGraph( "linkToOne(description)", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isFalse(); } @Test - public void testDifferentLinksEqual2() { - EntityGraph a = parseGraph( "linkToOne(name)" ); - EntityGraph b = parseGraph( "linkToOne(description)" ); - Assert.assertFalse( EntityGraphs.areEqual( a, b ) ); + public void testDifferentLinksEqual2(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( "linkToOne(name)", scope ); + EntityGraph b = parseGraph( "linkToOne(description)", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isFalse(); } @Test - public void testDifferentLinksEqual3() { - EntityGraph a = parseGraph( "linkToOne(name), linkToOne(GraphParsingTestSubentity:description)" ); - EntityGraph b = parseGraph( "linkToOne(name, description)" ); - Assert.assertFalse( EntityGraphs.areEqual( a, b ) ); + public void testDifferentLinksEqual3(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( + "linkToOne(name), linkToOne(GraphParsingTestSubentity:description)", scope ); + EntityGraph b = parseGraph( "linkToOne(name, description)", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isFalse(); } @Test - public void testEqualMapKeysEqual() { - EntityGraph a = parseGraph( "map.key(name, description)" ); - EntityGraph b = parseGraph( "map.key(description, name)" ); - Assert.assertTrue( EntityGraphs.areEqual( a, b ) ); + public void testEqualMapKeysEqual(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( "map.key(name, description)", scope ); + EntityGraph b = parseGraph( "map.key(description, name)", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isTrue(); } @Test - public void testDifferentMapKeysEqual1() { - EntityGraph a = parseGraph( "map.key(name, description)" ); - EntityGraph b = parseGraph( "map.key(description)" ); - Assert.assertFalse( EntityGraphs.areEqual( a, b ) ); + public void testDifferentMapKeysEqual1(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( "map.key(name, description)", scope ); + EntityGraph b = parseGraph( "map.key(description)", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isFalse(); } @Test - public void testDifferentMapKeysEqual2() { - EntityGraph a = parseGraph( "map.key(name)" ); - EntityGraph b = parseGraph( "map.key(description)" ); - Assert.assertFalse( EntityGraphs.areEqual( a, b ) ); + public void testDifferentMapKeysEqual2(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( "map.key(name)", scope ); + EntityGraph b = parseGraph( "map.key(description)", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isFalse(); } @Test - public void testEqualMapValuesEqual() { - EntityGraph a = parseGraph( "map.value(name, description)" ); - EntityGraph b = parseGraph( "map.value(description, name)" ); - Assert.assertTrue( EntityGraphs.areEqual( a, b ) ); + public void testEqualMapValuesEqual(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( "map.value(name, description)", scope ); + EntityGraph b = parseGraph( "map.value(description, name)", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isTrue(); } @Test - public void testDifferentMapValuesEqual1() { - EntityGraph a = parseGraph( "map.value(name, description)" ); - EntityGraph b = parseGraph( "map.value(description)" ); - Assert.assertFalse( EntityGraphs.areEqual( a, b ) ); + public void testDifferentMapValuesEqual1(EntityManagerFactoryScope scop) { + EntityGraph a = parseGraph( "map.value(name, description)", scop ); + EntityGraph b = parseGraph( "map.value(description)", scop ); + assertThat( EntityGraphs.areEqual( a, b ) ).isFalse(); } @Test - public void testDifferentMapValuesEqual2() { - EntityGraph a = parseGraph( "map.value(name)" ); - EntityGraph b = parseGraph( "map.value(description)" ); - Assert.assertFalse( EntityGraphs.areEqual( a, b ) ); + public void testDifferentMapValuesEqual2(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( "map.value(name)", scope ); + EntityGraph b = parseGraph( "map.value(description)", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isFalse(); } @Test - public void testEqualComplexGraphsEqual() { - EntityGraph a = parseGraph( "map.key(name, description), name, linkToOne(description), description" ); - EntityGraph b = parseGraph( "description, map.key(description, name), name, linkToOne(description)" ); - Assert.assertTrue( EntityGraphs.areEqual( a, b ) ); + public void testEqualComplexGraphsEqual(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( + "map.key(name, description), name, linkToOne(description), description", scope ); + EntityGraph b = parseGraph( + "description, map.key(description, name), name, linkToOne(description)", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isTrue(); } @Test - public void testDifferentComplexGraphsEqual() { - EntityGraph a = parseGraph( "map.key(name, description), name, linkToOne(description), description" ); - EntityGraph b = parseGraph( "description, map.value(description, name), name, linkToOne(description)" ); - Assert.assertFalse( EntityGraphs.areEqual( a, b ) ); + public void testDifferentComplexGraphsEqual(EntityManagerFactoryScope scope) { + EntityGraph a = parseGraph( + "map.key(name, description), name, linkToOne(description), description", scope ); + EntityGraph b = parseGraph( + "description, map.value(description, name), name, linkToOne(description)", scope ); + assertThat( EntityGraphs.areEqual( a, b ) ).isFalse(); } @Test - public void testNullsEqual() { - Assert.assertTrue( EntityGraphs.areEqual( (EntityGraph) null, (EntityGraph) null ) ); + public void testNullsEqual(EntityManagerFactoryScope scope) { + assertThat( EntityGraphs.areEqual( null, (EntityGraph) null ) ).isTrue(); } @Test - public void testNullAndNonNullEqual() { - EntityGraph graph = parseGraph( "name " ); - Assert.assertFalse( EntityGraphs.areEqual( graph, (EntityGraph) null ) ); - Assert.assertFalse( EntityGraphs.areEqual( (EntityGraph) null, graph ) ); + public void testNullAndNonNullEqual(EntityManagerFactoryScope scope) { + EntityGraph graph = parseGraph( "name ", scope ); + assertThat( EntityGraphs.areEqual( graph, null ) ).isFalse(); + assertThat( EntityGraphs.areEqual( null, graph ) ).isFalse(); } @Test - public void testBasicMerge() { - EntityGraph g1 = parseGraph( "name" ); - EntityGraph g2 = parseGraph( "description" ); - EntityGraph expected = parseGraph( "name, description " ); - checkMerge( expected, g1, g2 ); + public void testBasicMerge(EntityManagerFactoryScope scope) { + EntityGraph g1 = parseGraph( "name", scope ); + EntityGraph g2 = parseGraph( "description", scope ); + EntityGraph expected = parseGraph( "name, description ", scope ); + checkMerge( scope, expected, g1, g2 ); } @Test - public void testLinkMerge() { - EntityGraph g1 = parseGraph( "linkToOne(name)" ); - EntityGraph g2 = parseGraph( "linkToOne(description)" ); - EntityGraph expected = parseGraph( "linkToOne(name, description) " ); - checkMerge( expected, g1, g2 ); + public void testLinkMerge(EntityManagerFactoryScope scope) { + EntityGraph g1 = parseGraph( "linkToOne(name)", scope ); + EntityGraph g2 = parseGraph( "linkToOne(description)", scope ); + EntityGraph expected = parseGraph( "linkToOne(name, description) ", scope ); + checkMerge( scope, expected, g1, g2 ); } @Test - public void testMapKeyMerge() { - EntityGraph g1 = parseGraph( "map.key(name)" ); - EntityGraph g2 = parseGraph( "map.key(description)" ); - EntityGraph expected = parseGraph( "map.key(name, description) " ); - checkMerge( expected, g1, g2 ); + public void testMapKeyMerge(EntityManagerFactoryScope scope) { + EntityGraph g1 = parseGraph( "map.key(name)", scope ); + EntityGraph g2 = parseGraph( "map.key(description)", scope ); + EntityGraph expected = parseGraph( "map.key(name, description) ", scope ); + checkMerge( scope, expected, g1, g2 ); } @Test - public void testMapValueMerge() { - EntityGraph g1 = parseGraph( "map.value(name)" ); - EntityGraph g2 = parseGraph( "map.value(description)" ); - EntityGraph expected = parseGraph( "map.value(name, description) " ); - checkMerge( expected, g1, g2 ); + public void testMapValueMerge(EntityManagerFactoryScope scope) { + EntityGraph g1 = parseGraph( "map.value(name)", scope ); + EntityGraph g2 = parseGraph( "map.value(description)", scope ); + EntityGraph expected = parseGraph( "map.value(name, description) ", scope ); + checkMerge( scope, expected, g1, g2 ); } @Test - @JiraKey( value = "HHH-14264" ) - public void testRootGraphAppliesToChildEntityClass() { - RootGraphImplementor rootGraphImplementor = parseGraph( GraphParsingTestEntity.class, "name, description" ); - EntityDomainType entity = entityManagerFactory().getJpaMetamodel().entity( (Class) GraphParsingTestSubentity.class ); - Assert.assertTrue( rootGraphImplementor.appliesTo( entity ) ); + @JiraKey(value = "HHH-14264") + public void testRootGraphAppliesToChildEntityClass(EntityManagerFactoryScope scope) { + RootGraphImplementor rootGraphImplementor = parseGraph( GraphParsingTestEntity.class, + "name, description", scope ); + EntityDomainType entity = scope.getEntityManagerFactory().unwrap( SessionFactoryImplementor.class ) + .getJpaMetamodel() + .entity( (Class) GraphParsingTestSubentity.class ); + assertThat( rootGraphImplementor.appliesTo( entity ) ).isTrue(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/collectionpk/CollectionPkTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/collectionpk/CollectionPkTest.java index 96e7a6875700..017fc416f159 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/collectionpk/CollectionPkTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/collectionpk/CollectionPkTest.java @@ -4,38 +4,38 @@ */ package org.hibernate.orm.test.hbm.collectionpk; -import java.util.Arrays; - import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.tool.schema.internal.SchemaCreatorImpl; - +import org.hibernate.orm.test.hbm.index.JournalingSchemaToolingTarget; +import org.hibernate.testing.orm.junit.BaseUnitTest; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.util.ServiceRegistryUtil; +import org.hibernate.tool.schema.internal.SchemaCreatorImpl; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.hibernate.orm.test.hbm.index.JournalingSchemaToolingTarget; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import java.util.Arrays; + +import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertTrue; /** * @author Steve Ebersole */ -@JiraKey( value = "HHH-10206" ) -public class CollectionPkTest extends BaseUnitTestCase { +@JiraKey(value = "HHH-10206") +@BaseUnitTest +public class CollectionPkTest { private StandardServiceRegistry ssr; - @Before + @BeforeEach public void before() { ssr = ServiceRegistryUtil.serviceRegistry(); } - @After + @AfterEach public void after() { if ( ssr != null ) { StandardServiceRegistryBuilder.destroy( ssr ); @@ -59,10 +59,10 @@ private void verifyPkNameUsed(String mappingResource, String... expectedName) { final JournalingSchemaToolingTarget target = new JournalingSchemaToolingTarget(); new SchemaCreatorImpl( ssr ).doCreation( metadata, false, target ); - assertTrue( - "Expected foreign-key name [" + Arrays.toString(expectedName) + "] not seen in schema creation output", - Arrays.stream( expectedName ).anyMatch( target::containedText ) - ); + assertThat( Arrays.stream( expectedName ).anyMatch( target::containedText ) ) + .describedAs( "Expected foreign-key name [" + Arrays.toString( + expectedName ) + "] not seen in schema creation output" ) + .isTrue(); } @Test diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/comment/ClassCommentTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/comment/ClassCommentTest.java index c186d72c5453..887374f2b67d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/comment/ClassCommentTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/comment/ClassCommentTest.java @@ -4,8 +4,6 @@ */ package org.hibernate.orm.test.hbm.comment; -import java.io.StringReader; - import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; @@ -13,26 +11,29 @@ import org.hibernate.internal.util.ReaderInputStream; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Table; - -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.junit4.BaseUnitTestCase; +import org.hibernate.testing.orm.junit.BaseUnitTest; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import java.io.StringReader; + +import static org.assertj.core.api.Assertions.assertThat; -@RequiresDialect( H2Dialect.class ) -public class ClassCommentTest extends BaseUnitTestCase { +@RequiresDialect(H2Dialect.class) +@BaseUnitTest +public class ClassCommentTest { - private static String CLASS_COMMENT_HBM_XML = - " "+ - " "+ - " This is class 'Foo' with property 'bar'. "+ - " "+ - " "+ - " "+ - " "+ - " "+ - " "; + private static final String CLASS_COMMENT_HBM_XML = + " " + + " " + + " This is class 'Foo' with property 'bar'. " + + " " + + " " + + " " + + " " + + " " + + " "; @Test public void testClassComment() { @@ -41,10 +42,10 @@ public void testClassComment() { metadataSources.addInputStream( new ReaderInputStream( new StringReader( CLASS_COMMENT_HBM_XML ) ) ); Metadata metadata = metadataSources.buildMetadata(); PersistentClass pc = metadata.getEntityBinding( "org.hibernate.test.hbm.Foo" ); - Assert.assertNotNull( pc ); + assertThat( pc ).isNotNull(); Table table = pc.getTable(); - Assert.assertNotNull( table ); - Assert.assertEquals( "This is class 'Foo' with property 'bar'.", table.getComment() ); + assertThat( table ).isNotNull(); + assertThat( table.getComment() ).isEqualTo( "This is class 'Foo' with property 'bar'." ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/fk/CollectionKeyFkNameTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/fk/CollectionKeyFkNameTest.java index 6e044a4f3910..35049f8abb5b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/fk/CollectionKeyFkNameTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/fk/CollectionKeyFkNameTest.java @@ -9,31 +9,30 @@ import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.engine.config.spi.ConfigurationService; -import org.hibernate.tool.schema.internal.SchemaCreatorImpl; - +import org.hibernate.orm.test.hbm.index.JournalingSchemaToolingTarget; +import org.hibernate.testing.orm.junit.BaseUnitTest; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.util.ServiceRegistryUtil; +import org.hibernate.tool.schema.internal.SchemaCreatorImpl; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.hibernate.orm.test.hbm.index.JournalingSchemaToolingTarget; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Steve Ebersole */ -public class CollectionKeyFkNameTest extends BaseUnitTestCase { +@BaseUnitTest +public class CollectionKeyFkNameTest { private StandardServiceRegistry ssr; - @Before + @BeforeEach public void before() { ssr = ServiceRegistryUtil.serviceRegistry(); } - @After + @AfterEach public void after() { if ( ssr != null ) { StandardServiceRegistryBuilder.destroy( ssr ); @@ -41,7 +40,7 @@ public void after() { } @Test - @JiraKey( value = "HHH-10207" ) + @JiraKey(value = "HHH-10207") public void testExplicitFkNameOnCollectionKey() { verifyFkNameUsed( "org/hibernate/orm/test/hbm/fk/person_set.hbm.xml", @@ -63,14 +62,13 @@ private void verifyFkNameUsed(String mappingResource, String expectedName) { target ); - assertTrue( - "Expected foreign-key name [" + expectedName + "] not seen in schema creation output", - target.containedText( expectedName ) - ); + assertThat( target.containedText( expectedName ) ) + .describedAs( "Expected foreign-key name [" + expectedName + "] not seen in schema creation output" ) + .isTrue(); } @Test - @JiraKey( value = "HHH-10207" ) + @JiraKey(value = "HHH-10207") public void testExplicitFkNameOnManyToOne() { verifyFkNameUsed( "org/hibernate/orm/test/hbm/fk/person_set.hbm.xml", diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/index/IndexTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/index/IndexTest.java index 588cd1a59e56..56ab7e8e72bd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/index/IndexTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/index/IndexTest.java @@ -8,30 +8,30 @@ import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.tool.schema.internal.SchemaCreatorImpl; - +import org.hibernate.testing.orm.junit.BaseUnitTest; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.tool.schema.internal.SchemaCreatorImpl; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Steve Ebersole */ -@JiraKey( value = "HHH-10208" ) -public class IndexTest extends BaseUnitTestCase { +@JiraKey(value = "HHH-10208") +@BaseUnitTest +public class IndexTest { private StandardServiceRegistry ssr; - @Before + @BeforeEach public void before() { ssr = ServiceRegistryUtil.serviceRegistry(); } - @After + @AfterEach public void after() { if ( ssr != null ) { StandardServiceRegistryBuilder.destroy( ssr ); @@ -55,10 +55,9 @@ private void verifyIndexCreated(String mappingResource, String expectedIndexName final JournalingSchemaToolingTarget target = new JournalingSchemaToolingTarget(); new SchemaCreatorImpl( ssr ).doCreation( metadata, false, target ); - assertTrue( - "Expected index [" + expectedIndexName + "] not seen in schema creation output", - target.containedText( expectedIndexName ) - ); + assertThat( target.containedText( expectedIndexName ) ) + .describedAs( "Expected index [" + expectedIndexName + "] not seen in schema creation output" ) + .isTrue(); } @Test diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/query/NamedQueryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/query/NamedQueryTest.java index ff83a48ba768..229d41bd15b0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/query/NamedQueryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/query/NamedQueryTest.java @@ -11,20 +11,21 @@ import org.hibernate.dialect.H2Dialect; import org.hibernate.internal.util.ReaderInputStream; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.BaseUnitTest; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author Koen Aers */ @JiraKey( value = "HHH-10223" ) @RequiresDialect( H2Dialect.class ) -public class NamedQueryTest extends BaseUnitTestCase { +@BaseUnitTest +public class NamedQueryTest { - private static String NAMED_QUERY_HBM_XML = + private static final String NAMED_QUERY_HBM_XML = " "+ " "+ " "+ diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/query/QueryReturnTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/query/QueryReturnTest.java index 477841343d6a..d10af14ab6e0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/query/QueryReturnTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/query/QueryReturnTest.java @@ -4,49 +4,50 @@ */ package org.hibernate.orm.test.hbm.query; -import java.io.StringReader; - import org.hibernate.cfg.Configuration; import org.hibernate.dialect.H2Dialect; -import org.hibernate.internal.util.ReaderInputStream; import org.hibernate.engine.spi.SessionFactoryImplementor; +import org.hibernate.internal.util.ReaderInputStream; import org.hibernate.query.internal.ResultSetMappingResolutionContext; import org.hibernate.query.named.NamedResultSetMappingMemento; import org.hibernate.query.results.ResultSetMapping; import org.hibernate.query.results.internal.ResultSetMappingImpl; import org.hibernate.query.results.internal.complete.CompleteResultBuilderEntityValued; - -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.BaseUnitTest; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import java.io.StringReader; + +import static org.assertj.core.api.Assertions.assertThat; /** * @author Koen Aers */ -@JiraKey( value = "HHH-10405" ) -@RequiresDialect( H2Dialect.class ) -public class QueryReturnTest extends BaseUnitTestCase { - - private static String QUERY_RETURN_HBM_XML = - " "+ - " "+ - " "+ - " "+ - " "+ - " "+ - " "+ - " "+ - " "+ - " "+ - " 50]]> "+ - " "+ +@JiraKey(value = "HHH-10405") +@RequiresDialect(H2Dialect.class) +@BaseUnitTest +public class QueryReturnTest { + + private static final String QUERY_RETURN_HBM_XML = + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " 50]]> " + + " " + " "; @Test @@ -60,7 +61,7 @@ public void testQueryReturn() { NamedResultSetMappingMemento mappingMemento = sessionFactory.getQueryEngine() .getNamedObjectRepository() .getResultSetMappingMemento( "myQuery" ); - Assert.assertNotNull( mappingMemento ); + assertThat( mappingMemento ).isNotNull(); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // NYI @@ -73,17 +74,16 @@ public SessionFactoryImplementor getSessionFactory() { } }; - mappingMemento.resolve( mapping, querySpace -> {}, resolutionContext ); - Assert.assertEquals( 1, mapping.getNumberOfResultBuilders() ); + mappingMemento.resolve( mapping, querySpace -> { + }, resolutionContext ); + assertThat( mapping.getNumberOfResultBuilders() ).isEqualTo( 1 ); mapping.visitResultBuilders( (i, resultBuilder) -> { - Assert.assertTrue( resultBuilder instanceof CompleteResultBuilderEntityValued ); + assertThat( resultBuilder ).isInstanceOf( CompleteResultBuilderEntityValued.class ); CompleteResultBuilderEntityValued myQueryRootReturn = (CompleteResultBuilderEntityValued) resultBuilder; // Assert.assertEquals( "e", myQueryRootReturn.getTableAlias() ); - Assert.assertEquals( - "org.hibernate.orm.test.hbm.query.QueryReturnTest$Bar", - myQueryRootReturn.getReferencedPart().getEntityName() - ); + assertThat( myQueryRootReturn.getReferencedPart().getEntityName() ) + .isEqualTo( "org.hibernate.orm.test.hbm.query.QueryReturnTest$Bar" ); } ); } @@ -95,10 +95,22 @@ public SessionFactoryImplementor getSessionFactory() { public static class Bar { public Integer id; public String foo; - public Integer getId() { return id; } - public void setId(Integer id) { this.id = id; } - public String getFoo() { return foo; } - public void setFoo(String foo) { this.foo = foo; } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getFoo() { + return foo; + } + + public void setFoo(String foo) { + this.foo = foo; + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/version/GeneratedVersionBindingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/version/GeneratedVersionBindingTest.java index 81c7877ef776..7abb004fc58e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/version/GeneratedVersionBindingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/version/GeneratedVersionBindingTest.java @@ -8,26 +8,27 @@ import org.hibernate.boot.registry.BootstrapServiceRegistry; import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; import org.hibernate.service.ServiceRegistry; - -import org.hibernate.testing.junit4.BaseUnitTestCase; +import org.hibernate.testing.orm.junit.BaseUnitTest; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author Steve Ebersole */ -public class GeneratedVersionBindingTest extends BaseUnitTestCase { +@BaseUnitTest +public class GeneratedVersionBindingTest { + @Test public void testIt() { MetadataSources metadataSources = new MetadataSources( ServiceRegistryUtil.serviceRegistry() ) - .addResource( "org/hibernate/orm/test/hbm/version/Mappings.hbm.xml" ); + .addResource( "org/hibernate/orm/test/hbm/version/Mappings.hbm.xml" ); try { metadataSources.buildMetadata(); } finally { ServiceRegistry metaServiceRegistry = metadataSources.getServiceRegistry(); - if(metaServiceRegistry instanceof BootstrapServiceRegistry ) { + if ( metaServiceRegistry instanceof BootstrapServiceRegistry ) { BootstrapServiceRegistryBuilder.destroy( metaServiceRegistry ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/JpaComplianceTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/JpaComplianceTests.java index aa6abf3f205f..cdeef2dc4bd4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/JpaComplianceTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/JpaComplianceTests.java @@ -86,11 +86,14 @@ public void testSettingTrue() { .applySetting( AvailableSettings.JPA_COMPLIANCE, true ) .build(), (serviceRegistryScope) -> { - final SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) new MetadataSources( serviceRegistryScope.getRegistry() ) + try (final SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) new MetadataSources( + serviceRegistryScope.getRegistry() ) .buildMetadata() - .buildSessionFactory(); - final JpaCompliance jpaCompliance = sessionFactory.getSessionFactoryOptions().getJpaCompliance(); - assertAll( jpaCompliance, true ); + .buildSessionFactory()) { + final JpaCompliance jpaCompliance = sessionFactory.getSessionFactoryOptions() + .getJpaCompliance(); + assertAll( jpaCompliance, true ); + } } ); // MutableJpaComplianceImpl defaults its values based on the passed @@ -107,11 +110,14 @@ public void testSettingFalse() { .applySetting( AvailableSettings.JPA_COMPLIANCE, false ) .build(), (serviceRegistryScope) -> { - final SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) new MetadataSources( serviceRegistryScope.getRegistry() ) + try (final SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) new MetadataSources( + serviceRegistryScope.getRegistry() ) .buildMetadata() - .buildSessionFactory(); - final JpaCompliance jpaCompliance = sessionFactory.getSessionFactoryOptions().getJpaCompliance(); - assertAll( jpaCompliance, false ); + .buildSessionFactory()) { + final JpaCompliance jpaCompliance = sessionFactory.getSessionFactoryOptions() + .getJpaCompliance(); + assertAll( jpaCompliance, false ); + } } ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ordering/OrderByComplianceTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ordering/OrderByComplianceTests.java index c8ea235bc3e3..b7bd942dcf4f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ordering/OrderByComplianceTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ordering/OrderByComplianceTests.java @@ -25,16 +25,16 @@ public class OrderByComplianceTests { @ServiceRegistry( settings = @Setting( name= AvailableSettings.JPA_ORDER_BY_MAPPING_COMPLIANCE, value = "false" ) ) @DomainModel( annotatedClasses = { TypesOfThings.class, Contact.class, AddressBook.class } ) public void testNonCompliantBaseline(DomainModelScope scope) { - final SessionFactory sessionFactory = scope.getDomainModel().buildSessionFactory(); - assertThat( sessionFactory ).isNotNull(); + try(final SessionFactory sessionFactory = scope.getDomainModel().buildSessionFactory()) { + assertThat( sessionFactory ).isNotNull(); + } } @Test @ServiceRegistry( settings = @Setting( name= AvailableSettings.JPA_ORDER_BY_MAPPING_COMPLIANCE, value = "true" ) ) @DomainModel( annotatedClasses = { TypesOfThings.class, Contact.class, AddressBook.class } ) public void testNonCompliantStrictly(DomainModelScope scope) { - try { - final SessionFactory sessionFactory = scope.getDomainModel().buildSessionFactory(); + try (final SessionFactory sessionFactory = scope.getDomainModel().buildSessionFactory()) { assertThat( sessionFactory ).isNotNull(); fail( "Expecting a failure here" ); } @@ -50,16 +50,18 @@ public void testNonCompliantStrictly(DomainModelScope scope) { @ServiceRegistry( settings = @Setting( name= AvailableSettings.JPA_ORDER_BY_MAPPING_COMPLIANCE, value = "false" ) ) @DomainModel( annotatedClasses = { TypesOfThings.class, Contact.class, CompliantAddressBook.class } ) public void testCompliantBaseline(DomainModelScope scope) { - final SessionFactory sessionFactory = scope.getDomainModel().buildSessionFactory(); - assertThat( sessionFactory ).isNotNull(); + try (final SessionFactory sessionFactory = scope.getDomainModel().buildSessionFactory()) { + assertThat( sessionFactory ).isNotNull(); + } } @Test @ServiceRegistry( settings = @Setting( name= AvailableSettings.JPA_ORDER_BY_MAPPING_COMPLIANCE, value = "true" ) ) @DomainModel( annotatedClasses = { TypesOfThings.class, Contact.class, CompliantAddressBook.class } ) public void testCompliantStrictly(DomainModelScope scope) { - final SessionFactory sessionFactory = scope.getDomainModel().buildSessionFactory(); - assertThat( sessionFactory ).isNotNull(); + try (final SessionFactory sessionFactory = scope.getDomainModel().buildSessionFactory()) { + assertThat( sessionFactory ).isNotNull(); + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/usertypes/UserTypeMappingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/usertypes/UserTypeMappingTest.java index ac6ccbdfde6a..6005971f7e32 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/usertypes/UserTypeMappingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/usertypes/UserTypeMappingTest.java @@ -48,9 +48,9 @@ public void tearDown() { public void testFirstTypeThenEntity() { cfg.addResource( "org/hibernate/orm/test/mapping/usertypes/TestEnumType.hbm.xml" ) .addResource( "org/hibernate/orm/test/mapping/usertypes/TestEntity.hbm.xml" ); - SessionFactory sessions = cfg.buildSessionFactory( serviceRegistry ); - assertNotNull( sessions ); - sessions.close(); + try (SessionFactory sessions = cfg.buildSessionFactory( serviceRegistry )) { + assertNotNull( sessions ); + } } @Test @@ -58,9 +58,9 @@ public void testFirstEntityThenType() { cfg.addResource( "org/hibernate/orm/test/mapping/usertypes/TestEntity.hbm.xml" ) .addResource( "org/hibernate/orm/test/mapping/usertypes/TestEnumType.hbm.xml" ); - SessionFactory sessions = cfg.buildSessionFactory( serviceRegistry ); - assertNotNull( sessions ); - sessions.close(); + try (SessionFactory sessions = cfg.buildSessionFactory( serviceRegistry )) { + assertNotNull( sessions ); + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/merge/BidirectionalOneToManyMergeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/merge/BidirectionalOneToManyMergeTest.java index 97bb31d15c2d..c3312afc1d21 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/merge/BidirectionalOneToManyMergeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/merge/BidirectionalOneToManyMergeTest.java @@ -4,10 +4,6 @@ */ package org.hibernate.orm.test.merge; -import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Before; -import org.junit.Test; - import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; @@ -17,42 +13,45 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + import java.util.ArrayList; import java.util.List; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; - /** * @author Lisandro Fernandez (kelechul at gmail dot com) */ @JiraKey("HHH-13815") -public class BidirectionalOneToManyMergeTest extends org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - Post.class, - PostComment.class, - }; - } +@Jpa( + annotatedClasses = { + BidirectionalOneToManyMergeTest.Post.class, + BidirectionalOneToManyMergeTest.PostComment.class, + } +) +public class BidirectionalOneToManyMergeTest { + - @Before - public void setUp() { - doInJPA(this::entityManagerFactory, entityManager -> { + @BeforeAll + public void setUp(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { entityManager.persist( - new Post("High-Performance Java Persistence").setId(1L) + new Post( "High-Performance Java Persistence" ).setId( 1L ) ); - }); + } ); } @Test - public void testMerge() { - doInJPA(this::entityManagerFactory, entityManager -> { - Post post = entityManager.find(Post.class, 1L); - post.addComment(new PostComment("This post rocks!", post)); + public void testMerge(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Post post = entityManager.find( Post.class, 1L ); + post.addComment( new PostComment( "This post rocks!", post ) ); post.getComments().isEmpty(); - entityManager.merge(post); - }); + entityManager.merge( post ); + } ); } @Entity @@ -101,15 +100,15 @@ private Post setComments(List comments) { } public Post addComment(PostComment comment) { - comments.add(comment); - comment.setPost(this); + comments.add( comment ); + comment.setPost( this ); return this; } public Post removeComment(PostComment comment) { - comments.remove(comment); - comment.setPost(null); + comments.remove( comment ); + comment.setPost( null ); return this; } @@ -165,9 +164,13 @@ public PostComment setPost(Post post) { @Override public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof PostComment)) return false; - return id != null && id.equals(((PostComment) o).getId()); + if ( this == o ) { + return true; + } + if ( !(o instanceof PostComment) ) { + return false; + } + return id != null && id.equals( ((PostComment) o).getId() ); } @Override diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/AbstractMultiTenancyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/AbstractMultiTenancyTest.java index 1734e80f4660..8068ee335efd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/AbstractMultiTenancyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/AbstractMultiTenancyTest.java @@ -4,16 +4,8 @@ */ package org.hibernate.orm.test.multitenancy; -import java.io.FileInputStream; -import java.io.IOException; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; -import java.util.function.Consumer; import jakarta.persistence.Entity; import jakarta.persistence.Id; - import org.hibernate.Session; import org.hibernate.SessionException; import org.hibernate.SessionFactory; @@ -26,31 +18,37 @@ import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProvider; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.hibernate.internal.util.PropertiesHelper; +import org.hibernate.orm.test.util.DdlTransactionIsolatorTestingImpl; import org.hibernate.query.Query; import org.hibernate.service.spi.ServiceRegistryImplementor; import org.hibernate.service.spi.Stoppable; +import org.hibernate.testing.orm.junit.BaseUnitTest; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.util.ServiceRegistryUtil; import org.hibernate.tool.schema.internal.HibernateSchemaManagementTool; import org.hibernate.tool.schema.internal.SchemaCreatorImpl; import org.hibernate.tool.schema.internal.SchemaDropperImpl; import org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.AfterClassOnce; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.util.ServiceRegistryUtil; - -import org.hibernate.orm.test.util.DdlTransactionIsolatorTestingImpl; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import java.util.function.Consumer; import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * @author Vlad Mihalcea */ -public abstract class AbstractMultiTenancyTest extends BaseUnitTestCase { +@BaseUnitTest +public abstract class AbstractMultiTenancyTest { protected static final String FRONT_END_TENANT = "front_end"; protected static final String BACK_END_TENANT = "back_end"; @@ -65,47 +63,47 @@ public AbstractMultiTenancyTest() { //tag::multitenacy-hibernate-MultiTenantConnectionProvider-example[] private void init() { - registerConnectionProvider(FRONT_END_TENANT); - registerConnectionProvider(BACK_END_TENANT); - sessionFactory = sessionFactory(createSettings()); + registerConnectionProvider( FRONT_END_TENANT ); + registerConnectionProvider( BACK_END_TENANT ); + sessionFactory = sessionFactory( createSettings() ); } protected Map createSettings() { Map settings = new HashMap<>(); - settings.put(AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, - new ConfigurableMultiTenantConnectionProvider(connectionProviderMap)); + settings.put( AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, + new ConfigurableMultiTenantConnectionProvider( connectionProviderMap ) ); return settings; } //end::multitenacy-hibernate-MultiTenantConnectionProvider-example[] - @AfterClassOnce + @AfterAll public void destroy() { sessionFactory.close(); - for (ConnectionProvider connectionProvider : connectionProviderMap.values()) { - if (connectionProvider instanceof Stoppable) { + for ( ConnectionProvider connectionProvider : connectionProviderMap.values() ) { + if ( connectionProvider instanceof Stoppable ) { ((Stoppable) connectionProvider).stop(); } } } - @After + @AfterEach public void cleanup() { - doInSession(FRONT_END_TENANT, session -> session.createMutationQuery( "delete from Person" ).executeUpdate() ); - doInSession(BACK_END_TENANT, session -> session.createMutationQuery( "delete from Person" ).executeUpdate() ); + doInSession( FRONT_END_TENANT, session -> session.createMutationQuery( "delete from Person" ).executeUpdate() ); + doInSession( BACK_END_TENANT, session -> session.createMutationQuery( "delete from Person" ).executeUpdate() ); } //tag::multitenacy-hibernate-MultiTenantConnectionProvider-example[] protected void registerConnectionProvider(String tenantIdentifier) { Properties properties = properties(); - properties.put(Environment.URL, - tenantUrl(properties.getProperty(Environment.URL), tenantIdentifier)); + properties.put( Environment.URL, + tenantUrl( properties.getProperty( Environment.URL ), tenantIdentifier ) ); DriverManagerConnectionProvider connectionProvider = - new DriverManagerConnectionProvider(); - connectionProvider.configure( PropertiesHelper.map(properties) ); - connectionProviderMap.put(tenantIdentifier, connectionProvider); + new DriverManagerConnectionProvider(); + connectionProvider.configure( PropertiesHelper.map( properties ) ); + connectionProviderMap.put( tenantIdentifier, connectionProvider ); } //end::multitenacy-hibernate-MultiTenantConnectionProvider-example[] @@ -113,24 +111,24 @@ protected void registerConnectionProvider(String tenantIdentifier) { public void testBasicExpectedBehavior() { //tag::multitenacy-multitenacy-hibernate-same-entity-example[] - doInSession(FRONT_END_TENANT, session -> { + doInSession( FRONT_END_TENANT, session -> { Person person = new Person(); - person.setId(1L); - person.setName("John Doe"); - session.persist(person); - }); + person.setId( 1L ); + person.setName( "John Doe" ); + session.persist( person ); + } ); - doInSession(BACK_END_TENANT, session -> { + doInSession( BACK_END_TENANT, session -> { Person person = new Person(); - person.setId(1L); - person.setName("John Doe"); - session.persist(person); - }); + person.setId( 1L ); + person.setName( "John Doe" ); + session.persist( person ); + } ); //end::multitenacy-multitenacy-hibernate-same-entity-example[] } @Test - @JiraKey( value = "HHH-17972") + @JiraKey(value = "HHH-17972") public void testChangeTenantWithoutConnectionReuse() { Person person = new Person(); person.setId( 1L ); @@ -162,38 +160,41 @@ public void testChangeTenantWithoutConnectionReuse() { assertEquals( "Jane Doe", newSessionQuery.getResultList().get( 0 ).getName() ); } finally { - if (session != null) { + if ( session != null ) { session.close(); } - if (newSession != null) { + if ( newSession != null ) { newSession.close(); } } } @Test - @JiraKey( value = "HHH-17972") + @JiraKey(value = "HHH-17972") public void testChangeTenantWithConnectionReuse() { try (Session session = sessionFactory.withOptions().tenantIdentifier( FRONT_END_TENANT ).openSession()) { - Assert.assertThrows( "Cannot redefine the tenant identifier on a child session if the connection is reused", - SessionException.class, - () -> session.sessionWithOptions().tenantIdentifier( BACK_END_TENANT ).connection().openSession() + assertThrows( + SessionException.class, + () -> session.sessionWithOptions().tenantIdentifier( BACK_END_TENANT ).connection().openSession(), + "Cannot redefine the tenant identifier on a child session if the connection is reused" + ); - Assert.assertThrows( "Cannot redefine the tenant identifier on a child session if the connection is reused", - SessionException.class, - () -> session.sessionWithOptions().connection().tenantIdentifier( BACK_END_TENANT ).openSession() + assertThrows( + SessionException.class, + () -> session.sessionWithOptions().connection().tenantIdentifier( BACK_END_TENANT ).openSession(), + "Cannot redefine the tenant identifier on a child session if the connection is reused" ); } } protected Properties properties() { Properties properties = new Properties(); - URL propertiesURL = Thread.currentThread().getContextClassLoader().getResource("hibernate.properties"); - try(FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { - properties.load(inputStream); + URL propertiesURL = Thread.currentThread().getContextClassLoader().getResource( "hibernate.properties" ); + try (FileInputStream inputStream = new FileInputStream( propertiesURL.getFile() )) { + properties.load( inputStream ); } catch (IOException e) { - throw new IllegalArgumentException(e); + throw new IllegalArgumentException( e ); } return properties; } @@ -203,18 +204,18 @@ protected Properties properties() { protected SessionFactory sessionFactory(Map settings) { ServiceRegistryImplementor serviceRegistry = (ServiceRegistryImplementor) ServiceRegistryUtil.serviceRegistryBuilder() - .applySettings(settings) - .build(); + .applySettings( settings ) + .build(); - MetadataSources metadataSources = new MetadataSources(serviceRegistry); - for(Class annotatedClasses : getAnnotatedClasses()) { - metadataSources.addAnnotatedClass(annotatedClasses); + MetadataSources metadataSources = new MetadataSources( serviceRegistry ); + for ( Class annotatedClasses : getAnnotatedClasses() ) { + metadataSources.addAnnotatedClass( annotatedClasses ); } Metadata metadata = metadataSources.buildMetadata(); HibernateSchemaManagementTool tool = new HibernateSchemaManagementTool(); - tool.injectServices(serviceRegistry); + tool.injectServices( serviceRegistry ); new SchemaDropperImpl( serviceRegistry ).doDrop( metadata, @@ -260,7 +261,7 @@ protected SessionFactory sessionFactory(Map settings) { protected Class[] getAnnotatedClasses() { return new Class[] { - Person.class + Person.class }; } @@ -270,18 +271,22 @@ private void doInSession(String tenant, Consumer function) { Transaction txn = null; try { session = sessionFactory - .withOptions() - .tenantIdentifier(tenant) - .openSession(); + .withOptions() + .tenantIdentifier( tenant ) + .openSession(); txn = session.getTransaction(); txn.begin(); - function.accept(session); + function.accept( session ); txn.commit(); - } catch (Throwable e) { - if (txn != null) txn.rollback(); + } + catch (Throwable e) { + if ( txn != null ) { + txn.rollback(); + } throw e; - } finally { - if (session != null) { + } + finally { + if ( session != null ) { session.close(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/ConfigurationValidationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/ConfigurationValidationTest.java index e9fa4b1d13ec..e70f28739d4a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/ConfigurationValidationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/ConfigurationValidationTest.java @@ -13,39 +13,45 @@ import org.hibernate.service.spi.ServiceException; import org.hibernate.service.spi.ServiceRegistryImplementor; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.BaseUnitTest; import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.env.ConnectionProviderBuilder; -import org.hibernate.testing.junit4.BaseUnitTestCase; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; /** * @author Lukasz Antoniak */ @JiraKey(value = "HHH-7311") @RequiresDialect( H2Dialect.class ) -public class ConfigurationValidationTest extends BaseUnitTestCase { +@BaseUnitTest +public class ConfigurationValidationTest { - @Test(expected = ServiceException.class) + @Test public void testInvalidConnectionProvider() { - ServiceRegistryImplementor serviceRegistry = null; - try { - serviceRegistry = (ServiceRegistryImplementor) ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( Environment.MULTI_TENANT_CONNECTION_PROVIDER, "class.not.present.in.classpath" ) - .build(); + assertThrows(ServiceException.class, ()-> { + ServiceRegistryImplementor serviceRegistry = null; + try { + serviceRegistry = (ServiceRegistryImplementor) ServiceRegistryUtil.serviceRegistryBuilder() + .applySetting( Environment.MULTI_TENANT_CONNECTION_PROVIDER, "class.not.present.in.classpath" ) + .build(); - new MetadataSources( serviceRegistry ).buildMetadata().buildSessionFactory().close(); - } - finally { - if ( serviceRegistry != null ) { - try { - StandardServiceRegistryBuilder.destroy( serviceRegistry ); + new MetadataSources( serviceRegistry ).buildMetadata().buildSessionFactory().close(); + } + finally { + if ( serviceRegistry != null ) { + try { + StandardServiceRegistryBuilder.destroy( serviceRegistry ); + } + catch (Exception ignore) { + } + } + } } - catch (Exception ignore) { - } - } - } + ); } @Test diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/DatabaseMultiTenancyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/DatabaseMultiTenancyTest.java index f8e3ef992f7c..c362e16ecda1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/DatabaseMultiTenancyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/DatabaseMultiTenancyTest.java @@ -5,8 +5,7 @@ package org.hibernate.orm.test.multitenancy; import org.hibernate.dialect.H2Dialect; - -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.RequiresDialect; /** * @author Vlad Mihalcea @@ -16,6 +15,6 @@ public class DatabaseMultiTenancyTest extends AbstractMultiTenancyTest { @Override protected String tenantUrl(String originalUrl, String tenantIdentifier) { - return originalUrl.replace("db1", tenantIdentifier); + return originalUrl.replace( "db1", tenantIdentifier ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/DatabaseTimeZoneMultiTenancyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/DatabaseTimeZoneMultiTenancyTest.java index 4ecf1303b11f..8e7166573aaa 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/DatabaseTimeZoneMultiTenancyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/DatabaseTimeZoneMultiTenancyTest.java @@ -4,21 +4,9 @@ */ package org.hibernate.orm.test.multitenancy; -import java.io.FileInputStream; -import java.io.IOException; -import java.net.URL; -import java.sql.Timestamp; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; -import java.util.TimeZone; -import java.util.function.Consumer; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; - import org.hibernate.Session; import org.hibernate.SessionBuilder; import org.hibernate.SessionFactory; @@ -32,28 +20,39 @@ import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProvider; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.hibernate.internal.util.PropertiesHelper; +import org.hibernate.orm.test.util.DdlTransactionIsolatorTestingImpl; import org.hibernate.service.spi.ServiceRegistryImplementor; import org.hibernate.service.spi.Stoppable; +import org.hibernate.testing.orm.junit.BaseUnitTest; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.util.ServiceRegistryUtil; import org.hibernate.tool.schema.internal.HibernateSchemaManagementTool; import org.hibernate.tool.schema.internal.SchemaCreatorImpl; import org.hibernate.tool.schema.internal.SchemaDropperImpl; import org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.AfterClassOnce; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.hibernate.testing.util.ServiceRegistryUtil; - -import org.hibernate.orm.test.util.DdlTransactionIsolatorTestingImpl; -import org.junit.Test; +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.sql.Timestamp; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import java.util.TimeZone; +import java.util.function.Consumer; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Vlad Mihalcea */ @RequiresDialect(H2Dialect.class) -public class DatabaseTimeZoneMultiTenancyTest extends BaseUnitTestCase { +@BaseUnitTest +public class DatabaseTimeZoneMultiTenancyTest { protected static final String FRONT_END_TENANT = "front_end"; protected static final String BACK_END_TENANT = "back_end"; @@ -72,26 +71,32 @@ public DatabaseTimeZoneMultiTenancyTest() { private void init() { //tag::multitenacy-hibernate-timezone-configuration-registerConnectionProvider-call-example[] - registerConnectionProvider(FRONT_END_TENANT, TimeZone.getTimeZone("UTC")); - registerConnectionProvider(BACK_END_TENANT, TimeZone.getTimeZone("CST")); + registerConnectionProvider( FRONT_END_TENANT, TimeZone.getTimeZone( "UTC" ) ); + registerConnectionProvider( BACK_END_TENANT, TimeZone.getTimeZone( "CST" ) ); //end::multitenacy-hibernate-timezone-configuration-registerConnectionProvider-call-example[] Map settings = new HashMap<>(); settings.put( AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, - new ConfigurableMultiTenantConnectionProvider(connectionProviderMap) - ); + new ConfigurableMultiTenantConnectionProvider( connectionProviderMap ) + ); - sessionFactory = sessionFactory(settings); + sessionFactory = sessionFactory( settings ); } - @AfterClassOnce + @AfterAll public void destroy() { - sessionFactory.close(); - for (ConnectionProvider connectionProvider : connectionProviderMap.values()) { - if (connectionProvider instanceof Stoppable) { - ((Stoppable) connectionProvider).stop(); + try { + if ( sessionFactory != null ) { + sessionFactory.close(); + } + } + finally { + for ( ConnectionProvider connectionProvider : connectionProviderMap.values() ) { + if ( connectionProvider instanceof Stoppable ) { + ((Stoppable) connectionProvider).stop(); + } } } } @@ -100,17 +105,17 @@ public void destroy() { protected void registerConnectionProvider(String tenantIdentifier, TimeZone timeZone) { Properties properties = properties(); properties.put( - Environment.URL, - tenantUrl( properties.getProperty(Environment.URL), tenantIdentifier ) - ); + Environment.URL, + tenantUrl( properties.getProperty( Environment.URL ), tenantIdentifier ) + ); DriverManagerConnectionProvider connectionProvider = new DriverManagerConnectionProvider(); - connectionProvider.configure( PropertiesHelper.map(properties) ); + connectionProvider.configure( PropertiesHelper.map( properties ) ); - connectionProviderMap.put(tenantIdentifier, connectionProvider); + connectionProviderMap.put( tenantIdentifier, connectionProvider ); - timeZoneTenantMap.put(tenantIdentifier, timeZone); + timeZoneTenantMap.put( tenantIdentifier, timeZone ); } //end::multitenacy-hibernate-timezone-configuration-registerConnectionProvider-example[] @@ -118,118 +123,103 @@ protected void registerConnectionProvider(String tenantIdentifier, TimeZone time public void testBasicExpectedBehavior() { //tag::multitenacy-hibernate-applying-timezone-configuration-example[] - doInSession(FRONT_END_TENANT, session -> { + doInSession( FRONT_END_TENANT, session -> { Person person = new Person(); - person.setId(1L); - person.setName("John Doe"); - person.setCreatedOn(LocalDateTime.of(2018, 11, 23, 12, 0, 0)); + person.setId( 1L ); + person.setName( "John Doe" ); + person.setCreatedOn( LocalDateTime.of( 2018, 11, 23, 12, 0, 0 ) ); - session.persist(person); - }, true); + session.persist( person ); + }, true ); - doInSession(BACK_END_TENANT, session -> { + doInSession( BACK_END_TENANT, session -> { Person person = new Person(); - person.setId(1L); - person.setName("John Doe"); - person.setCreatedOn(LocalDateTime.of(2018, 11, 23, 12, 0, 0)); + person.setId( 1L ); + person.setName( "John Doe" ); + person.setCreatedOn( LocalDateTime.of( 2018, 11, 23, 12, 0, 0 ) ); - session.persist(person); - }, true); + session.persist( person ); + }, true ); - doInSession(FRONT_END_TENANT, session -> { + doInSession( FRONT_END_TENANT, session -> { Timestamp personCreationTimestamp = session - .createNativeQuery( - "select p.created_on " + - "from Person p " + - "where p.id = :personId", Timestamp.class) - .setParameter("personId", 1L) - .getSingleResult(); - - assertEquals( - Timestamp.valueOf(LocalDateTime.of(2018, 11, 23, 12, 0, 0)), - personCreationTimestamp - ); - }, true); - - doInSession(BACK_END_TENANT, session -> { + .createNativeQuery( + "select p.created_on " + + "from Person p " + + "where p.id = :personId", Timestamp.class ) + .setParameter( "personId", 1L ) + .getSingleResult(); + + assertThat( personCreationTimestamp ) + .isEqualTo( Timestamp.valueOf( LocalDateTime.of( 2018, 11, 23, 12, 0, 0 ) ) ); + }, true ); + + doInSession( BACK_END_TENANT, session -> { Timestamp personCreationTimestamp = session - .createNativeQuery( - "select p.created_on " + - "from Person p " + - "where p.id = :personId", Timestamp.class) - .setParameter("personId", 1L) - .getSingleResult(); - - assertEquals( - Timestamp.valueOf(LocalDateTime.of(2018, 11, 23, 12, 0, 0)), - personCreationTimestamp - ); - }, true); + .createNativeQuery( + "select p.created_on " + + "from Person p " + + "where p.id = :personId", Timestamp.class ) + .setParameter( "personId", 1L ) + .getSingleResult(); + + assertThat( personCreationTimestamp ) + .isEqualTo( Timestamp.valueOf( LocalDateTime.of( 2018, 11, 23, 12, 0, 0 ) ) ); + }, true ); //end::multitenacy-hibernate-applying-timezone-configuration-example[] //tag::multitenacy-hibernate-not-applying-timezone-configuration-example[] - doInSession(FRONT_END_TENANT, session -> { + doInSession( FRONT_END_TENANT, session -> { Timestamp personCreationTimestamp = session - .createNativeQuery( - "select p.created_on " + - "from Person p " + - "where p.id = :personId", Timestamp.class) - .setParameter("personId", 1L) - .getSingleResult(); - - log.infof( - "The created_on timestamp value is: [%s]", - personCreationTimestamp - ); + .createNativeQuery( + "select p.created_on " + + "from Person p " + + "where p.id = :personId", Timestamp.class ) + .setParameter( "personId", 1L ) + .getSingleResult(); long timeZoneOffsetMillis = - Timestamp.valueOf(LocalDateTime.of(2018, 11, 23, 12, 0, 0)).getTime() - + Timestamp.valueOf( LocalDateTime.of( 2018, 11, 23, 12, 0, 0 ) ).getTime() - personCreationTimestamp.getTime(); - assertEquals( - TimeZone.getTimeZone(ZoneId.systemDefault()).getRawOffset(), - timeZoneOffsetMillis - ); + assertThat( timeZoneOffsetMillis ) + .isEqualTo( TimeZone.getTimeZone( ZoneId.systemDefault() ).getRawOffset() ); - log.infof( - "For the current time zone: [%s], the UTC time zone offset is: [%d]", - TimeZone.getDefault().getDisplayName(), timeZoneOffsetMillis - ); - }, false); + }, false ); //end::multitenacy-hibernate-not-applying-timezone-configuration-example[] } protected Properties properties() { Properties properties = new Properties(); - URL propertiesURL = Thread.currentThread().getContextClassLoader().getResource("hibernate.properties"); - try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { - properties.load(inputStream); + URL propertiesURL = Thread.currentThread().getContextClassLoader().getResource( "hibernate.properties" ); + try (FileInputStream inputStream = new FileInputStream( propertiesURL.getFile() )) { + properties.load( inputStream ); } catch (IOException e) { - throw new IllegalArgumentException(e); + throw new IllegalArgumentException( e ); } return properties; } protected String tenantUrl(String originalUrl, String tenantIdentifier) { - return originalUrl.replace("db1", tenantIdentifier); + return originalUrl.replace( "db1", tenantIdentifier ); } protected SessionFactory sessionFactory(Map settings) { ServiceRegistryImplementor serviceRegistry = (ServiceRegistryImplementor) ServiceRegistryUtil.serviceRegistryBuilder() - .applySettings(settings) + .applySettings( settings ) .build(); - MetadataSources metadataSources = new MetadataSources(serviceRegistry); - for (Class annotatedClasses : getAnnotatedClasses()) { - metadataSources.addAnnotatedClass(annotatedClasses); + MetadataSources metadataSources = new MetadataSources( serviceRegistry ); + for ( Class annotatedClasses : getAnnotatedClasses() ) { + metadataSources.addAnnotatedClass( annotatedClasses ); } Metadata metadata = metadataSources.buildMetadata(); HibernateSchemaManagementTool tool = new HibernateSchemaManagementTool(); - tool.injectServices(serviceRegistry); + tool.injectServices( serviceRegistry ); new SchemaDropperImpl( serviceRegistry ).doDrop( metadata, @@ -287,10 +277,10 @@ private void doInSession(String tenant, Consumer function, boolean useT try { SessionBuilder sessionBuilder = sessionFactory .withOptions() - .tenantIdentifier(tenant); + .tenantIdentifier( tenant ); - if (useTenantTimeZone) { - sessionBuilder.jdbcTimeZone(timeZoneTenantMap.get(tenant)); + if ( useTenantTimeZone ) { + sessionBuilder.jdbcTimeZone( timeZoneTenantMap.get( tenant ) ); } session = sessionBuilder.openSession(); @@ -298,18 +288,18 @@ private void doInSession(String tenant, Consumer function, boolean useT txn = session.getTransaction(); txn.begin(); - function.accept(session); + function.accept( session ); txn.commit(); } catch (Throwable e) { - if (txn != null) { + if ( txn != null ) { txn.rollback(); } throw e; } finally { - if (session != null) { + if ( session != null ) { session.close(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/SchemaMultiTenancyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/SchemaMultiTenancyTest.java index a4f65d148623..15b257937141 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/SchemaMultiTenancyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/SchemaMultiTenancyTest.java @@ -5,8 +5,7 @@ package org.hibernate.orm.test.multitenancy; import org.hibernate.dialect.H2Dialect; - -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.RequiresDialect; /** * @author Vlad Mihalcea diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/beancontainer/MultiTenantConnectionProviderFromBeanContainerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/beancontainer/MultiTenantConnectionProviderFromBeanContainerTest.java index b5a6ccb4e0ae..169eede03b34 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/beancontainer/MultiTenantConnectionProviderFromBeanContainerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/beancontainer/MultiTenantConnectionProviderFromBeanContainerTest.java @@ -18,9 +18,9 @@ import org.hibernate.resource.beans.spi.BeanInstanceProducer; import org.hibernate.testing.orm.junit.RequiresDialect; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Yanming Zhou @@ -89,7 +89,7 @@ protected String tenantUrl(String originalUrl, String tenantIdentifier) { @Test public void testProviderInUse() { MultiTenantConnectionProvider providerInUse = ((SessionFactoryImpl) sessionFactory).getServiceRegistry().getService( MultiTenantConnectionProvider.class ); - assertSame( providerInUse, expectedProviderInUse()); + assertThat( providerInUse).isSameAs( expectedProviderInUse() ); } protected MultiTenantConnectionProvider expectedProviderInUse() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/discriminator/DiscriminatorMultiTenancyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/discriminator/DiscriminatorMultiTenancyTest.java index ab3fca1ce893..f74388ce7740 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/discriminator/DiscriminatorMultiTenancyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/discriminator/DiscriminatorMultiTenancyTest.java @@ -4,49 +4,50 @@ */ package org.hibernate.orm.test.multitenancy.discriminator; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Consumer; - import org.hibernate.Session; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.SessionFactoryBuilder; import org.hibernate.cfg.Environment; import org.hibernate.context.spi.CurrentTenantIdentifierResolver; +import org.hibernate.dialect.H2Dialect; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.RootClass; +import org.hibernate.orm.test.multitenancy.schema.Customer; +import org.hibernate.orm.test.util.DdlTransactionIsolatorTestingImpl; import org.hibernate.service.spi.ServiceRegistryImplementor; import org.hibernate.service.spi.Stoppable; +import org.hibernate.testing.cache.CachingRegionFactory; +import org.hibernate.testing.env.ConnectionProviderBuilder; +import org.hibernate.testing.orm.junit.BaseUnitTest; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.transaction.TransactionUtil; +import org.hibernate.testing.util.ServiceRegistryUtil; import org.hibernate.tool.schema.internal.HibernateSchemaManagementTool; import org.hibernate.tool.schema.internal.SchemaCreatorImpl; import org.hibernate.tool.schema.internal.SchemaDropperImpl; import org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.RequiresDialectFeature; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.cache.CachingRegionFactory; -import org.hibernate.testing.env.ConnectionProviderBuilder; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.hibernate.testing.transaction.TransactionUtil; -import org.hibernate.testing.util.ServiceRegistryUtil; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Consumer; -import org.hibernate.orm.test.multitenancy.schema.Customer; -import org.hibernate.orm.test.util.DdlTransactionIsolatorTestingImpl; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Mårten Svantesson */ @JiraKey(value = "HHH-11980") -@RequiresDialectFeature( value = ConnectionProviderBuilder.class ) -public class DiscriminatorMultiTenancyTest extends BaseUnitTestCase { +@RequiresDialect(H2Dialect.class) +@BaseUnitTest +public class DiscriminatorMultiTenancyTest { private SessionFactoryImplementor sessionFactory; @@ -54,15 +55,15 @@ public class DiscriminatorMultiTenancyTest extends BaseUnitTestCase { private final TestCurrentTenantIdentifierResolver currentTenantResolver = new TestCurrentTenantIdentifierResolver(); - @Before + @BeforeEach public void setUp() { - Map settings = new HashMap<>(); - settings.put(Environment.MULTI_TENANT_IDENTIFIER_RESOLVER, currentTenantResolver); - settings.put(Environment.CACHE_REGION_FACTORY, CachingRegionFactory.class.getName()); - settings.put(Environment.GENERATE_STATISTICS, "true"); + Map settings = new HashMap<>(); + settings.put( Environment.MULTI_TENANT_IDENTIFIER_RESOLVER, currentTenantResolver ); + settings.put( Environment.CACHE_REGION_FACTORY, CachingRegionFactory.class.getName() ); + settings.put( Environment.GENERATE_STATISTICS, "true" ); ServiceRegistryImplementor serviceRegistry = (ServiceRegistryImplementor) ServiceRegistryUtil.serviceRegistryBuilder() - .applySettings(settings) + .applySettings( settings ) .build(); try { @@ -72,7 +73,7 @@ public void setUp() { Metadata metadata = ms.buildMetadata(); final PersistentClass customerMapping = metadata.getEntityBinding( Customer.class.getName() ); customerMapping.setCached( true ); - ( (RootClass) customerMapping ).setCacheConcurrencyStrategy( "read-write" ); + ((RootClass) customerMapping).setCacheConcurrencyStrategy( "read-write" ); HibernateSchemaManagementTool tool = new HibernateSchemaManagementTool(); tool.injectServices( serviceRegistry ); @@ -83,7 +84,6 @@ public void setUp() { new DdlTransactionIsolatorTestingImpl( tool.resolveJdbcContext( settings ) ) ); - new SchemaDropperImpl( serviceRegistry ).doDrop( metadata, serviceRegistry, @@ -110,10 +110,10 @@ public void setUp() { } } - @After + @AfterEach public void destroy() { sessionFactory.close(); - ( (Stoppable) connectionProvider ).stop(); + ((Stoppable) connectionProvider).stop(); } public SessionFactoryImplementor sessionFactory() { @@ -137,9 +137,9 @@ public void testDiscriminator() { // make sure we get the steve back, from cache if same tenant (jboss) doInHibernate( "jboss", session -> { Customer customer = session.getReference( Customer.class, 1L ); - Assert.assertEquals( "steve", customer.getName() ); + assertThat( customer.getName() ).isEqualTo( "steve" ); // also, make sure this came from second level - Assert.assertEquals( 1, sessionFactory.getStatistics().getSecondLevelCacheHitCount() ); + assertThat( sessionFactory.getStatistics().getSecondLevelCacheHitCount() ).isEqualTo( 1 ); } ); sessionFactory.getStatistics().clear(); @@ -147,9 +147,9 @@ public void testDiscriminator() { // then make sure we get the steve back, from db if other tenant (acme) doInHibernate( "acme", session -> { Customer customer = session.getReference( Customer.class, 1L ); - Assert.assertEquals( "steve", customer.getName() ); + assertThat( customer.getName() ).isEqualTo( "steve" ); // also, make sure this doesn't came from second level - Assert.assertEquals( 0, sessionFactory.getStatistics().getSecondLevelCacheHitCount() ); + assertThat( sessionFactory.getStatistics().getSecondLevelCacheHitCount() ).isEqualTo( 0 ); } ); // make sure the same works from data store too @@ -159,18 +159,18 @@ public void testDiscriminator() { // first jboss doInHibernate( "jboss", session -> { Customer customer = session.getReference( Customer.class, 1L ); - Assert.assertEquals( "steve", customer.getName() ); + assertThat( customer.getName() ).isEqualTo( "steve" ); // also, make sure this doesn't came from second level - Assert.assertEquals( 0, sessionFactory.getStatistics().getSecondLevelCacheHitCount() ); + assertThat( sessionFactory.getStatistics().getSecondLevelCacheHitCount() ).isEqualTo( 0 ); } ); sessionFactory.getStatistics().clear(); // then, acme doInHibernate( "acme", session -> { Customer customer = session.getReference( Customer.class, 1L ); - Assert.assertEquals( "steve", customer.getName() ); + assertThat( customer.getName() ).isEqualTo( "steve" ); // also, make sure this doesn't came from second level - Assert.assertEquals( 0, sessionFactory.getStatistics().getSecondLevelCacheHitCount() ); + assertThat( sessionFactory.getStatistics().getSecondLevelCacheHitCount() ).isEqualTo( 0 ); } ); doInHibernate( "jboss", session -> { @@ -181,7 +181,7 @@ public void testDiscriminator() { private static class TestCurrentTenantIdentifierResolver implements CurrentTenantIdentifierResolver { private String currentTenantIdentifier; - private final AtomicBoolean postBoot = new AtomicBoolean(false); + private final AtomicBoolean postBoot = new AtomicBoolean( false ); public void setHibernateBooted() { postBoot.set( true ); @@ -189,10 +189,11 @@ public void setHibernateBooted() { @Override public Object resolveCurrentTenantIdentifier() { - if ( postBoot.get() == false ) { + if ( !postBoot.get() ) { //Check to prevent any optimisation which might want to cache the tenantId too early during bootstrap: //it's a common use case to want to provide the tenantId, for example, via a ThreadLocal. - throw new IllegalStateException( "Not booted yet: illegal to try reading the tenant Id at this point!" ); + throw new IllegalStateException( + "Not booted yet: illegal to try reading the tenant Id at this point!" ); } return currentTenantIdentifier; } @@ -207,6 +208,6 @@ public void doInHibernate(String tenant, Consumer function) { currentTenantResolver.currentTenantIdentifier = tenant; //Careful: do not use the #doInHibernate version of the method which takes a tenant: the goal of these tests is // to verify that the CurrentTenantIdentifierResolver is being applied! - TransactionUtil.doInHibernate( this::sessionFactory, function); + TransactionUtil.doInHibernate( this::sessionFactory, function ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/schema/AbstractSchemaBasedMultiTenancyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/schema/AbstractSchemaBasedMultiTenancyTest.java index 665024a697c5..58aca31fface 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/schema/AbstractSchemaBasedMultiTenancyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/schema/AbstractSchemaBasedMultiTenancyTest.java @@ -4,9 +4,6 @@ */ package org.hibernate.orm.test.multitenancy.schema; -import java.util.HashMap; -import java.util.Map; - import org.hibernate.SessionBuilder; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; @@ -18,32 +15,30 @@ import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.RootClass; +import org.hibernate.orm.test.util.DdlTransactionIsolatorTestingImpl; import org.hibernate.service.spi.ServiceRegistryImplementor; import org.hibernate.service.spi.Stoppable; +import org.hibernate.testing.cache.CachingRegionFactory; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.util.ServiceRegistryUtil; import org.hibernate.tool.schema.internal.HibernateSchemaManagementTool; import org.hibernate.tool.schema.internal.SchemaCreatorImpl; import org.hibernate.tool.schema.internal.SchemaDropperImpl; import org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.cache.CachingRegionFactory; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.hibernate.testing.util.ServiceRegistryUtil; - -import org.hibernate.orm.test.util.DdlTransactionIsolatorTestingImpl; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import java.util.HashMap; +import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernateSessionBuilder; +import static org.hibernate.testing.orm.junit.BaseSessionFactoryFunctionalTest.doInHibernateSessionBuilder; /** * @author Steve Ebersole */ -public abstract class AbstractSchemaBasedMultiTenancyTest, C extends ConnectionProvider> extends BaseUnitTestCase { +public abstract class AbstractSchemaBasedMultiTenancyTest, C extends ConnectionProvider> { protected C acmeProvider; protected C jbossProvider; @@ -55,11 +50,11 @@ protected SessionFactoryImplementor getSessionFactory() { return sessionFactory; } - @Before + @BeforeEach public void setUp() { T multiTenantConnectionProvider = buildMultiTenantConnectionProvider(); - Map settings = new HashMap<>(); + Map settings = new HashMap<>(); settings.put( Environment.CACHE_REGION_FACTORY, CachingRegionFactory.class.getName() ); settings.put( Environment.GENERATE_STATISTICS, "true" ); @@ -78,7 +73,7 @@ public void setUp() { Metadata metadata = ms.buildMetadata(); final PersistentClass customerMapping = metadata.getEntityBinding( Customer.class.getName() ); customerMapping.setCached( true ); - ( (RootClass) customerMapping ).setCacheConcurrencyStrategy( "read-write" ); + ((RootClass) customerMapping).setCacheConcurrencyStrategy( "read-write" ); HibernateSchemaManagementTool tool = new HibernateSchemaManagementTool(); tool.injectServices( serviceRegistry ); @@ -131,7 +126,7 @@ protected void configure(SessionFactoryBuilder sfb) { protected abstract T buildMultiTenantConnectionProvider(); - @After + @AfterEach public void tearDown() { if ( sessionFactory != null ) { sessionFactory.close(); @@ -140,18 +135,18 @@ public void tearDown() { serviceRegistry.destroy(); } if ( jbossProvider != null ) { - ( (Stoppable) jbossProvider ).stop(); + ((Stoppable) jbossProvider).stop(); } if ( acmeProvider != null ) { - ( (Stoppable) acmeProvider ).stop(); + ((Stoppable) acmeProvider).stop(); } } @Test @JiraKey(value = "HHH-16310") public void testJdbcMetadataAccessible() { - assertThat( ( (ExtractedDatabaseMetaDataImpl) sessionFactory.getJdbcServices().getJdbcEnvironment() - .getExtractedDatabaseMetaData() ).isJdbcMetadataAccessible() ) + assertThat( ((ExtractedDatabaseMetaDataImpl) sessionFactory.getJdbcServices().getJdbcEnvironment() + .getExtractedDatabaseMetaData()).isJdbcMetadataAccessible() ) .isTrue(); } @@ -165,7 +160,9 @@ public void testBasicExpectedBehavior() { doInHibernateSessionBuilder( this::acme, session -> { Customer check = session.get( Customer.class, steve.getId() ); - Assert.assertNull( "tenancy not properly isolated", check ); + assertThat( check ) + .describedAs( "tenancy not properly isolated" ) + .isNull(); } ); doInHibernateSessionBuilder( this::jboss, session -> { @@ -195,18 +192,18 @@ public void testSameIdentifiers() { // first, jboss doInHibernateSessionBuilder( this::jboss, session -> { Customer customer = session.getReference( Customer.class, 1L ); - Assert.assertEquals( "steve", customer.getName() ); + assertThat( customer.getName()).isEqualTo("steve"); // also, make sure this came from second level - Assert.assertEquals( 1, sessionFactory.getStatistics().getSecondLevelCacheHitCount() ); + assertThat( sessionFactory.getStatistics().getSecondLevelCacheHitCount()).isEqualTo(1); } ); sessionFactory.getStatistics().clear(); // then, acme doInHibernateSessionBuilder( this::acme, session -> { Customer customer = session.getReference( Customer.class, 1L ); - Assert.assertEquals( "john", customer.getName() ); + assertThat( customer.getName()).isEqualTo("john"); // also, make sure this came from second level - Assert.assertEquals( 1, sessionFactory.getStatistics().getSecondLevelCacheHitCount() ); + assertThat( sessionFactory.getStatistics().getSecondLevelCacheHitCount()).isEqualTo(1); } ); // make sure the same works from datastore too @@ -215,18 +212,18 @@ public void testSameIdentifiers() { // first jboss doInHibernateSessionBuilder( this::jboss, session -> { Customer customer = session.getReference( Customer.class, 1L ); - Assert.assertEquals( "steve", customer.getName() ); + assertThat( customer.getName()).isEqualTo("steve"); // also, make sure this came from second level - Assert.assertEquals( 0, sessionFactory.getStatistics().getSecondLevelCacheHitCount() ); + assertThat( sessionFactory.getStatistics().getSecondLevelCacheHitCount()).isEqualTo(0); } ); sessionFactory.getStatistics().clear(); // then, acme doInHibernateSessionBuilder( this::acme, session -> { Customer customer = session.getReference( Customer.class, 1L ); - Assert.assertEquals( "john", customer.getName() ); + assertThat( customer.getName()).isEqualTo("john"); // also, make sure this came from second level - Assert.assertEquals( 0, sessionFactory.getStatistics().getSecondLevelCacheHitCount() ); + assertThat( sessionFactory.getStatistics().getSecondLevelCacheHitCount()).isEqualTo(0); } ); doInHibernateSessionBuilder( this::jboss, session -> { @@ -243,14 +240,14 @@ public void testTableIdentifiers() { Invoice orderJboss = doInHibernateSessionBuilder( this::jboss, session -> { Invoice _orderJboss = new Invoice(); session.persist( _orderJboss ); - Assert.assertEquals( Long.valueOf( 1 ), _orderJboss.getId() ); + assertThat( _orderJboss.getId()).isEqualTo(1L); return _orderJboss; } ); Invoice orderAcme = doInHibernateSessionBuilder( this::acme, session -> { Invoice _orderAcme = new Invoice(); session.persist( _orderAcme ); - Assert.assertEquals( Long.valueOf( 1 ), _orderAcme.getId() ); + assertThat( _orderAcme.getId()).isEqualTo(1L); return _orderAcme; } ); @@ -267,8 +264,8 @@ public void testTableIdentifiers() { protected SessionBuilder newSession(String tenant) { return sessionFactory - .withOptions() - .tenantIdentifier( (Object) tenant ); + .withOptions() + .tenantIdentifier( (Object) tenant ); } private SessionBuilder jboss() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/schema/SchemaBasedDataSourceMultiTenancyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/schema/SchemaBasedDataSourceMultiTenancyTest.java index 2bacfae41019..4a351862033b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/schema/SchemaBasedDataSourceMultiTenancyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/schema/SchemaBasedDataSourceMultiTenancyTest.java @@ -4,27 +4,26 @@ */ package org.hibernate.orm.test.multitenancy.schema; -import javax.sql.DataSource; - import org.hibernate.HibernateException; +import org.hibernate.dialect.H2Dialect; import org.hibernate.engine.jdbc.connections.spi.AbstractDataSourceBasedMultiTenantConnectionProviderImpl; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider; - -import org.hibernate.testing.RequiresDialectFeature; -import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.env.ConnectionProviderBuilder; -import org.junit.Test; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.junit.jupiter.api.Test; + +import javax.sql.DataSource; + +import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.core.Is.is; -import static org.hamcrest.core.IsNull.notNullValue; -import static org.junit.Assert.assertThat; /** * @author Vlad Mihalcea */ -@RequiresDialectFeature( value = ConnectionProviderBuilder.class ) -public class SchemaBasedDataSourceMultiTenancyTest extends AbstractSchemaBasedMultiTenancyTest< +@RequiresDialect(H2Dialect.class) +public class SchemaBasedDataSourceMultiTenancyTest extends AbstractSchemaBasedMultiTenancyTest< AbstractDataSourceBasedMultiTenantConnectionProviderImpl, ConnectionProvider> { protected AbstractDataSourceBasedMultiTenantConnectionProviderImpl buildMultiTenantConnectionProvider() { @@ -50,12 +49,12 @@ else if ( "jboss".equals( tenantIdentifier ) ) { } @Test - @JiraKey( value = "HHH-11651") + @JiraKey(value = "HHH-11651") public void testUnwrappingConnectionProvider() { final MultiTenantConnectionProvider multiTenantConnectionProvider = serviceRegistry.getService( MultiTenantConnectionProvider.class ); final DataSource dataSource = multiTenantConnectionProvider.unwrap( DataSource.class ); - assertThat( dataSource, is( notNullValue() ) ); + assertThat( dataSource ).isNotNull(); } @Test @@ -65,7 +64,7 @@ public void testUnwrappingAbstractMultiTenantConnectionProvider() { MultiTenantConnectionProvider.class ); final AbstractDataSourceBasedMultiTenantConnectionProviderImpl dataSourceBasedMultiTenantConnectionProvider = multiTenantConnectionProvider.unwrap( AbstractDataSourceBasedMultiTenantConnectionProviderImpl.class ); - assertThat( dataSourceBasedMultiTenantConnectionProvider, is( notNullValue() ) ); + assertThat( dataSourceBasedMultiTenantConnectionProvider ).isNotNull(); } @Test @@ -75,6 +74,6 @@ public void testUnwrappingMultiTenantConnectionProvider() { MultiTenantConnectionProvider.class ); final MultiTenantConnectionProvider connectionProvider = multiTenantConnectionProvider.unwrap( MultiTenantConnectionProvider.class ); - assertThat( connectionProvider, is( notNullValue() ) ); + assertThat( connectionProvider ).isNotNull(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/schema/SchemaBasedMultiTenancyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/schema/SchemaBasedMultiTenancyTest.java index e0329b5ce680..a44b2be2dcd3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/schema/SchemaBasedMultiTenancyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/schema/SchemaBasedMultiTenancyTest.java @@ -5,23 +5,21 @@ package org.hibernate.orm.test.multitenancy.schema; import org.hibernate.HibernateException; +import org.hibernate.dialect.H2Dialect; import org.hibernate.engine.jdbc.connections.spi.AbstractMultiTenantConnectionProvider; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider; - -import org.hibernate.testing.RequiresDialectFeature; -import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.env.ConnectionProviderBuilder; -import org.junit.Test; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.junit.jupiter.api.Test; -import static org.hamcrest.core.Is.is; -import static org.hamcrest.core.IsNull.notNullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Steve Ebersole */ -@RequiresDialectFeature( value = ConnectionProviderBuilder.class ) +@RequiresDialect(H2Dialect.class) public class SchemaBasedMultiTenancyTest extends AbstractSchemaBasedMultiTenancyTest< AbstractMultiTenantConnectionProvider, ConnectionProvider> { @@ -48,12 +46,12 @@ else if ( "jboss".equals( tenantIdentifier ) ) { } @Test - @JiraKey( value = "HHH-11651") + @JiraKey(value = "HHH-11651") public void testUnwrappingConnectionProvider() { final MultiTenantConnectionProvider multiTenantConnectionProvider = serviceRegistry.getService( MultiTenantConnectionProvider.class ); final ConnectionProvider connectionProvider = multiTenantConnectionProvider.unwrap( ConnectionProvider.class ); - assertThat( connectionProvider, is( notNullValue() ) ); + assertThat( connectionProvider ).isNotNull(); } @Test @@ -63,7 +61,7 @@ public void testUnwrappingAbstractMultiTenantConnectionProvider() { MultiTenantConnectionProvider.class ); final AbstractMultiTenantConnectionProvider connectionProvider = multiTenantConnectionProvider.unwrap( AbstractMultiTenantConnectionProvider.class ); - assertThat( connectionProvider, is( notNullValue() ) ); + assertThat( connectionProvider ).isNotNull(); } @Test @@ -73,6 +71,6 @@ public void testUnwrappingMultiTenantConnectionProvider() { MultiTenantConnectionProvider.class ); final MultiTenantConnectionProvider connectionProvider = multiTenantConnectionProvider.unwrap( MultiTenantConnectionProvider.class ); - assertThat( connectionProvider, is( notNullValue() ) ); + assertThat( connectionProvider ).isNotNull(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/schema/TenantResolverConfigurationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/schema/TenantResolverConfigurationTest.java index a96fe2b7de5d..28364d4c4d12 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/schema/TenantResolverConfigurationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/schema/TenantResolverConfigurationTest.java @@ -4,12 +4,16 @@ */ package org.hibernate.orm.test.multitenancy.schema; -import org.hibernate.cfg.Configuration; +import org.hibernate.boot.SessionFactoryBuilder; +import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.context.spi.CurrentTenantIdentifierResolver; - +import org.hibernate.engine.spi.SessionFactoryImplementor; +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.SessionFactoryProducer; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; import static org.junit.Assert.assertSame; @@ -17,19 +21,22 @@ * @author Vlad Mihalcea */ @JiraKey(value = "HHH-10964") -public class TenantResolverConfigurationTest extends BaseCoreFunctionalTestCase { +@SessionFactory +@DomainModel +public class TenantResolverConfigurationTest implements SessionFactoryProducer { private TestCurrentTenantIdentifierResolver currentTenantResolver = new TestCurrentTenantIdentifierResolver(); @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - configuration.setCurrentTenantIdentifierResolver( currentTenantResolver ); + public SessionFactoryImplementor produceSessionFactory(MetadataImplementor model) { + final SessionFactoryBuilder sessionFactoryBuilder = model.getSessionFactoryBuilder(); + sessionFactoryBuilder.applyCurrentTenantIdentifierResolver( currentTenantResolver); + return (SessionFactoryImplementor) sessionFactoryBuilder.build(); } @Test - public void testConfiguration() throws Exception { - assertSame(currentTenantResolver, sessionFactory().getCurrentTenantIdentifierResolver()); + public void testConfiguration(SessionFactoryScope scope) { + assertSame(currentTenantResolver, scope.getSessionFactory().getCurrentTenantIdentifierResolver()); } private static class TestCurrentTenantIdentifierResolver implements CurrentTenantIdentifierResolver { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/naming/AcmeCorpPhysicalNamingStrategyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/naming/AcmeCorpPhysicalNamingStrategyTest.java index 447040474579..77df7e716c4e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/naming/AcmeCorpPhysicalNamingStrategyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/naming/AcmeCorpPhysicalNamingStrategyTest.java @@ -8,14 +8,12 @@ import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; - import org.hibernate.testing.util.ServiceRegistryUtil; -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.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Steve Ebersole @@ -24,25 +22,25 @@ public class AcmeCorpPhysicalNamingStrategyTest { private AcmeCorpPhysicalNamingStrategy strategy = new AcmeCorpPhysicalNamingStrategy(); private StandardServiceRegistry serviceRegistry; - @Before + @BeforeEach public void prepareServiceRegistry() { serviceRegistry = ServiceRegistryUtil.serviceRegistryBuilder() .build(); } - @After + @AfterEach public void releaseServiceRegistry() { - if (serviceRegistry != null) { - StandardServiceRegistryBuilder.destroy(serviceRegistry); + if ( serviceRegistry != null ) { + StandardServiceRegistryBuilder.destroy( serviceRegistry ); } } @Test public void testTableNaming() { { - Identifier in = Identifier.toIdentifier("accountNumber"); - Identifier out = strategy.toPhysicalTableName(in, serviceRegistry.getService(JdbcEnvironment.class)); - assertThat(out.getText(), equalTo("acct_num")); + Identifier in = Identifier.toIdentifier( "accountNumber" ); + Identifier out = strategy.toPhysicalTableName( in, serviceRegistry.getService( JdbcEnvironment.class ) ); + assertThat( out.getText() ).isEqualTo( "acct_num" ); } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/namingstrategy/complete/BaseNamingTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/namingstrategy/complete/BaseNamingTests.java index 9c72e2c3f306..5f442ad67032 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/namingstrategy/complete/BaseNamingTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/namingstrategy/complete/BaseNamingTests.java @@ -15,19 +15,18 @@ import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Property; import org.hibernate.service.ServiceRegistry; - -import org.hibernate.testing.junit4.BaseUnitTestCase; +import org.hibernate.testing.orm.junit.BaseUnitTest; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Steve Ebersole */ -public abstract class BaseNamingTests extends BaseUnitTestCase { +@BaseUnitTest +public abstract class BaseNamingTests { @Test public void doTest() { @@ -50,7 +49,7 @@ public void doTest() { } finally { ServiceRegistry metaServiceRegistry = metadataSources.getServiceRegistry(); - if(metaServiceRegistry instanceof BootstrapServiceRegistry ) { + if ( metaServiceRegistry instanceof BootstrapServiceRegistry ) { BootstrapServiceRegistryBuilder.destroy( metaServiceRegistry ); } } @@ -62,25 +61,25 @@ public void doTest() { protected void validateCustomer(Metadata metadata) { final PersistentClass customerBinding = metadata.getEntityBinding( Customer.class.getName() ); - assertNotNull( customerBinding ); + assertThat( customerBinding ).isNotNull(); validateCustomerPrimaryTableName( customerBinding.getTable().getQuotedName() ); - assertEquals( 1, customerBinding.getIdentifier().getColumnSpan() ); + assertThat( customerBinding.getIdentifier().getColumnSpan() ).isEqualTo( 1 ); validateCustomerPrimaryKeyColumn( (Column) customerBinding.getIdentifier().getSelectables().get( 0 ) ); - assertNotNull( customerBinding.getVersion() ); - assertEquals( 1, customerBinding.getVersion().getColumnSpan() ); + assertThat( customerBinding.getVersion() ).isNotNull(); + assertThat( customerBinding.getVersion().getColumnSpan() ).isEqualTo( 1 ); validateCustomerVersionColumn( (Column) customerBinding.getVersion().getSelectables().get( 0 ) ); final Property nameBinding = customerBinding.getProperty( "name" ); - assertNotNull( nameBinding ); - assertEquals( 1, nameBinding.getColumnSpan() ); + assertThat( nameBinding ).isNotNull(); + assertThat( nameBinding.getColumnSpan() ).isEqualTo( 1 ); validateCustomerNameColumn( (Column) nameBinding.getSelectables().get( 0 ) ); final Property hqAddressBinding = customerBinding.getProperty( "hqAddress" ); - assertNotNull( hqAddressBinding ); - assertEquals( 3, hqAddressBinding.getColumnSpan() ); + assertThat( hqAddressBinding ).isNotNull(); + assertThat( hqAddressBinding.getColumnSpan() ).isEqualTo( 3 ); validateCustomerHqAddressComponent( assertTyping( Component.class, hqAddressBinding.getValue() ) ); } @@ -97,31 +96,31 @@ protected void validateCustomer(Metadata metadata) { protected void validateOrder(Metadata metadata) { final PersistentClass orderBinding = metadata.getEntityBinding( Order.class.getName() ); - assertNotNull( orderBinding ); + assertThat( orderBinding ).isNotNull(); validateOrderPrimaryTableName( orderBinding.getTable().getQuotedName() ); - assertEquals( 1, orderBinding.getIdentifier().getColumnSpan() ); + assertThat( orderBinding.getIdentifier().getColumnSpan() ).isEqualTo( 1 ); validateOrderPrimaryKeyColumn( (Column) orderBinding.getIdentifier().getSelectables().get( 0 ) ); final Property referenceCodeBinding = orderBinding.getProperty( "referenceCode" ); - assertNotNull( referenceCodeBinding ); - assertEquals( 1, referenceCodeBinding.getColumnSpan() ); + assertThat( referenceCodeBinding ).isNotNull(); + assertThat( referenceCodeBinding.getColumnSpan() ).isEqualTo( 1 ); validateOrderReferenceCodeColumn( (Column) referenceCodeBinding.getSelectables().get( 0 ) ); final Property placedBinding = orderBinding.getProperty( "placed" ); - assertNotNull( placedBinding ); - assertEquals( 1, placedBinding.getColumnSpan() ); + assertThat( placedBinding ).isNotNull(); + assertThat( placedBinding.getColumnSpan() ).isEqualTo( 1 ); validateOrderPlacedColumn( (Column) placedBinding.getSelectables().get( 0 ) ); final Property fulfilledBinding = orderBinding.getProperty( "fulfilled" ); - assertNotNull( fulfilledBinding ); - assertEquals( 1, fulfilledBinding.getColumnSpan() ); + assertThat( fulfilledBinding ).isNotNull(); + assertThat( fulfilledBinding.getColumnSpan() ).isEqualTo( 1 ); validateOrderFulfilledColumn( (Column) fulfilledBinding.getSelectables().get( 0 ) ); final Property customerBinding = orderBinding.getProperty( "customer" ); - assertNotNull( customerBinding ); - assertEquals( 1, customerBinding.getColumnSpan() ); + assertThat( customerBinding ).isNotNull(); + assertThat( customerBinding.getColumnSpan() ).isEqualTo( 1 ); validateOrderCustomerColumn( (Column) customerBinding.getSelectables().get( 0 ) ); } @@ -138,29 +137,28 @@ protected void validateOrder(Metadata metadata) { protected abstract void validateOrderCustomerColumn(Column column); - protected void validateZipCode(Metadata metadata) { final PersistentClass zipCodeBinding = metadata.getEntityBinding( ZipCode.class.getName() ); - assertNotNull( zipCodeBinding ); + assertThat( zipCodeBinding ).isNotNull(); validateZipCodePrimaryTableName( zipCodeBinding.getTable().getQuotedName() ); - assertEquals( 1, zipCodeBinding.getIdentifier().getColumnSpan() ); + assertThat( zipCodeBinding.getIdentifier().getColumnSpan() ).isEqualTo( 1 ); validateZipCodePrimaryKeyColumn( (Column) zipCodeBinding.getIdentifier().getSelectables().get( 0 ) ); final Property codeBinding = zipCodeBinding.getProperty( "code" ); - assertNotNull( codeBinding ); - assertEquals( 1, codeBinding.getColumnSpan() ); + assertThat( codeBinding ).isNotNull(); + assertThat( codeBinding.getColumnSpan() ).isEqualTo( 1 ); validateZipCodeCodeColumn( (Column) codeBinding.getSelectables().get( 0 ) ); final Property cityBinding = zipCodeBinding.getProperty( "city" ); - assertNotNull( cityBinding ); - assertEquals( 1, cityBinding.getColumnSpan() ); + assertThat( cityBinding ).isNotNull(); + assertThat( cityBinding.getColumnSpan() ).isEqualTo( 1 ); validateZipCodeCityColumn( (Column) cityBinding.getSelectables().get( 0 ) ); final Property stateBinding = zipCodeBinding.getProperty( "state" ); - assertNotNull( stateBinding ); - assertEquals( 1, stateBinding.getColumnSpan() ); + assertThat( stateBinding ).isNotNull(); + assertThat( stateBinding.getColumnSpan() ).isEqualTo( 1 ); validateZipCodeStateColumn( (Column) stateBinding.getSelectables().get( 0 ) ); } @@ -176,15 +174,16 @@ protected void validateZipCode(Metadata metadata) { protected void validateCustomerRegisteredTrademarks(Metadata metadata) { - final Collection collectionBinding = metadata.getCollectionBinding( Customer.class.getName() + ".registeredTrademarks" ); - assertNotNull( collectionBinding ); + final Collection collectionBinding = metadata.getCollectionBinding( + Customer.class.getName() + ".registeredTrademarks" ); + assertThat( collectionBinding ).isNotNull(); validateCustomerRegisteredTrademarksTableName( collectionBinding.getCollectionTable().getQuotedName() ); - assertEquals( 1, collectionBinding.getKey().getColumnSpan() ); + assertThat( collectionBinding.getKey().getColumnSpan() ).isEqualTo( 1 ); validateCustomerRegisteredTrademarksKeyColumn( (Column) collectionBinding.getKey().getSelectables().get( 0 ) ); - assertEquals( 1, collectionBinding.getElement().getColumnSpan() ); + assertThat( collectionBinding.getElement().getColumnSpan() ).isEqualTo( 1 ); validateCustomerRegisteredTrademarksElementColumn( (Column) collectionBinding.getElement() .getSelectables() @@ -201,14 +200,14 @@ protected void validateCustomerRegisteredTrademarks(Metadata metadata) { protected void validateCustomerAddresses(Metadata metadata) { final Collection collectionBinding = metadata.getCollectionBinding( Customer.class.getName() + ".addresses" ); - assertNotNull( collectionBinding ); + assertThat( collectionBinding ).isNotNull(); validateCustomerAddressesTableName( collectionBinding.getCollectionTable().getQuotedName() ); - assertEquals( 1, collectionBinding.getKey().getColumnSpan() ); + assertThat( collectionBinding.getKey().getColumnSpan() ).isEqualTo( 1 ); validateCustomerAddressesKeyColumn( (Column) collectionBinding.getKey().getSelectables().get( 0 ) ); - assertEquals( 3, collectionBinding.getElement().getColumnSpan() ); + assertThat( collectionBinding.getElement().getColumnSpan() ).isEqualTo( 3 ); validateCustomerAddressesElementComponent( assertTyping( Component.class, collectionBinding.getElement() ) ); } @@ -221,14 +220,14 @@ protected void validateCustomerAddresses(Metadata metadata) { protected void validateCustomerOrders(Metadata metadata) { final Collection collectionBinding = metadata.getCollectionBinding( Customer.class.getName() + ".orders" ); - assertNotNull( collectionBinding ); + assertThat( collectionBinding ).isNotNull(); validateCustomerOrdersTableName( collectionBinding.getCollectionTable().getQuotedName() ); - assertEquals( 1, collectionBinding.getKey().getColumnSpan() ); + assertThat( collectionBinding.getKey().getColumnSpan() ).isEqualTo( 1 ); validateCustomerOrdersKeyColumn( (Column) collectionBinding.getKey().getSelectables().get( 0 ) ); - assertEquals( 1, collectionBinding.getElement().getColumnSpan() ); + assertThat( collectionBinding.getElement().getColumnSpan() ).isEqualTo( 1 ); validateCustomerOrdersElementColumn( (Column) collectionBinding.getElement().getSelectables().get( 0 ) ); } @@ -240,17 +239,30 @@ protected void validateCustomerOrders(Metadata metadata) { protected void validateCustomerIndustries(Metadata metadata) { final Collection collectionBinding = metadata.getCollectionBinding( Customer.class.getName() + ".industries" ); - assertNotNull( collectionBinding ); + assertThat( collectionBinding ).isNotNull(); validateCustomerIndustriesTableName( collectionBinding.getCollectionTable().getQuotedName() ); - assertEquals( 1, collectionBinding.getKey().getColumnSpan() ); + assertThat( collectionBinding.getKey().getColumnSpan() ).isEqualTo( 1 ); validateCustomerIndustriesKeyColumn( (Column) collectionBinding.getKey().getSelectables().get( 0 ) ); - assertEquals( 1, collectionBinding.getElement().getColumnSpan() ); + assertThat( collectionBinding.getElement().getColumnSpan() ).isEqualTo( 1 ); validateCustomerIndustriesElementColumn( (Column) collectionBinding.getElement().getSelectables().get( 0 ) ); } + public static T assertTyping(Class expectedType, Object value) { + if ( !expectedType.isInstance( value ) ) { + fail( + String.format( + "Expecting value of type [%s], but found [%s]", + expectedType.getName(), + value == null ? "" : value + ) + ); + } + return (T) value; + } + protected abstract void validateCustomerIndustriesTableName(String name); protected abstract void validateCustomerIndustriesKeyColumn(Column column); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/namingstrategy/complete/LegacyJpaNamingWithAnnotationBindingTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/namingstrategy/complete/LegacyJpaNamingWithAnnotationBindingTests.java index 2c50f596e0a2..cfdd8e5607d3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/namingstrategy/complete/LegacyJpaNamingWithAnnotationBindingTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/namingstrategy/complete/LegacyJpaNamingWithAnnotationBindingTests.java @@ -4,19 +4,17 @@ */ package org.hibernate.orm.test.namingstrategy.complete; -import java.util.Iterator; - import org.hibernate.boot.model.naming.ImplicitNamingStrategy; import org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl; import org.hibernate.mapping.Column; import org.hibernate.mapping.Component; import org.hibernate.mapping.Selectable; +import java.util.Iterator; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.Matchers.equalTo; -import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; -import static org.junit.Assert.assertEquals; /** * @author Steve Ebersole @@ -29,39 +27,39 @@ protected ImplicitNamingStrategy getImplicitNamingStrategyToUse() { @Override protected void validateCustomerPrimaryTableName(String name) { - assertEquals( "CuStOmEr", name ); + assertThat( name, equalTo( "CuStOmEr" ) ); } @Override protected void validateCustomerPrimaryKeyColumn(Column column) { - assertEquals( "id", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "id" ) ); } @Override protected void validateCustomerVersionColumn(Column column) { - assertEquals( "version", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "version" ) ); } @Override protected void validateCustomerNameColumn(Column column) { - assertEquals( "name", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "name" ) ); } @Override protected void validateCustomerHqAddressComponent(Component component) { - assertEquals( 3, component.getColumnSpan() ); + assertThat( component.getColumnSpan(), equalTo( 3 ) ); Iterator selectables = component.getSelectables().iterator(); int pass = 1; while ( selectables.hasNext() ) { final Column column = assertTyping( Column.class, selectables.next() ); if ( pass == 1 ) { - assertEquals( "line1", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "line1" ) ); } else if ( pass == 2 ) { - assertEquals( "line2", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "line2" ) ); } else if ( pass == 3 ) { - assertEquals( "zipCode_id", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "zipCode_id" ) ); } pass++; } @@ -69,103 +67,103 @@ else if ( pass == 3 ) { @Override protected void validateOrderPrimaryTableName(String name) { - assertThat( name, anyOf( equalTo( "Order"), equalTo( "`Order`") ) ); + assertThat( name, anyOf( equalTo( "Order" ), equalTo( "`Order`" ) ) ); } @Override protected void validateOrderPrimaryKeyColumn(Column column) { - assertEquals( "id", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "id" ) ); } @Override protected void validateOrderReferenceCodeColumn(Column column) { - assertEquals( "referenceCode", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "referenceCode" ) ); } @Override protected void validateOrderFulfilledColumn(Column column) { - assertEquals( "fulfilled", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "fulfilled" ) ); } @Override protected void validateOrderPlacedColumn(Column column) { - assertEquals( "placed", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "placed" ) ); } @Override protected void validateOrderCustomerColumn(Column column) { - assertEquals( "customer_id", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "customer_id" ) ); } @Override protected void validateZipCodePrimaryTableName(String name) { - assertEquals( "ZipCode", name ); + assertThat( name, equalTo( "ZipCode" ) ); } @Override protected void validateZipCodePrimaryKeyColumn(Column column) { - assertEquals( "id", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "id" ) ); } @Override protected void validateZipCodeCodeColumn(Column column) { - assertEquals( "code", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "code" ) ); } @Override protected void validateZipCodeCityColumn(Column column) { - assertEquals( "city", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "city" ) ); } @Override protected void validateZipCodeStateColumn(Column column) { - assertEquals( "state", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "state" ) ); } @Override protected void validateCustomerRegisteredTrademarksTableName(String name) { // CuStOmEr is the Customer entity primary table name (implicitly via jpa entity name) - assertEquals( "CuStOmEr_registeredTrademarks", name ); + assertThat( name, equalTo( "CuStOmEr_registeredTrademarks" ) ); } @Override protected void validateCustomerRegisteredTrademarksKeyColumn(Column column) { // CuStOmEr is the Customer entity primary table name (implicitly via jpa entity name) - assertEquals( "CuStOmEr_id", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "CuStOmEr_id" ) ); } @Override protected void validateCustomerRegisteredTrademarksElementColumn(Column column) { - assertEquals( "registeredTrademarks", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "registeredTrademarks" ) ); } @Override protected void validateCustomerAddressesTableName(String name) { // CuStOmEr is the Customer entity primary table name (implicitly via jpa entity name) - assertEquals( "CuStOmEr_addresses", name ); + assertThat( name, equalTo( "CuStOmEr_addresses" ) ); } @Override protected void validateCustomerAddressesKeyColumn(Column column) { // CuStOmEr is the Customer entity primary table name (implicitly via jpa entity name) - assertEquals( "CuStOmEr_id", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "CuStOmEr_id" ) ); } @Override protected void validateCustomerAddressesElementComponent(Component component) { - assertEquals( 3, component.getColumnSpan() ); + assertThat( component.getColumnSpan(), equalTo( 3 ) ); Iterator selectables = component.getSelectables().iterator(); int pass = 1; while ( selectables.hasNext() ) { final Column column = assertTyping( Column.class, selectables.next() ); if ( pass == 1 ) { - assertEquals( "line1", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "line1" ) ); } else if ( pass == 2 ) { - assertEquals( "line2", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "line2" ) ); } else if ( pass == 3 ) { - assertEquals( "zipCode_id", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "zipCode_id" ) ); } pass++; } @@ -173,32 +171,32 @@ else if ( pass == 3 ) { @Override protected void validateCustomerOrdersTableName(String name) { - assertThat( name, anyOf( equalTo( "Order"), equalTo( "`Order`") ) ); + assertThat( name, anyOf( equalTo( "Order" ), equalTo( "`Order`" ) ) ); } @Override protected void validateCustomerOrdersKeyColumn(Column column) { - assertEquals( "customer_id", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "customer_id" ) ); } @Override protected void validateCustomerOrdersElementColumn(Column column) { - assertEquals( "id", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "id" ) ); } @Override protected void validateCustomerIndustriesTableName(String name) { // CuStOmEr is the Customer entity primary table name (implicitly via jpa entity name) - assertEquals( "CuStOmEr_InDuStRy", name ); + assertThat( name, equalTo( "CuStOmEr_InDuStRy" ) ); } @Override protected void validateCustomerIndustriesKeyColumn(Column column) { - assertEquals( "CuStOmEr_id", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "CuStOmEr_id" ) ); } @Override protected void validateCustomerIndustriesElementColumn(Column column) { - assertEquals( "industries_id", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "industries_id" ) ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/namingstrategy/complete/LegacyJpaNamingWithHbmBindingTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/namingstrategy/complete/LegacyJpaNamingWithHbmBindingTests.java index f9972a9a7e37..f59db1f8e8c3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/namingstrategy/complete/LegacyJpaNamingWithHbmBindingTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/namingstrategy/complete/LegacyJpaNamingWithHbmBindingTests.java @@ -4,21 +4,18 @@ */ package org.hibernate.orm.test.namingstrategy.complete; -import java.util.Iterator; - import org.hibernate.boot.model.naming.ImplicitNamingStrategy; import org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl; import org.hibernate.mapping.Column; import org.hibernate.mapping.Component; import org.hibernate.mapping.Selectable; - import org.hibernate.testing.orm.junit.JiraKey; +import java.util.Iterator; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.Matchers.equalTo; -import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; -import static org.junit.Assert.assertEquals; /** * The default naming strategy is actually always EJB3NamingStrategy historically, @@ -26,7 +23,7 @@ * * @author Steve Ebersole */ -@JiraKey( value = "" ) +@JiraKey(value = "") public class LegacyJpaNamingWithHbmBindingTests extends BaseHbmBindingTests { @Override protected ImplicitNamingStrategy getImplicitNamingStrategyToUse() { @@ -35,39 +32,39 @@ protected ImplicitNamingStrategy getImplicitNamingStrategyToUse() { @Override protected void validateCustomerPrimaryTableName(String name) { - assertEquals( "Customer", name ); + assertThat( name, equalTo( "Customer" ) ); } @Override protected void validateCustomerPrimaryKeyColumn(Column column) { - assertEquals( "id", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "id" ) ); } @Override protected void validateCustomerVersionColumn(Column column) { - assertEquals( "version", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "version" ) ); } @Override protected void validateCustomerNameColumn(Column column) { - assertEquals( "name", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "name" ) ); } @Override protected void validateCustomerHqAddressComponent(Component component) { - assertEquals( 3, component.getColumnSpan() ); + assertThat( component.getColumnSpan(), equalTo( 3 ) ); Iterator selectables = component.getSelectables().iterator(); int pass = 1; while ( selectables.hasNext() ) { final Column column = assertTyping( Column.class, selectables.next() ); if ( pass == 1 ) { - assertEquals( "line1", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "line1" ) ); } else if ( pass == 2 ) { - assertEquals( "line2", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "line2" ) ); } else if ( pass == 3 ) { - assertEquals( "zipCode", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "zipCode" ) ); } pass++; } @@ -75,99 +72,99 @@ else if ( pass == 3 ) { @Override protected void validateOrderPrimaryTableName(String name) { - assertThat( name, anyOf( equalTo( "Order"), equalTo( "`Order`") ) ); + assertThat( name, anyOf( equalTo( "Order" ), equalTo( "`Order`" ) ) ); } @Override protected void validateOrderPrimaryKeyColumn(Column column) { - assertEquals( "id", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "id" ) ); } @Override protected void validateOrderReferenceCodeColumn(Column column) { - assertEquals( "referenceCode", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "referenceCode" ) ); } @Override protected void validateOrderFulfilledColumn(Column column) { - assertEquals( "fulfilled", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "fulfilled" ) ); } @Override protected void validateOrderPlacedColumn(Column column) { - assertEquals( "placed", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "placed" ) ); } @Override protected void validateOrderCustomerColumn(Column column) { - assertEquals( "customer", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "customer" ) ); } @Override protected void validateZipCodePrimaryTableName(String name) { - assertEquals( "ZipCode", name ); + assertThat( name, equalTo( "ZipCode" ) ); } @Override protected void validateZipCodePrimaryKeyColumn(Column column) { - assertEquals( "id", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "id" ) ); } @Override protected void validateZipCodeCodeColumn(Column column) { - assertEquals( "code", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "code" ) ); } @Override protected void validateZipCodeCityColumn(Column column) { - assertEquals( "city", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "city" ) ); } @Override protected void validateZipCodeStateColumn(Column column) { - assertEquals( "state", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "state" ) ); } @Override protected void validateCustomerRegisteredTrademarksTableName(String name) { - assertEquals( "Customer_registeredTrademarks", name ); + assertThat( name, equalTo( "Customer_registeredTrademarks" ) ); } @Override protected void validateCustomerRegisteredTrademarksKeyColumn(Column column) { - assertEquals( "id", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "id" ) ); } @Override protected void validateCustomerRegisteredTrademarksElementColumn(Column column) { - assertEquals( "elt", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "elt" ) ); } @Override protected void validateCustomerAddressesTableName(String name) { - assertEquals( "Customer_addresses", name ); + assertThat( name, equalTo( "Customer_addresses" ) ); } @Override protected void validateCustomerAddressesKeyColumn(Column column) { - assertEquals( "id", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "id" ) ); } @Override protected void validateCustomerAddressesElementComponent(Component component) { - assertEquals( 3, component.getColumnSpan() ); + assertThat( component.getColumnSpan(), equalTo( 3 ) ); Iterator selectables = component.getSelectables().iterator(); int pass = 1; while ( selectables.hasNext() ) { final Column column = assertTyping( Column.class, selectables.next() ); if ( pass == 1 ) { - assertEquals( "line1", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "line1" ) ); } else if ( pass == 2 ) { - assertEquals( "line2", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "line2" ) ); } else if ( pass == 3 ) { - assertEquals( "zipCode", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "zipCode" ) ); } pass++; } @@ -175,31 +172,31 @@ else if ( pass == 3 ) { @Override protected void validateCustomerOrdersTableName(String name) { - assertThat( name, anyOf( equalTo( "Order"), equalTo( "`Order`") ) ); + assertThat( name, anyOf( equalTo( "Order" ), equalTo( "`Order`" ) ) ); } @Override protected void validateCustomerOrdersKeyColumn(Column column) { - assertEquals( "id", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "id" ) ); } @Override protected void validateCustomerOrdersElementColumn(Column column) { - assertEquals( "id", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "id" ) ); } @Override protected void validateCustomerIndustriesTableName(String name) { - assertEquals( "Customer_industries", name ); + assertThat( name, equalTo( "Customer_industries" ) ); } @Override protected void validateCustomerIndustriesKeyColumn(Column column) { - assertEquals( "id", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "id" ) ); } @Override protected void validateCustomerIndustriesElementColumn(Column column) { - assertEquals( "elt", column.getQuotedName() ); + assertThat( column.getQuotedName(), equalTo( "elt" ) ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/nationalized/UseNationalizedCharDataSettingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/nationalized/UseNationalizedCharDataSettingTest.java index 7e7e0ba27ccf..ba4355f1da77 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/nationalized/UseNationalizedCharDataSettingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/nationalized/UseNationalizedCharDataSettingTest.java @@ -4,13 +4,10 @@ */ package org.hibernate.orm.test.nationalized; -import java.sql.Types; - import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.Table; - import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; @@ -20,18 +17,20 @@ import org.hibernate.dialect.NationalizationSupport; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Property; +import org.hibernate.testing.orm.junit.BaseUnitTest; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.util.ServiceRegistryUtil; import org.hibernate.type.BasicType; import org.hibernate.type.descriptor.java.CharacterJavaType; import org.hibernate.type.descriptor.java.StringJavaType; import org.hibernate.type.descriptor.jdbc.spi.JdbcTypeRegistry; - -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.Assertions; +import org.junit.jupiter.api.Test; + +import java.sql.Types; + +import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertSame; /** * Test the use of {@value AvailableSettings#USE_NATIONALIZED_CHARACTER_DATA} @@ -39,7 +38,9 @@ * * @author Steve Ebersole */ -public class UseNationalizedCharDataSettingTest extends BaseUnitTestCase { +@BaseUnitTest +public class UseNationalizedCharDataSettingTest { + @Test @JiraKey(value = "HHH-10528") public void testSetting() { @@ -59,7 +60,7 @@ public void testSetting() { final Property nameAttribute = pc.getProperty( "name" ); final BasicType type = (BasicType) nameAttribute.getType(); final Dialect dialect = metadata.getDatabase().getDialect(); - assertSame( StringJavaType.INSTANCE, type.getJavaTypeDescriptor() ); + assertThat( type.getJavaTypeDescriptor() ).isSameAs( StringJavaType.INSTANCE ); if ( dialect.getNationalizationSupport() != NationalizationSupport.EXPLICIT ) { Assertions.assertSame( jdbcTypeRegistry.getDescriptor( Types.VARCHAR ), type.getJdbcType() ); } @@ -92,7 +93,7 @@ public void testSettingOnCharType() { final Property nameAttribute = pc.getProperty( "flag" ); final BasicType type = (BasicType) nameAttribute.getType(); final Dialect dialect = metadata.getDatabase().getDialect(); - assertSame( CharacterJavaType.INSTANCE, type.getJavaTypeDescriptor() ); + assertThat( type.getJavaTypeDescriptor() ).isSameAs( CharacterJavaType.INSTANCE ); if ( dialect.getNationalizationSupport() != NationalizationSupport.EXPLICIT ) { Assertions.assertSame( jdbcTypeRegistry.getDescriptor( Types.CHAR ), type.getJdbcType() ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/notfound/IsNullAndNotFoundTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/notfound/IsNullAndNotFoundTest.java index a7c8cbf2b6e6..d3f2766fc2db 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/notfound/IsNullAndNotFoundTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/notfound/IsNullAndNotFoundTest.java @@ -4,49 +4,44 @@ */ package org.hibernate.orm.test.notfound; -import java.util.List; - +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToOne; +import jakarta.persistence.Table; import org.hibernate.annotations.NotFound; import org.hibernate.annotations.NotFoundAction; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.AvailableSettings; - import org.hibernate.community.dialect.AltibaseDialect; import org.hibernate.testing.jdbc.SQLStatementInspector; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.Jira; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.testing.orm.junit.SkipForDialect; -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 jakarta.persistence.Entity; -import jakarta.persistence.FetchType; -import jakarta.persistence.Id; -import jakarta.persistence.OneToOne; -import jakarta.persistence.Table; +import java.util.List; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -public class IsNullAndNotFoundTest extends BaseNonConfigCoreFunctionalTestCase { - private final SQLStatementInspector inspector = new SQLStatementInspector(); - - @Override - protected void configureStandardServiceRegistryBuilder(StandardServiceRegistryBuilder ssrb) { - super.configureStandardServiceRegistryBuilder( ssrb ); - ssrb.applySetting( AvailableSettings.STATEMENT_INSPECTOR, inspector ); - } +@DomainModel( + annotatedClasses = { + IsNullAndNotFoundTest.Account.class, + IsNullAndNotFoundTest.Person.class + } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Account.class, Person.class }; - } +) +@SessionFactory( + statementInspectorClass = SQLStatementInspector.class +) +public class IsNullAndNotFoundTest { - @Before - public void setUp() { - inTransaction( + @BeforeEach + public void setUp(SessionFactoryScope scope) { + scope.inTransaction( session -> { Account account1 = new Account( 1, null, null ); Account account2 = new Account( 2, "Fab", null ); @@ -64,30 +59,26 @@ public void setUp() { ); } - @After - public void tearDown() { - inTransaction( - session -> { - session.createMutationQuery( "delete from Person" ).executeUpdate(); - session.createMutationQuery( "delete from Account" ).executeUpdate(); - } - ); + @AfterEach + public void tearDown(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Test - public void testAssociationDereferenceIsNullInWhereClause() { - inTransaction( + public void testAssociationDereferenceIsNullInWhereClause(SessionFactoryScope scope) { + SQLStatementInspector inspector = scope.getStatementInspector( SQLStatementInspector.class ); + scope.inTransaction( session -> { inspector.clear(); // should produce an inner join to ACCOUNT_TABLE final List ids = session.createQuery( - "select p.id from Person p where p.account.code is null", Integer.class ) + "select p.id from Person p where p.account.code is null", Integer.class ) .getResultList(); - assertEquals( 1, ids.size() ); - assertEquals( 1, (int) ids.get( 0 ) ); + assertThat( ids ).hasSize( 1 ); + assertThat( ids.get( 0 ) ).isEqualTo( 1 ); assertThat( inspector.getSqlQueries() ).hasSize( 1 ); assertThat( inspector.getSqlQueries().get( 0 ) ).containsIgnoringCase( " join " ); @@ -98,8 +89,10 @@ public void testAssociationDereferenceIsNullInWhereClause() { } @Test - public void testAssociationIsNullInWhereClause() { - inTransaction( + public void testAssociationIsNullInWhereClause(SessionFactoryScope scope) { + SQLStatementInspector inspector = scope.getStatementInspector( SQLStatementInspector.class ); + + scope.inTransaction( session -> { inspector.clear(); @@ -112,11 +105,11 @@ public void testAssociationIsNullInWhereClause() { // where a.id is null final List ids = session.createQuery( - "select distinct p.id from Person p where p.account is null", Integer.class ) + "select distinct p.id from Person p where p.account is null", Integer.class ) .getResultList(); - assertEquals( 1, ids.size() ); - assertEquals( 3, (int) ids.get( 0 ) ); + assertThat( ids ).hasSize( 1 ); + assertThat( ids.get( 0 ) ).isEqualTo( 3 ); assertThat( inspector.getSqlQueries() ).hasSize( 1 ); assertThat( inspector.getSqlQueries().get( 0 ) ).containsIgnoringCase( " left join " ); @@ -126,8 +119,10 @@ public void testAssociationIsNullInWhereClause() { } @Test - public void testFetchedAssociationIsNullInWhereClause() { - inTransaction( + public void testFetchedAssociationIsNullInWhereClause(SessionFactoryScope scope) { + SQLStatementInspector inspector = scope.getStatementInspector( SQLStatementInspector.class ); + + scope.inTransaction( session -> { inspector.clear(); @@ -153,17 +148,19 @@ public void testFetchedAssociationIsNullInWhereClause() { } @Test - public void testIsNullInWhereClause3() { - inTransaction( + public void testIsNullInWhereClause3(SessionFactoryScope scope) { + SQLStatementInspector inspector = scope.getStatementInspector( SQLStatementInspector.class ); + + scope.inTransaction( session -> { inspector.clear(); final List ids = session.createQuery( - "select distinct p.id from Person p where fk(p.account) is null", Integer.class ) + "select distinct p.id from Person p where fk(p.account) is null", Integer.class ) .getResultList(); - assertEquals( 1, ids.size() ); - assertEquals( 3, (int) ids.get( 0 ) ); + assertThat( ids ).hasSize( 1 ); + assertThat( ids.get( 0 ) ).isEqualTo( 3 ); assertThat( inspector.getSqlQueries() ).hasSize( 1 ); assertThat( inspector.getSqlQueries().get( 0 ) ).doesNotContainIgnoringCase( " join " ); @@ -173,8 +170,10 @@ public void testIsNullInWhereClause3() { } @Test - public void testAssociationEqualsInWhereClause() { - inTransaction( + public void testAssociationEqualsInWhereClause(SessionFactoryScope scope) { + SQLStatementInspector inspector = scope.getStatementInspector( SQLStatementInspector.class ); + + scope.inTransaction( session -> { inspector.clear(); @@ -191,12 +190,12 @@ public void testAssociationEqualsInWhereClause() { // a1_0.id=? final List ids = session.createQuery( - "select distinct p.id from Person p where p.account = :acct", Integer.class ) + "select distinct p.id from Person p where p.account = :acct", Integer.class ) .setParameter( "acct", new Account( 1, null, null ) ) .getResultList(); assertThat( ids ).hasSize( 1 ); - assertThat( ids.get(0) ).isEqualTo( 1 ); + assertThat( ids.get( 0 ) ).isEqualTo( 1 ); assertThat( inspector.getSqlQueries() ).hasSize( 1 ); assertThat( inspector.getSqlQueries().get( 0 ) ).containsIgnoringCase( " join " ); @@ -206,43 +205,44 @@ public void testAssociationEqualsInWhereClause() { } @Test - public void testIsNullInWhereClause5() { - inTransaction( + public void testIsNullInWhereClause5(SessionFactoryScope scope) { + scope.inTransaction( session -> { final List ids = session.createQuery( - "select p.id from Person p where p.account.code is null or p.account.id is null", Integer.class ) + "select p.id from Person p where p.account.code is null or p.account.id is null", + Integer.class ) .getResultList(); - assertEquals( 1, ids.size() ); - assertEquals( 1, (int) ids.get( 0 ) ); - + assertThat( ids ).hasSize( 1 ); + assertThat( ids.get( 0 ) ).isEqualTo( 1 ); } ); } @Test - public void testWhereClause() { - inTransaction( + public void testWhereClause(SessionFactoryScope scope) { + scope.inTransaction( session -> { final List ids = session.createQuery( - "select p.id from Person p where p.account.code = :code and p.account.id = :id", Integer.class ) + "select p.id from Person p where p.account.code = :code and p.account.id = :id", + Integer.class ) .setParameter( "code", "Fab" ) .setParameter( "id", 2 ) .getResultList(); - assertEquals( 1, ids.size() ); - assertEquals( 2, (int) ids.get( 0 ) ); - + assertThat( ids ).hasSize( 1 ); + assertThat( ids.get( 0 ) ).isEqualTo( 2 ); } ); } @Test - public void testDelete() { + public void testDelete(SessionFactoryScope scope) { + SQLStatementInspector inspector = scope.getStatementInspector( SQLStatementInspector.class ); inspector.clear(); - inTransaction( (entityManager) -> { - entityManager.createQuery( "delete from Person p where p.account is null" ).executeUpdate(); + scope.inTransaction( (entityManager) -> { + entityManager.createMutationQuery( "delete from Person p where p.account is null" ).executeUpdate(); assertThat( inspector.getSqlQueries() ).hasSize( 1 ); // could physically be a join or exists sub-query @@ -252,13 +252,16 @@ public void testDelete() { } @Test - @Jira( "https://hibernate.atlassian.net/browse/HHH-17384" ) + @Jira("https://hibernate.atlassian.net/browse/HHH-17384") @SkipForDialect(dialectClass = AltibaseDialect.class, reason = "left join cannot be used inside exists clause") - public void testDeleteAdditionalPredicate() { + public void testDeleteAdditionalPredicate(SessionFactoryScope scope) { + SQLStatementInspector inspector = scope.getStatementInspector( SQLStatementInspector.class ); inspector.clear(); - inTransaction( (entityManager) -> { - entityManager.createQuery( "delete from Person p where p.account is null and p.lazyAccount.code <>'aaa'" ).executeUpdate(); + scope.inTransaction( (entityManager) -> { + entityManager.createMutationQuery( + "delete from Person p where p.account is null and p.lazyAccount.code <>'aaa'" ) + .executeUpdate(); assertThat( inspector.getSqlQueries() ).hasSize( 1 ); // could physically be a join or exists sub-query @@ -268,11 +271,13 @@ public void testDeleteAdditionalPredicate() { } @Test - public void testHqlUpdate() { + public void testHqlUpdate(SessionFactoryScope scope) { + SQLStatementInspector inspector = scope.getStatementInspector( SQLStatementInspector.class ); inspector.clear(); - inTransaction( (entityManager) -> { - entityManager.createQuery( "update Person p set p.name = 'abc' where p.account is null" ).executeUpdate(); + scope.inTransaction( (entityManager) -> { + entityManager.createMutationQuery( "update Person p set p.name = 'abc' where p.account is null" ) + .executeUpdate(); assertThat( inspector.getSqlQueries() ).hasSize( 1 ); // could physically be a join or exists sub-query @@ -282,14 +287,15 @@ public void testHqlUpdate() { } @Test - public void testHqlUpdateSet() { + public void testHqlUpdateSet(SessionFactoryScope scope) { + SQLStatementInspector inspector = scope.getStatementInspector( SQLStatementInspector.class ); inspector.clear(); - inTransaction( (entityManager) -> { - entityManager.createQuery( "update Person p set p.account = null" ).executeUpdate(); + scope.inTransaction( (entityManager) -> { + entityManager.createMutationQuery( "update Person p set p.account = null" ).executeUpdate(); assertThat( inspector.getSqlQueries() ).hasSize( 1 ); - assertThat( inspector.getSqlQueries().get(0) ).doesNotContainIgnoringCase( " join " ); + assertThat( inspector.getSqlQueries().get( 0 ) ).doesNotContainIgnoringCase( " join " ); assertThat( inspector.getSqlQueries().get( 0 ) ).containsIgnoringCase( "account_id=null" ); } ); } @@ -332,7 +338,7 @@ public Account getAccount() { } } - @SuppressWarnings({ "FieldCanBeLocal", "unused" }) + @SuppressWarnings({"FieldCanBeLocal", "unused"}) @Entity(name = "Account") @Table(name = "ACCOUNT_TABLE") public static class Account { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/ops/multiload/MultiLoadEntityGraphTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/ops/multiload/MultiLoadEntityGraphTest.java index 9633a9f7efbb..f46937e12cd0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/ops/multiload/MultiLoadEntityGraphTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/ops/multiload/MultiLoadEntityGraphTest.java @@ -4,8 +4,6 @@ */ package org.hibernate.orm.test.ops.multiload; -import java.util.ArrayList; -import java.util.List; import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; @@ -14,131 +12,139 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.NamedEntityGraph; import jakarta.persistence.OneToMany; - import org.hibernate.Hibernate; -import org.hibernate.Session; import org.hibernate.graph.GraphSemantic; import org.hibernate.graph.RootGraph; +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 org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Before; -import org.junit.Test; +import java.util.ArrayList; +import java.util.List; import static jakarta.persistence.GenerationType.AUTO; -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.assertTrue; - -public class MultiLoadEntityGraphTest extends BaseNonConfigCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Parent.class, Child.class, Pet.class }; - } +import static org.assertj.core.api.Assertions.assertThat; - @Before - public void before() { - sessionFactory().getSchemaManager().truncate(); - Session session = sessionFactory().openSession(); - session.getTransaction().begin(); - for ( int i = 0; i < 5; i++ ) { - Parent p = new Parent( i, "Entity #" + i ); - for ( int j = 0; j < 5; j++ ) { - Child child = new Child(); - child.setParent( p ); - p.getChildren().add( child ); - } - for ( int j = 0; j < 5; j++ ) { - Pet pet = new Pet(); - pet.setMaster( p ); - p.getPets().add( pet ); - } - session.persist( p ); +@DomainModel( + annotatedClasses = { + MultiLoadEntityGraphTest.Parent.class, + MultiLoadEntityGraphTest.Child.class, + MultiLoadEntityGraphTest.Pet.class } - session.getTransaction().commit(); - session.close(); +) +@SessionFactory +public class MultiLoadEntityGraphTest { + + @BeforeEach + public void before(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + for ( int i = 0; i < 5; i++ ) { + Parent p = new Parent( i, "Entity #" + i ); + for ( int j = 0; j < 5; j++ ) { + Child child = new Child(); + child.setParent( p ); + p.getChildren().add( child ); + } + for ( int j = 0; j < 5; j++ ) { + Pet pet = new Pet(); + pet.setMaster( p ); + p.getPets().add( pet ); + } + session.persist( p ); + } + } + ); + } + + @AfterEach + public void cleanUp(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncate(); } @Test - public void testFetchGraph() { - doInHibernate( this::sessionFactory, session -> { + public void testFetchGraph(SessionFactoryScope scope) { + scope.inTransaction( session -> { List list = session.byMultipleIds( Parent.class ).multiLoad( 1, 2, 3 ); - assertEquals( 3, list.size() ); + assertThat( list ).hasSize( 3 ); // Collections should be loaded according to their defaults for ( Parent p : list ) { - assertFalse( Hibernate.isInitialized( p.children ) ); - assertTrue( Hibernate.isInitialized( p.pets ) ); + assertThat( Hibernate.isInitialized( p.children ) ).isFalse(); + assertThat( Hibernate.isInitialized( p.pets ) ).isTrue(); } } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { List list = session.byMultipleIds( Parent.class ) .with( (RootGraph) session.getEntityGraph( "eager" ), GraphSemantic.FETCH ) .multiLoad( 1, 2, 3 ); - assertEquals( 3, list.size() ); + assertThat( list ).hasSize( 3 ); // Collections should be loaded eagerly if mentioned in the graph, or lazily otherwise. // Since the graph contains all collections, all collections should be loaded eagerly. for ( Parent p : list ) { - assertTrue( Hibernate.isInitialized( p.children ) ); - assertTrue( Hibernate.isInitialized( p.pets ) ); + assertThat( Hibernate.isInitialized( p.children ) ).isTrue(); + assertThat( Hibernate.isInitialized( p.pets ) ).isTrue(); } } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { List list = session.byMultipleIds( Parent.class ) .with( (RootGraph) session.getEntityGraph( "lazy" ), GraphSemantic.FETCH ) .multiLoad( 1, 2, 3 ); - assertEquals( 3, list.size() ); + assertThat( list ).hasSize( 3 ); // Collections should be loaded eagerly if mentioned in the graph, or lazily otherwise. // Since the graph is empty, all collections should be loaded lazily. for ( Parent p : list ) { - assertFalse( Hibernate.isInitialized( p.children ) ); - assertFalse( Hibernate.isInitialized( p.pets ) ); + assertThat( Hibernate.isInitialized( p.children ) ).isFalse(); + assertThat( Hibernate.isInitialized( p.pets ) ).isFalse(); } } ); } @Test - public void testLoadGraph() { - doInHibernate( this::sessionFactory, session -> { + public void testLoadGraph(SessionFactoryScope scope) { + scope.inTransaction( session -> { List list = session.byMultipleIds( Parent.class ).multiLoad( 1, 2, 3 ); - assertEquals( 3, list.size() ); + assertThat( list ).hasSize( 3 ); // Collections should be loaded according to their defaults for ( Parent p : list ) { - assertFalse( Hibernate.isInitialized( p.children ) ); - assertTrue( Hibernate.isInitialized( p.pets ) ); + assertThat( Hibernate.isInitialized( p.children ) ).isFalse(); + assertThat( Hibernate.isInitialized( p.pets ) ).isTrue(); } } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { List list = session.byMultipleIds( Parent.class ) .with( (RootGraph) session.getEntityGraph( "eager" ), GraphSemantic.LOAD ) .multiLoad( 1, 2, 3 ); - assertEquals( 3, list.size() ); + assertThat( list ).hasSize( 3 ); // Collections should be loaded eagerly if mentioned in the graph, or according to their default otherwise. // Since the graph contains all collections, all collections should be loaded eagerly. for ( Parent p : list ) { - assertTrue( Hibernate.isInitialized( p.children ) ); - assertTrue( Hibernate.isInitialized( p.pets ) ); + assertThat( Hibernate.isInitialized( p.children ) ).isTrue(); + assertThat( Hibernate.isInitialized( p.pets ) ).isTrue(); } } ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { List list = session.byMultipleIds( Parent.class ) .with( (RootGraph) session.getEntityGraph( "lazy" ), GraphSemantic.LOAD ) .multiLoad( 1, 2, 3 ); - assertEquals( 3, list.size() ); + assertThat( list ).hasSize( 3 ); // Collections should be loaded eagerly if mentioned in the graph, or according to their default otherwise. // Since the graph is empty, all collections should be loaded according to their default. for ( Parent p : list ) { - assertFalse( Hibernate.isInitialized( p.children ) ); - assertTrue( Hibernate.isInitialized( p.pets ) ); + assertThat( Hibernate.isInitialized( p.children ) ).isFalse(); + assertThat( Hibernate.isInitialized( p.pets ) ).isTrue(); } } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/ops/replicate/ReplicateTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/ops/replicate/ReplicateTest.java index 86d6cce130af..0111898af1f4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/ops/replicate/ReplicateTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/ops/replicate/ReplicateTest.java @@ -8,19 +8,18 @@ import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; - import org.hibernate.ReplicationMode; import org.hibernate.Session; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -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.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.FailureExpected; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; /** * Test trying to replicate HHH-11514 @@ -28,32 +27,31 @@ * @author Vlad Mihalcea */ @JiraKey(value = "HHH-11514") -@RequiresDialectFeature(DialectChecks.SupportsIdentityColumns.class) -@FailureExpected( jiraKey = "HHH-11514" ) -public class ReplicateTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - City.class, - }; - } +@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsIdentityColumns.class) +@FailureExpected(jiraKey = "HHH-11514") +@Jpa( + annotatedClasses = { + ReplicateTest.City.class + } +) +public class ReplicateTest { @Test - public void refreshTest() { - doInJPA( this::entityManagerFactory, entityManager -> { + public void refreshTest(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { City city = new City(); city.setId( 100L ); city.setName( "Cluj-Napoca" ); - entityManager.unwrap(Session.class).replicate( city, ReplicationMode.OVERWRITE ); + entityManager.unwrap( Session.class ).replicate( city, ReplicationMode.OVERWRITE ); } ); - doInJPA( this::entityManagerFactory, entityManager -> { - City city = entityManager.find( City.class, 100L); - assertEquals("Cluj-Napoca", city.getName()); + + scope.inTransaction( entityManager -> { + City city = entityManager.find( City.class, 100L ); + assertThat( city.getName() ).isEqualTo( "Cluj-Napoca" ); } ); } - @Entity(name = "City" ) + @Entity(name = "City") public static class City { @Id diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/pagination/DistinctSelectTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/pagination/DistinctSelectTest.java index 0f535c2108cc..a68ed3bef6cc 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/pagination/DistinctSelectTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/pagination/DistinctSelectTest.java @@ -4,20 +4,19 @@ */ package org.hibernate.orm.test.pagination; -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; - -import org.hibernate.Session; -import org.hibernate.Transaction; import org.hibernate.dialect.SQLServerDialect; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.testing.util.uuid.SafeRandomUUIDGenerator; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import java.util.ArrayList; +import java.util.List; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; /** * HHH-5715 bug test case: Duplicated entries when using select distinct with join and pagination. The bug has to do @@ -25,54 +24,51 @@ * * @author Valotasios Yoryos */ -@JiraKey( value = "HHH-5715" ) -public class DistinctSelectTest extends BaseCoreFunctionalTestCase { +@JiraKey(value = "HHH-5715") +@DomainModel( + xmlMappings = "org/hibernate/orm/test/pagination/EntryTag.hbm.xml" +) +@SessionFactory +public class DistinctSelectTest { private static final int NUM_OF_USERS = 30; - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } - - @Override - public String[] getMappings() { - return new String[] { "pagination/EntryTag.hbm.xml" }; + @BeforeAll + public void setUp(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + List tags = new ArrayList<>(); + + for ( int i = 0; i < 5; i++ ) { + Tag tag = new Tag( "Tag: " + SafeRandomUUIDGenerator.safeRandomUUID() ); + tags.add( tag ); + session.persist( tag ); + } + + for ( int i = 0; i < NUM_OF_USERS; i++ ) { + Entry e = new Entry( "Entry: " + SafeRandomUUIDGenerator.safeRandomUUID() ); + e.getTags().addAll( tags ); + session.persist( e ); + } + } + ); } - public void feedDatabase() { - List tags = new ArrayList(); - - Session s = openSession(); - Transaction t = s.beginTransaction(); - - for (int i = 0; i < 5; i++) { - Tag tag = new Tag("Tag: " + SafeRandomUUIDGenerator.safeRandomUUID()); - tags.add(tag); - s.persist(tag); - } - - for (int i = 0; i < NUM_OF_USERS; i++) { - Entry e = new Entry("Entry: " + SafeRandomUUIDGenerator.safeRandomUUID()); - e.getTags().addAll(tags); - s.persist(e); - } - t.commit(); - s.close(); - } - - @SuppressWarnings( {"unchecked"}) @Test - public void testDistinctSelectWithJoin() { - feedDatabase(); - - Session s = openSession(); - - List entries = s.createQuery("select distinct e from Entry e join e.tags t where t.surrogate is not null order by e.name").setFirstResult(10).setMaxResults(5).list(); - - // System.out.println(entries); - Entry firstEntry = entries.remove(0); - assertFalse("The list of entries should not contain dublicated Entry objects as we've done a distinct select", entries.contains(firstEntry)); - - s.close(); + public void testDistinctSelectWithJoin(SessionFactoryScope scope) { + scope.inSession( + session -> { + List entries = session.createQuery( + "select distinct e from Entry e join e.tags t where t.surrogate is not null order by e.name", + Entry.class ) + .setFirstResult( 10 ).setMaxResults( 5 ).list(); + + // System.out.println(entries); + Entry firstEntry = entries.remove( 0 ); + assertThat( entries ) + .describedAs( + "The list of entries should not contain duplicated Entry objects as we've done a distinct select" ) + .doesNotContain( firstEntry ); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/pagination/hhh9965/HHH9965Test.java b/hibernate-core/src/test/java/org/hibernate/orm/test/pagination/hhh9965/HHH9965Test.java index abe07bdd2b89..e69754d58379 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/pagination/hhh9965/HHH9965Test.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/pagination/hhh9965/HHH9965Test.java @@ -4,14 +4,18 @@ */ package org.hibernate.orm.test.pagination.hhh9965; -import org.hibernate.Session; -import org.hibernate.cfg.Configuration; +import org.hibernate.HibernateException; 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.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; /** * Created on 17/12/17. @@ -19,39 +23,27 @@ * @author Reda.Housni-Alaoui */ @JiraKey(value = "HHH-9965") -public class HHH9965Test extends BaseCoreFunctionalTestCase { - - @Test - public void testHHH9965() { - Session session = openSession(); - session.beginTransaction(); - - String hql = "SELECT s FROM Shop s join fetch s.products"; - - try{ - session.createQuery(hql) - .setMaxResults(3) - .list(); - fail("Pagination over collection fetch failure was expected"); - } catch (Exception e){ - log.info(e.getMessage()); - } - - session.getTransaction().commit(); - session.close(); - } - - @Override - protected void configure(Configuration cfg) { - super.configure(cfg); - cfg.setProperty( Environment.FAIL_ON_PAGINATION_OVER_COLLECTION_FETCH, true ); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ +@DomainModel( + annotatedClasses = { Shop.class, Product.class - }; + } +) +@ServiceRegistry( + settings = @Setting(name = Environment.FAIL_ON_PAGINATION_OVER_COLLECTION_FETCH, value = "true") +) +@SessionFactory +public class HHH9965Test { + + @Test + public void testHHH9965(SessionFactoryScope scope) { + assertThrows( HibernateException.class, () -> scope.inTransaction( + session -> { + session.createSelectionQuery( "SELECT s FROM Shop s join fetch s.products", Shop.class ) + .setMaxResults( 3 ) + .list(); + fail( "Pagination over collection fetch failure was expected" ); + } ) + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/BytecodeEnhancementTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/BytecodeEnhancementTest.java index 081cc056d423..6326a200f263 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/BytecodeEnhancementTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/BytecodeEnhancementTest.java @@ -4,10 +4,6 @@ */ package org.hibernate.orm.test.pc; -import java.sql.Blob; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; import jakarta.persistence.Basic; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; @@ -15,32 +11,33 @@ import jakarta.persistence.Lob; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; - import org.hibernate.annotations.LazyGroup; import org.hibernate.annotations.NaturalId; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import java.sql.Blob; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; /** * @author Vlad Mihalcea */ -public class BytecodeEnhancementTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Book.class, - Customer.class - }; - } +@Jpa( + annotatedClasses = { + BytecodeEnhancementTest.Person.class, + BytecodeEnhancementTest.Book.class, + BytecodeEnhancementTest.Customer.class + } +) +public class BytecodeEnhancementTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::BytecodeEnhancement-dirty-tracking-bidirectional-incorrect-usage-example[] Person person = new Person(); person.setName("John Doe"); @@ -55,7 +52,7 @@ public void test() { } //end::BytecodeEnhancement-dirty-tracking-bidirectional-incorrect-usage-example[] }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::BytecodeEnhancement-dirty-tracking-bidirectional-correct-usage-example[] Person person = new Person(); person.setName("John Doe"); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeDetachTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeDetachTest.java index c058187660eb..4e0cd588605d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeDetachTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeDetachTest.java @@ -4,60 +4,56 @@ */ package org.hibernate.orm.test.pc; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Fábio Takeo Ueno */ -public class CascadeDetachTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { +@Jpa( + annotatedClasses = { Person.class, Phone.class - }; - } + } +) +public class CascadeDetachTest { @Test - public void detachTest() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void detachTest(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(); - person.setId(1L); - person.setName("John Doe"); + person.setId( 1L ); + person.setName( "John Doe" ); Phone phone = new Phone(); - phone.setId(1L); - phone.setNumber("123-456-7890"); + phone.setId( 1L ); + phone.setNumber( "123-456-7890" ); - person.addPhone(phone); - entityManager.persist(person); + person.addPhone( phone ); + entityManager.persist( person ); - }); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::pc-cascade-detach-example[] - Person person = entityManager.find(Person.class, 1L); - assertEquals(1, person.getPhones().size()); - Phone phone = person.getPhones().get(0); + Person person = entityManager.find( Person.class, 1L ); + assertThat( person.getPhones() ).hasSize( 1 ); + Phone phone = person.getPhones().get( 0 ); - assertTrue(entityManager.contains(person)); - assertTrue(entityManager.contains(phone)); + assertThat( entityManager.contains( person ) ).isTrue(); + assertThat( entityManager.contains( phone ) ).isTrue(); - entityManager.detach(person); + entityManager.detach( person ); - assertFalse(entityManager.contains(person)); - assertFalse(entityManager.contains(phone)); + assertThat( entityManager.contains( person ) ).isFalse(); + assertThat( entityManager.contains( phone ) ).isFalse(); //end::pc-cascade-detach-example[] - }); + } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeMergeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeMergeTest.java index 5ac9be4c7672..9d1dcb0a37b2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeMergeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeMergeTest.java @@ -4,55 +4,50 @@ */ package org.hibernate.orm.test.pc; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Fábio Takeo Ueno */ -public class CascadeMergeTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { +@Jpa( + annotatedClasses = { Person.class, Phone.class - }; - } + } +) +public class CascadeMergeTest { @Test - public void mergeTest() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void mergeTest(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(); - person.setId(1L); - person.setName("John Doe"); + person.setId( 1L ); + person.setName( "John Doe" ); Phone phone = new Phone(); - phone.setId(1L); - phone.setNumber("123-456-7890"); - - person.addPhone(phone); + phone.setId( 1L ); + phone.setNumber( "123-456-7890" ); - entityManager.persist(person); + person.addPhone( phone ); - }); + entityManager.persist( person ); - doInJPA(this::entityManagerFactory, entityManager -> { + } ); + scope.inTransaction( entityManager -> { //tag::pc-cascade-merge-example[] - Phone phone = entityManager.find(Phone.class, 1L); + Phone phone = entityManager.find( Phone.class, 1L ); Person person = phone.getOwner(); - person.setName("John Doe Jr."); - phone.setNumber("987-654-3210"); + person.setName( "John Doe Jr." ); + phone.setNumber( "987-654-3210" ); entityManager.clear(); - entityManager.merge(person); + entityManager.merge( person ); //end::pc-cascade-merge-example[] - }); + } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeOnDeleteCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeOnDeleteCollectionTest.java index 9e63b5895b7b..1fdc420ddbef 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeOnDeleteCollectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeOnDeleteCollectionTest.java @@ -4,8 +4,6 @@ */ package org.hibernate.orm.test.pc; -import java.util.ArrayList; -import java.util.List; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -13,56 +11,53 @@ import jakarta.persistence.Id; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; - import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import java.util.ArrayList; +import java.util.List; /** * @author Vlad Mihalcea */ -public class CascadeOnDeleteCollectionTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class - }; - } +@Jpa( + annotatedClasses = { + CascadeOnDeleteCollectionTest.Person.class, + CascadeOnDeleteCollectionTest.Phone.class + } +) +public class CascadeOnDeleteCollectionTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(); - person.setId(1L); - person.setName("John Doe"); - entityManager.persist(person); + person.setId( 1L ); + person.setName( "John Doe" ); + entityManager.persist( person ); Phone phone1 = new Phone(); - phone1.setId(1L); - phone1.setNumber("123-456-7890"); - phone1.setOwner(person); - person.addPhone(phone1); + phone1.setId( 1L ); + phone1.setNumber( "123-456-7890" ); + phone1.setOwner( person ); + person.addPhone( phone1 ); Phone phone2 = new Phone(); - phone2.setId(2L); - phone2.setNumber("101-010-1234"); - phone2.setOwner(person); - person.addPhone(phone2); - }); + phone2.setId( 2L ); + phone2.setNumber( "101-010-1234" ); + phone2.setOwner( person ); + person.addPhone( phone2 ); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::pc-cascade-on-delete-collection-example[] - Person person = entityManager.find(Person.class, 1L); - entityManager.remove(person); + Person person = entityManager.find( Person.class, 1L ); + entityManager.remove( person ); //end::pc-cascade-on-delete-collection-example[] - }); - + } ); } //tag::pc-cascade-on-delete-collection-mapping-Person-example[] @@ -99,8 +94,8 @@ public void setName(String name) { } public void addPhone(Phone phone) { - phone.setOwner(this); - phones.add(phone); + phone.setOwner( this ); + phones.add( phone ); } //tag::pc-cascade-on-delete-collection-mapping-Person-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeOnDeleteTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeOnDeleteTest.java index 982f7336088c..f49a2389ab5f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeOnDeleteTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeOnDeleteTest.java @@ -8,53 +8,49 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.ManyToOne; - import org.hibernate.annotations.OnDelete; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DialectFeatureChecks; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.junit.jupiter.api.Test; import static jakarta.persistence.FetchType.LAZY; import static org.hibernate.annotations.OnDeleteAction.CASCADE; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; /** * @author Vlad Mihalcea */ -@RequiresDialectFeature(DialectChecks.SupportsCascadeDeleteCheck.class) -public class CascadeOnDeleteTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class - }; - } +@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsCascadeDeleteCheck.class) +@Jpa( + annotatedClasses = { + CascadeOnDeleteTest.Person.class, + CascadeOnDeleteTest.Phone.class + } +) +public class CascadeOnDeleteTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(); - person.setId(1L); - person.setName("John Doe"); - entityManager.persist(person); + person.setId( 1L ); + person.setName( "John Doe" ); + entityManager.persist( person ); Phone phone = new Phone(); - phone.setId(1L); - phone.setNumber("123-456-7890"); - phone.setOwner(person); - entityManager.persist(phone); - }); + phone.setId( 1L ); + phone.setNumber( "123-456-7890" ); + phone.setOwner( person ); + entityManager.persist( phone ); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::pc-cascade-on-delete-example[] - Person person = entityManager.find(Person.class, 1L); - entityManager.remove(person); + Person person = entityManager.find( Person.class, 1L ); + entityManager.remove( person ); //end::pc-cascade-on-delete-example[] - }); + } ); } //tag::pc-cascade-on-delete-mapping-Person-example[] @@ -68,7 +64,7 @@ public static class Person { //Getters and setters are omitted for brevity - //end::pc-cascade-on-delete-mapping-Person-example[] + //end::pc-cascade-on-delete-mapping-Person-example[] public Long getId() { return id; @@ -85,7 +81,7 @@ public String getName() { public void setName(String name) { this.name = name; } - //tag::pc-cascade-on-delete-mapping-Person-example[] + //tag::pc-cascade-on-delete-mapping-Person-example[] } //end::pc-cascade-on-delete-mapping-Person-example[] @@ -105,7 +101,7 @@ public static class Phone { //Getters and setters are omitted for brevity - //end::pc-cascade-on-delete-mapping-Phone-example[] + //end::pc-cascade-on-delete-mapping-Phone-example[] public Long getId() { return id; @@ -130,7 +126,7 @@ public Person getOwner() { public void setOwner(Person owner) { this.owner = owner; } - //tag::pc-cascade-on-delete-mapping-Phone-example[] + //tag::pc-cascade-on-delete-mapping-Phone-example[] } //end::pc-cascade-on-delete-mapping-Phone-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadePersistTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadePersistTest.java index ba94d3292c68..1a53c3b9c914 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadePersistTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadePersistTest.java @@ -4,28 +4,25 @@ */ package org.hibernate.orm.test.pc; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Fábio Takeo Ueno */ -public class CascadePersistTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class - }; - } +@Jpa( + annotatedClasses = { + Person.class, + Phone.class + } +) +public class CascadePersistTest { @Test - public void persistTest() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void persistTest(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::pc-cascade-persist-example[] Person person = new Person(); person.setId(1L); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeRefreshTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeRefreshTest.java index ba1965e5a408..80589fceeea9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeRefreshTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeRefreshTest.java @@ -4,55 +4,53 @@ */ package org.hibernate.orm.test.pc; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Fábio Takeo Ueno */ -public class CascadeRefreshTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class - }; - } +@Jpa( + annotatedClasses = { + Person.class, + Phone.class + } +) +public class CascadeRefreshTest { @Test - public void refreshTest() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void refreshTest(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(); - person.setId(1L); - person.setName("John Doe"); + person.setId( 1L ); + person.setName( "John Doe" ); Phone phone = new Phone(); - phone.setId(1L); - phone.setNumber("123-456-7890"); + phone.setId( 1L ); + phone.setNumber( "123-456-7890" ); - person.addPhone(phone); - entityManager.persist(person); - }); + person.addPhone( phone ); + entityManager.persist( person ); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::pc-cascade-refresh-example[] - Person person = entityManager.find(Person.class, 1L); - Phone phone = person.getPhones().get(0); + Person person = entityManager.find( Person.class, 1L ); + Phone phone = person.getPhones().get( 0 ); - person.setName("John Doe Jr."); - phone.setNumber("987-654-3210"); + person.setName( "John Doe Jr." ); + phone.setNumber( "987-654-3210" ); - entityManager.refresh(person); + entityManager.refresh( person ); - assertEquals("John Doe", person.getName()); - assertEquals("123-456-7890", phone.getNumber()); + assertThat( person.getName() ).isEqualTo( "John Doe" ); + assertThat( phone.getNumber() ).isEqualTo( "123-456-7890" ); //end::pc-cascade-refresh-example[] - }); + } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeRemoveTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeRemoveTest.java index 73de2f17842c..2caec8fb9b6b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeRemoveTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeRemoveTest.java @@ -4,46 +4,42 @@ */ package org.hibernate.orm.test.pc; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Fábio Takeo Ueno */ -public class CascadeRemoveTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { +@Jpa( + annotatedClasses = { Person.class, Phone.class - }; - } + } +) +public class CascadeRemoveTest { @Test - public void removeTest() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void removeTest(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(); - person.setId(1L); - person.setName("John Doe"); + person.setId( 1L ); + person.setName( "John Doe" ); Phone phone = new Phone(); - phone.setId(1L); - phone.setNumber("123-456-7890"); + phone.setId( 1L ); + phone.setNumber( "123-456-7890" ); - person.addPhone(phone); - entityManager.persist(person); - }); + person.addPhone( phone ); + entityManager.persist( person ); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::pc-cascade-remove-example[] - Person person = entityManager.find(Person.class, 1L); + Person person = entityManager.find( Person.class, 1L ); - entityManager.remove(person); + entityManager.remove( person ); //end::pc-cascade-remove-example[] - }); + } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeReplicateTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeReplicateTest.java index 43c9f017e056..b79248c026c5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeReplicateTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeReplicateTest.java @@ -6,54 +6,50 @@ import org.hibernate.ReplicationMode; import org.hibernate.Session; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Fábio Takeo Ueno */ -public class CascadeReplicateTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class - }; - } +@Jpa( + annotatedClasses = { + Person.class, + Phone.class + } +) +public class CascadeReplicateTest { @Test - public void refreshTest() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void refreshTest(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(); - person.setId(1L); - person.setName("John Doe"); + person.setId( 1L ); + person.setName( "John Doe" ); Phone phone = new Phone(); - phone.setId(1L); - phone.setNumber("123-456-7890"); + phone.setId( 1L ); + phone.setNumber( "123-456-7890" ); - person.addPhone(phone); - entityManager.persist(person); - }); + person.addPhone( phone ); + entityManager.persist( person ); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::pc-cascade-replicate-example[] Person person = new Person(); - person.setId(1L); - person.setName("John Doe Sr."); + person.setId( 1L ); + person.setName( "John Doe Sr." ); Phone phone = new Phone(); - phone.setId(1L); - phone.setNumber("(01) 123-456-7890"); - person.addPhone(phone); + phone.setId( 1L ); + phone.setNumber( "(01) 123-456-7890" ); + person.addPhone( phone ); - entityManager.unwrap(Session.class).replicate(person, ReplicationMode.OVERWRITE); + entityManager.unwrap( Session.class ).replicate( person, ReplicationMode.OVERWRITE ); //end::pc-cascade-replicate-example[] - }); + } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/DynamicUpdateTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/DynamicUpdateTest.java index 32447dceca1a..4c26746ca708 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/DynamicUpdateTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/DynamicUpdateTest.java @@ -7,45 +7,40 @@ import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; - import org.hibernate.annotations.DynamicUpdate; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class DynamicUpdateTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class, - }; - } +@Jpa( + annotatedClasses = { + DynamicUpdateTest.Product.class + } +) +public class DynamicUpdateTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Product book = new Product(); - book.setId(1L); - book.setName("High-Performance Java Persistence"); - book.setDescription("get the most out of your persistence layer"); - book.setPriceCents(29_99); - book.setQuantity(10_000); + book.setId( 1L ); + book.setName( "High-Performance Java Persistence" ); + book.setDescription( "get the most out of your persistence layer" ); + book.setPriceCents( 29_99 ); + book.setQuantity( 10_000 ); - entityManager.persist(book); - }); + entityManager.persist( book ); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { - Product book = entityManager.find(Product.class, 1L); - book.setPriceCents(24_99); - }); + Product book = entityManager.find( Product.class, 1L ); + book.setPriceCents( 24_99 ); + } ); } //tag::pc-managed-state-dynamic-update-mapping-example[] @@ -70,7 +65,7 @@ public static class Product { //Getters and setters are omitted for brevity - //end::pc-managed-state-dynamic-update-mapping-example[] + //end::pc-managed-state-dynamic-update-mapping-example[] public Long getId() { return id; @@ -111,7 +106,7 @@ public Integer getQuantity() { public void setQuantity(Integer quantity) { this.quantity = quantity; } - //tag::pc-managed-state-dynamic-update-mapping-example[] + //tag::pc-managed-state-dynamic-update-mapping-example[] } //end::pc-managed-state-dynamic-update-mapping-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/FilterJoinTableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/FilterJoinTableTest.java index 5de446f3a2ba..b2deb78a2e70 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/FilterJoinTableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/FilterJoinTableTest.java @@ -19,29 +19,26 @@ import org.hibernate.annotations.FilterDef; import org.hibernate.annotations.FilterJoinTable; import org.hibernate.annotations.ParamDef; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Vlad Mihalcea */ -public class FilterJoinTableTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Client.class, - Account.class - }; - } +@Jpa( + annotatedClasses = { + FilterJoinTableTest.Client.class, + FilterJoinTableTest.Account.class + } +) +public class FilterJoinTableTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::pc-filter-join-table-persistence-example[] Client client = new Client() .setId(1L) @@ -75,17 +72,15 @@ public void testLifecycle() { //end::pc-filter-join-table-persistence-example[] }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::pc-no-filter-join-table-collection-query-example[] Client client = entityManager.find(Client.class, 1L); - assertEquals(3, client.getAccounts().size()); + assertThat(client.getAccounts()).hasSize( 3 ); //end::pc-no-filter-join-table-collection-query-example[] }); - doInJPA(this::entityManagerFactory, entityManager -> { - log.infof("Activate filter [%s]", "firstAccounts"); - + scope.inTransaction( entityManager -> { //tag::pc-filter-join-table-collection-query-example[] Client client = entityManager.find(Client.class, 1L); @@ -94,7 +89,7 @@ public void testLifecycle() { .enableFilter("firstAccounts") .setParameter("maxOrderId", 1); - assertEquals(2, client.getAccounts().size()); + assertThat(client.getAccounts()).hasSize( 2 ); //end::pc-filter-join-table-collection-query-example[] }); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/FilterSqlFragementAliasTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/FilterSqlFragmentAliasTest.java similarity index 51% rename from hibernate-core/src/test/java/org/hibernate/orm/test/pc/FilterSqlFragementAliasTest.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/pc/FilterSqlFragmentAliasTest.java index a02cb6c54b1a..5b02f9eb9c83 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/FilterSqlFragementAliasTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/FilterSqlFragmentAliasTest.java @@ -4,13 +4,11 @@ */ package org.hibernate.orm.test.pc; -import java.util.List; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.SecondaryTable; import jakarta.persistence.Table; - import org.hibernate.Session; import org.hibernate.annotations.Comment; import org.hibernate.annotations.Filter; @@ -19,95 +17,93 @@ import org.hibernate.annotations.SQLDelete; import org.hibernate.annotations.SqlFragmentAlias; import org.hibernate.dialect.H2Dialect; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.RequiresDialect; -import org.junit.Test; +import java.util.List; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Vlad Mihalcea */ @RequiresDialect(H2Dialect.class) -public class FilterSqlFragementAliasTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Account.class - }; - } +@Jpa( + annotatedClasses = { + FilterSqlFragmentAliasTest.Account.class + } +) +public class FilterSqlFragmentAliasTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Account account1 = new Account(); - account1.setId(1L); - account1.setAmount(5000d); - account1.setRate(1.25 / 100); - account1.setActive(true); - entityManager.persist(account1); + account1.setId( 1L ); + account1.setAmount( 5000d ); + account1.setRate( 1.25 / 100 ); + account1.setActive( true ); + entityManager.persist( account1 ); Account account2 = new Account(); - account2.setId(2L); - account2.setAmount(0d); - account2.setRate(1.05 / 100); - account2.setActive(false); - entityManager.persist(account2); + account2.setId( 2L ); + account2.setAmount( 0d ); + account2.setRate( 1.05 / 100 ); + account2.setActive( false ); + entityManager.persist( account2 ); Account account3 = new Account(); - account3.setId(3L); - account3.setAmount(250d); - account3.setRate(1.05 / 100); - account3.setActive(true); - entityManager.persist(account3); - }); + account3.setId( 3L ); + account3.setAmount( 250d ); + account3.setRate( 1.05 / 100 ); + account3.setActive( true ); + entityManager.persist( account3 ); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { - log.infof("Activate filter [%s]", "activeAccount"); + scope.inTransaction( entityManager -> { //tag::pc-filter-sql-fragment-alias-query-example[] entityManager - .unwrap(Session.class) - .enableFilter("activeAccount") - .setParameter("active", true); + .unwrap( Session.class ) + .enableFilter( "activeAccount" ) + .setParameter( "active", true ); List accounts = entityManager.createQuery( - "select a from Account a", Account.class) - .getResultList(); + "select a from Account a", Account.class ) + .getResultList(); //end::pc-filter-sql-fragment-alias-query-example[] - assertEquals(2, accounts.size()); - }); + assertThat( accounts ).hasSize( 2 ); + } ); } //tag::pc-filter-sql-fragment-alias-example[] @Entity(name = "Account") @Table(name = "account") - @Comment(on="account", value = "The account table") + @Comment(on = "account", value = "The account table") @SecondaryTable( - name = "account_details" + name = "account_details" ) - @Comment(on="account_details", value = "The account details secondary table") + @Comment(on = "account_details", value = "The account details secondary table") @SQLDelete( - sql = "UPDATE account_details SET deleted = true WHERE id = ? " + sql = "UPDATE account_details SET deleted = true WHERE id = ? " ) @FilterDef( - name="activeAccount", - parameters = @ParamDef( - name="active", - type=Boolean.class - ) + name = "activeAccount", + parameters = @ParamDef( + name = "active", + type = Boolean.class + ) ) @Filter( - name="activeAccount", - condition="{a}.active = :active and {ad}.deleted = false", - aliases = { - @SqlFragmentAlias(alias = "a", table= "account"), - @SqlFragmentAlias(alias = "ad", table= "account_details"), - } + name = "activeAccount", + condition = "{a}.active = :active and {ad}.deleted = false", + aliases = { + @SqlFragmentAlias(alias = "a", table = "account"), + @SqlFragmentAlias(alias = "ad", table = "account_details"), + } ) public static class Account { @@ -125,7 +121,7 @@ public static class Account { //Getters and setters omitted for brevity - //end::pc-filter-sql-fragment-alias-example[] + //end::pc-filter-sql-fragment-alias-example[] public Long getId() { return id; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/FilterTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/FilterTest.java index fd9ffd42dedf..fc0fbaa2c270 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/FilterTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/FilterTest.java @@ -4,11 +4,6 @@ */ package org.hibernate.orm.test.pc; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.function.Supplier; - import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -22,10 +17,10 @@ import jakarta.persistence.NoResultException; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; - import org.hibernate.EntityFilterException; import org.hibernate.Hibernate; import org.hibernate.Session; +import org.hibernate.SessionFactory; import org.hibernate.annotations.Filter; import org.hibernate.annotations.FilterDef; import org.hibernate.annotations.NotFound; @@ -33,279 +28,267 @@ import org.hibernate.annotations.ParamDef; import org.hibernate.jpa.AvailableHints; import org.hibernate.metamodel.CollectionClassification; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; 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.Jpa; +import org.hibernate.testing.orm.junit.SettingProvider; +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 java.util.Map; +import java.util.function.Supplier; + +import static org.assertj.core.api.Assertions.assertThat; import static org.hibernate.cfg.AvailableSettings.DEFAULT_LIST_SEMANTICS; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -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.assertThrows; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * @author Vlad Mihalcea */ -public class FilterTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Client.class, - Account.class, - AccountEager.class, - AccountNotFound.class, - AccountNotFoundException.class - }; - } +@Jpa( + annotatedClasses = { + FilterTest.Client.class, + FilterTest.Account.class, + FilterTest.AccountEager.class, + FilterTest.AccountNotFound.class, + FilterTest.AccountNotFoundException.class + }, + settingProviders = @SettingProvider( + settingName = DEFAULT_LIST_SEMANTICS, + provider = FilterTest.CollectionClassificationProvider.class + ) +) +public class FilterTest { - @Override - protected void addConfigOptions(Map options) { - super.addConfigOptions( options ); - options.put( DEFAULT_LIST_SEMANTICS, CollectionClassification.BAG.name() ); + public static class CollectionClassificationProvider implements SettingProvider.Provider { + @Override + public CollectionClassification getSetting() { + return CollectionClassification.BAG; + } } - @Before - public void setup() { - doInJPA(this::entityManagerFactory, entityManager -> { + @BeforeEach + public void setup(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::pc-filter-persistence-example[] Client client = new Client() - .setId(1L) - .setName("John Doe") - .setType(AccountType.DEBIT); + .setId( 1L ) + .setName( "John Doe" ) + .setType( AccountType.DEBIT ); Account account1; client.addAccount( account1 = new Account() - .setId(1L) - .setType(AccountType.CREDIT) - .setAmount(5000d) - .setRate(1.25 / 100) - .setActive(true) + .setId( 1L ) + .setType( AccountType.CREDIT ) + .setAmount( 5000d ) + .setRate( 1.25 / 100 ) + .setActive( true ) ); client.addAccount( new Account() - .setId(2L) - .setType(AccountType.DEBIT) - .setAmount(0d) - .setRate(1.05 / 100) - .setActive(false) + .setId( 2L ) + .setType( AccountType.DEBIT ) + .setAmount( 0d ) + .setRate( 1.05 / 100 ) + .setActive( false ) .setParentAccount( account1 ) ); client.addAccount( new Account() - .setType(AccountType.DEBIT) - .setId(3L) - .setAmount(250d) - .setRate(1.05 / 100) - .setActive(true) + .setType( AccountType.DEBIT ) + .setId( 3L ) + .setAmount( 250d ) + .setRate( 1.05 / 100 ) + .setActive( true ) ); - entityManager.persist(client); + entityManager.persist( client ); //end::pc-filter-persistence-example[] entityManager.persist( new AccountEager() - .setId(2L) + .setId( 2L ) .setParentAccount( account1 ) ); entityManager.persist( new AccountNotFound() - .setId(2L) + .setId( 2L ) .setParentAccount( account1 ) ); entityManager.persist( new AccountNotFoundException() - .setId(2L) + .setId( 2L ) .setParentAccount( account1 ) ); - }); + } ); } - @After - public void tearDown() { - doInJPA(this::entityManagerFactory, entityManager -> { - entityManager.createQuery( "update Account set parentAccount = null" ).executeUpdate(); - entityManager.createQuery( "delete from AccountEager" ).executeUpdate(); - entityManager.createQuery( "delete from AccountNotFound" ).executeUpdate(); - entityManager.createQuery( "delete from AccountNotFoundException" ).executeUpdate(); - entityManager.createQuery( "delete from Account" ).executeUpdate(); - entityManager.createQuery( "delete from Client" ).executeUpdate(); - }); + @AfterEach + public void tearDown(EntityManagerFactoryScope scope) { + scope.getEntityManagerFactory().unwrap( SessionFactory.class ).getSchemaManager().truncateMappedObjects(); } @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { - log.infof("Activate filter [%s]", "activeAccount"); + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { entityManager - .unwrap(Session.class) - .enableFilter("activeAccount") - .setParameter("active", true); - - Account account1 = entityManager.find(Account.class, 1L); - Account account2 = entityManager.find(Account.class, 2L); + .unwrap( Session.class ) + .enableFilter( "activeAccount" ) + .setParameter( "active", true ); - assertNotNull(account1); - assertNotNull(account2); - }); + Account account1 = entityManager.find( Account.class, 1L ); + Account account2 = entityManager.find( Account.class, 2L ); - doInJPA(this::entityManagerFactory, entityManager -> { - log.infof("Activate filter [%s]", "activeAccount"); + assertThat(account1 ).isNotNull(); + assertThat(account2 ).isNotNull(); + } ); + scope.inTransaction( entityManager -> { entityManager - .unwrap(Session.class) - .enableFilter("activeAccount") - .setParameter("active", true); + .unwrap( Session.class ) + .enableFilter( "activeAccount" ) + .setParameter( "active", true ); Account account1 = entityManager.createQuery( - "select a from Account a where a.id = :id", Account.class) - .setParameter("id", 1L) + "select a from Account a where a.id = :id", Account.class ) + .setParameter( "id", 1L ) .getSingleResult(); - assertNotNull(account1); + assertThat(account1 ).isNotNull(); try { Account account2 = entityManager.createQuery( - "select a from Account a where a.id = :id", Account.class) - .setParameter("id", 2L) + "select a from Account a where a.id = :id", Account.class ) + .setParameter( "id", 2L ) .getSingleResult(); } catch (NoResultException expected) { } - }); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { - log.infof("Activate filter [%s]", "activeAccount"); + scope.inTransaction( entityManager -> { //tag::pc-filter-entity-example[] entityManager - .unwrap(Session.class) - .enableFilter("activeAccount") - .setParameter("active", true); + .unwrap( Session.class ) + .enableFilter( "activeAccount" ) + .setParameter( "active", true ); - Account account = entityManager.find(Account.class, 2L); + Account account = entityManager.find( Account.class, 2L ); - assertFalse( account.isActive() ); + assertThat( account.isActive() ).isFalse(); //end::pc-filter-entity-example[] - }); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::pc-no-filter-entity-query-example[] List accounts = entityManager.createQuery( - "select a from Account a", Account.class) - .getResultList(); + "select a from Account a", Account.class ) + .getResultList(); - assertEquals(3, accounts.size()); + assertThat( accounts ).hasSize( 3 ); //end::pc-no-filter-entity-query-example[] - }); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { - log.infof("Activate filter [%s]", "activeAccount"); + scope.inTransaction( entityManager -> { //tag::pc-filter-entity-query-example[] entityManager - .unwrap(Session.class) - .enableFilter("activeAccount") - .setParameter("active", true); + .unwrap( Session.class ) + .enableFilter( "activeAccount" ) + .setParameter( "active", true ); List accounts = entityManager.createQuery( - "select a from Account a", Account.class) - .getResultList(); + "select a from Account a", Account.class ) + .getResultList(); - assertEquals(2, accounts.size()); + assertThat( accounts ).hasSize( 2 ); //end::pc-filter-entity-query-example[] - }); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::pc-no-filter-collection-query-example[] - Client client = entityManager.find(Client.class, 1L); + Client client = entityManager.find( Client.class, 1L ); - assertEquals(3, client.getAccounts().size()); + assertThat( client.getAccounts()).hasSize( 3 ); //end::pc-no-filter-collection-query-example[] - }); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { - log.infof("Activate filter [%s]", "activeAccount"); + scope.inTransaction( entityManager -> { //tag::pc-filter-collection-query-example[] entityManager - .unwrap(Session.class) - .enableFilter("activeAccount") - .setParameter("active", true); + .unwrap( Session.class ) + .enableFilter( "activeAccount" ) + .setParameter( "active", true ); - Client client = entityManager.find(Client.class, 1L); + Client client = entityManager.find( Client.class, 1L ); - assertEquals(2, client.getAccounts().size()); + assertThat( client.getAccounts()).hasSize( 2 ); //end::pc-filter-collection-query-example[] - }); + } ); } @Test @JiraKey("HHH-16830") - public void testApplyToLoadByKey() { - doInJPA(this::entityManagerFactory, entityManager -> { - log.infof("Activate filter [%s]", "minimumAmount"); + public void testApplyToLoadByKey(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::pc-filter-entity-example[] entityManager - .unwrap(Session.class) - .enableFilter("minimumAmount") - .setParameter("amount", 9000d); + .unwrap( Session.class ) + .enableFilter( "minimumAmount" ) + .setParameter( "amount", 9000d ); - Account account = entityManager.find(Account.class, 1L); + Account account = entityManager.find( Account.class, 1L ); - assertNull( account ); + assertThat(account ).isNull(); //end::pc-filter-entity-example[] - }); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { - log.infof("Activate filter [%s]", "minimumAmount"); + scope.inTransaction( entityManager -> { //tag::pc-filter-entity-example[] entityManager - .unwrap(Session.class) - .enableFilter("minimumAmount") - .setParameter("amount", 100d); + .unwrap( Session.class ) + .enableFilter( "minimumAmount" ) + .setParameter( "amount", 100d ); - Account account = entityManager.find(Account.class, 1L); + Account account = entityManager.find( Account.class, 1L ); - assertNotNull( account ); + assertThat(account ).isNotNull(); //end::pc-filter-entity-example[] - }); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { - log.infof("Activate filter [%s]", "minimumAmount"); + scope.inTransaction( entityManager -> { //tag::pc-filter-entity-query-example[] entityManager - .unwrap(Session.class) - .enableFilter("minimumAmount") - .setParameter("amount", 500d); + .unwrap( Session.class ) + .enableFilter( "minimumAmount" ) + .setParameter( "amount", 500d ); List accounts = entityManager.createQuery( - "select a from Account a", Account.class) + "select a from Account a", Account.class ) .getResultList(); - assertEquals(1, accounts.size()); + assertThat( accounts ).hasSize( 1 ); //end::pc-filter-entity-query-example[] - }); + } ); } @Test @JiraKey("HHH-16830") - public void testApplyToLoadByKeyAssociationFiltering() { - doInJPA( this::entityManagerFactory, entityManager -> { + public void testApplyToLoadByKeyAssociationFiltering(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Account account = entityManager.find( Account.class, 2L ); - assertNotNull( account.getParentAccount() ); + assertThat(account.getParentAccount() ).isNotNull(); } ); } @Test @JiraKey("HHH-16830") - public void testApplyToLoadByKeyAssociationFilteringLazyInitialization() { - doInJPA( this::entityManagerFactory, entityManager -> { + public void testApplyToLoadByKeyAssociationFilteringLazyInitialization(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { entityManager.unwrap( Session.class ) .enableFilter( "accountType" ) .setParameter( "type", "DEBIT" ); @@ -316,14 +299,14 @@ public void testApplyToLoadByKeyAssociationFilteringLazyInitialization() { () -> Hibernate.initialize( account.getParentAccount() ) ); // Account with id 1 does not exist - assertTrue( exception.getMessage().endsWith( "'1']" ) ); + assertThat( exception.getMessage() ).endsWith( "'1']" ); } ); } @Test @JiraKey("HHH-16830") - public void testApplyToLoadByKeyAssociationFilteringAccountLoadGraphInitializer() { - doInJPA( this::entityManagerFactory, entityManager -> { + public void testApplyToLoadByKeyAssociationFilteringAccountLoadGraphInitializer(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { entityManager.unwrap( Session.class ) .enableFilter( "accountType" ) .setParameter( "type", "DEBIT" ); @@ -339,15 +322,15 @@ public void testApplyToLoadByKeyAssociationFilteringAccountLoadGraphInitializer( ) ); // Account with id 1 does not exist - assertTrue( exception.getRole().endsWith( "parentAccount" ) ); - assertEquals( 1L, exception.getIdentifier() ); + assertThat( exception.getRole() ).endsWith( "parentAccount" ); + assertThat( exception.getIdentifier() ).isEqualTo( 1L ); } ); } @Test @JiraKey("HHH-16830") - public void testApplyToLoadByKeyAssociationFilteringAccountJoinInitializer() { - doInJPA( this::entityManagerFactory, entityManager -> { + public void testApplyToLoadByKeyAssociationFilteringAccountJoinInitializer(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { entityManager.unwrap( Session.class ) .enableFilter( "accountType" ) .setParameter( "type", "DEBIT" ); @@ -360,15 +343,15 @@ public void testApplyToLoadByKeyAssociationFilteringAccountJoinInitializer() { ).getResultList() ); // Account with id 1 does not exist - assertTrue( exception.getRole().contains( "parentAccount" ) ); - assertEquals( 1L, exception.getIdentifier() ); + assertThat( exception.getRole() ).contains( "parentAccount" ); + assertThat( exception.getIdentifier() ).isEqualTo( 1L ); } ); } @Test @JiraKey("HHH-16830") - public void testApplyToLoadByKeyAssociationFilteringAccountSelectInitializer() { - doInJPA( this::entityManagerFactory, entityManager -> { + public void testApplyToLoadByKeyAssociationFilteringAccountSelectInitializer(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { entityManager.unwrap( Session.class ) .enableFilter( "accountType" ) .setParameter( "type", "DEBIT" ); @@ -381,18 +364,18 @@ public void testApplyToLoadByKeyAssociationFilteringAccountSelectInitializer() { ).getResultList() ); // Account with id 1 does not exist - assertTrue( exception.getRole().contains( "parentAccount" ) ); - assertEquals( 1L, exception.getIdentifier() ); + assertThat( exception.getRole() ).contains( "parentAccount" ); + assertThat( exception.getIdentifier() ).isEqualTo( 1L ); } ); } @Test @JiraKey("HHH-16830") - public void testApplyToLoadByKeyAssociationFilteringAccountNotFoundException() { - doInJPA(this::entityManagerFactory, entityManager -> { - entityManager.unwrap(Session.class) - .enableFilter("accountType") - .setParameter("type", "DEBIT"); + public void testApplyToLoadByKeyAssociationFilteringAccountNotFoundException(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + entityManager.unwrap( Session.class ) + .enableFilter( "accountType" ) + .setParameter( "type", "DEBIT" ); EntityFilterException exception = assertThrows( EntityFilterException.class, @@ -402,13 +385,13 @@ public void testApplyToLoadByKeyAssociationFilteringAccountNotFoundException() { ).getSingleResult() ); // Account with id 1 does not exist - assertTrue( exception.getRole().contains( "parentAccount" ) ); - assertEquals( 1L, exception.getIdentifier() ); - }); - doInJPA(this::entityManagerFactory, entityManager -> { - entityManager.unwrap(Session.class) - .enableFilter("accountType") - .setParameter("type", "DEBIT"); + assertThat( exception.getRole() ).contains( "parentAccount" ); + assertThat( exception.getIdentifier() ).isEqualTo( 1L ); + } ); + scope.inTransaction( entityManager -> { + entityManager.unwrap( Session.class ) + .enableFilter( "accountType" ) + .setParameter( "type", "DEBIT" ); EntityFilterException exception = assertThrows( EntityFilterException.class, @@ -418,38 +401,38 @@ public void testApplyToLoadByKeyAssociationFilteringAccountNotFoundException() { ).getSingleResult() ); // Account with id 1 does not exist - assertTrue( exception.getRole().contains( "parentAccount" ) ); - assertEquals( 1L, exception.getIdentifier() ); - }); + assertThat( exception.getRole() ).contains( "parentAccount" ); + assertThat( exception.getIdentifier() ).isEqualTo( 1L ); + } ); } @Test @JiraKey("HHH-16830") - public void testApplyToLoadByKeyAssociationFilteringAccountNotFoundIgnore() { - doInJPA(this::entityManagerFactory, entityManager -> { - entityManager.unwrap(Session.class) - .enableFilter("accountType") - .setParameter("type", "DEBIT"); + public void testApplyToLoadByKeyAssociationFilteringAccountNotFoundIgnore(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + entityManager.unwrap( Session.class ) + .enableFilter( "accountType" ) + .setParameter( "type", "DEBIT" ); AccountNotFound account = entityManager.createQuery( "select a from AccountNotFound a where a.id = 2", AccountNotFound.class ).getSingleResult(); // No exception, since we use NotFoundAction.IGNORE - assertNull( account.getParentAccount() ); - }); - doInJPA(this::entityManagerFactory, entityManager -> { - entityManager.unwrap(Session.class) - .enableFilter("accountType") - .setParameter("type", "DEBIT"); + assertThat(account.getParentAccount() ).isNull(); + } ); + scope.inTransaction( entityManager -> { + entityManager.unwrap( Session.class ) + .enableFilter( "accountType" ) + .setParameter( "type", "DEBIT" ); AccountNotFound account = entityManager.createQuery( "select a from AccountNotFound a left join fetch a.parentAccount where a.id = 2", AccountNotFound.class ).getSingleResult(); // No exception, since we use NotFoundAction.IGNORE - assertNull( account.getParentAccount() ); - }); + assertThat(account.getParentAccount() ).isNull(); + } ); } public enum AccountType { @@ -470,17 +453,17 @@ public static class Client { private AccountType type; @OneToMany( - mappedBy = "client", - cascade = CascadeType.ALL - ) + mappedBy = "client", + cascade = CascadeType.ALL + ) @Filter( - name="activeAccount", - condition="active_status = :active" - ) + name = "activeAccount", + condition = "active_status = :active" + ) private List accounts = new ArrayList<>(); //Getters and setters omitted for brevity - //end::pc-filter-Client-example[] + //end::pc-filter-Client-example[] public Long getId() { return id; } @@ -511,11 +494,11 @@ public Client setType(AccountType type) { public List getAccounts() { return accounts; } - //tag::pc-filter-Client-example[] + //tag::pc-filter-Client-example[] public void addAccount(Account account) { - account.setClient(this); - this.accounts.add(account); + account.setClient( this ); + this.accounts.add( account ); } } //end::pc-filter-Client-example[] @@ -524,39 +507,39 @@ public void addAccount(Account account) { @Entity(name = "Account") @Table(name = "account") @FilterDef( - name="activeAccount", - parameters = @ParamDef( - name="active", - type=Boolean.class + name = "activeAccount", + parameters = @ParamDef( + name = "active", + type = Boolean.class + ) ) -) @Filter( - name="activeAccount", - condition="active_status = :active" + name = "activeAccount", + condition = "active_status = :active" ) @FilterDef( - name="minimumAmount", + name = "minimumAmount", parameters = @ParamDef( - name="amount", - type=Double.class + name = "amount", + type = Double.class ), applyToLoadByKey = true ) @Filter( - name="minimumAmount", - condition="amount > :amount" + name = "minimumAmount", + condition = "amount > :amount" ) @FilterDef( - name="accountType", + name = "accountType", parameters = @ParamDef( - name="type", - type=String.class + name = "type", + type = String.class ), applyToLoadByKey = true ) @Filter( - name="accountType", - condition="account_type = :type" + name = "accountType", + condition = "account_type = :type" ) public static class Account { @@ -579,7 +562,7 @@ public static class Account { private boolean active; //Getters and setters omitted for brevity - //end::pc-filter-Account-example[] + //end::pc-filter-Account-example[] @ManyToOne(fetch = FetchType.LAZY) private Account parentAccount; @@ -646,7 +629,7 @@ public Account setParentAccount(Account parentAccount) { this.parentAccount = parentAccount; return this; } - //tag::pc-filter-Account-example[] + //tag::pc-filter-Account-example[] } //end::pc-filter-Account-example[] @@ -655,24 +638,24 @@ public Account setParentAccount(Account parentAccount) { @Table(name = "autofilteredaccount") //tag::pc-filter-auto-enabled-Account-example[] @FilterDef( - name="activeAccount", + name = "activeAccount", parameters = @ParamDef( - name="active", - type=Boolean.class + name = "active", + type = Boolean.class ), autoEnabled = true ) //end::pc-filter-auto-enabled-Account-example[] @Filter( - name="activeAccount", - condition="active_status = :active" + name = "activeAccount", + condition = "active_status = :active" ) //tag::pc-filter-resolver-Account-example[] @FilterDef( - name="activeAccountWithResolver", + name = "activeAccountWithResolver", parameters = @ParamDef( - name="active", - type=Boolean.class, + name = "active", + type = Boolean.class, resolver = AccountIsActiveResolver.class ), autoEnabled = true diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/NoDynamicUpdateTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/NoDynamicUpdateTest.java index 07e3b278acf9..b6239e68da02 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/NoDynamicUpdateTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/NoDynamicUpdateTest.java @@ -7,47 +7,43 @@ import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; /** * @author Vlad Mihalcea */ -public class NoDynamicUpdateTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class, - }; - } +@Jpa( + annotatedClasses = { + NoDynamicUpdateTest.Product.class + } +) +public class NoDynamicUpdateTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::pc-managed-state-update-persist-example[] Product book = new Product(); - book.setId(1L); - book.setName("High-Performance Java Persistence"); - book.setDescription("Get the most out of your persistence layer"); - book.setPriceCents(29_99); - book.setQuantity(10_000); + book.setId( 1L ); + book.setName( "High-Performance Java Persistence" ); + book.setDescription( "Get the most out of your persistence layer" ); + book.setPriceCents( 29_99 ); + book.setQuantity( 10_000 ); - entityManager.persist(book); + entityManager.persist( book ); //end::pc-managed-state-update-persist-example[] - }); + } ); //tag::pc-managed-state-update-example[] - doInJPA(this::entityManagerFactory, entityManager -> { - Product book = entityManager.find(Product.class, 1L); - book.setPriceCents(24_99); - }); + scope.inTransaction( entityManager -> { + Product book = entityManager.find( Product.class, 1L ); + book.setPriceCents( 24_99 ); + } ); //end::pc-managed-state-update-example[] } @@ -72,7 +68,7 @@ public static class Product { //Getters and setters are omitted for brevity - //end::pc-managed-state-update-mapping-example[] + //end::pc-managed-state-update-mapping-example[] public Long getId() { return id; @@ -113,7 +109,7 @@ public Integer getQuantity() { public void setQuantity(Integer quantity) { this.quantity = quantity; } - //tag::pc-managed-state-update-mapping-example[] + //tag::pc-managed-state-update-mapping-example[] } //end::pc-managed-state-update-mapping-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/PersistenceContextTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/PersistenceContextTest.java index 120f5360ecb3..30c1dd3855cc 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/PersistenceContextTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/PersistenceContextTest.java @@ -4,11 +4,6 @@ */ package org.hibernate.orm.test.pc; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; import jakarta.persistence.EntityNotFoundException; @@ -18,317 +13,322 @@ import jakarta.persistence.Persistence; import jakarta.persistence.PersistenceUnitUtil; import jakarta.persistence.PersistenceUtil; - import org.hibernate.Hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.annotations.NaturalId; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.metamodel.CollectionClassification; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.SettingProvider; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import static org.assertj.core.api.Assertions.assertThat; import static org.hibernate.cfg.AvailableSettings.DEFAULT_LIST_SEMANTICS; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; /** * @author Vlad Mihalcea */ -public class PersistenceContextTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Book.class, - }; - } - - @Override - protected void addConfigOptions(Map options) { - super.addConfigOptions( options ); - options.put( DEFAULT_LIST_SEMANTICS, CollectionClassification.BAG.name() ); +@Jpa( + annotatedClasses = { + PersistenceContextTest.Person.class, + PersistenceContextTest.Book.class, + }, + settingProviders = @SettingProvider( + settingName = DEFAULT_LIST_SEMANTICS, + provider = PersistenceContextTest.CollectionClassificationProvider.class + ) +) +public class PersistenceContextTest { + + public static class CollectionClassificationProvider implements SettingProvider.Provider { + @Override + public CollectionClassification getSetting() { + return CollectionClassification.BAG; + } } @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::pc-unwrap-example[] - Session session = entityManager.unwrap(Session.class); - SessionImplementor sessionImplementor = entityManager.unwrap(SessionImplementor.class); + Session session = entityManager.unwrap( Session.class ); + SessionImplementor sessionImplementor = entityManager.unwrap( SessionImplementor.class ); - SessionFactory sessionFactory = entityManager.getEntityManagerFactory().unwrap(SessionFactory.class); + SessionFactory sessionFactory = entityManager.getEntityManagerFactory().unwrap( SessionFactory.class ); //end::pc-unwrap-example[] - }); - Long _personId = doInJPA(this::entityManagerFactory, entityManager -> { - entityManager.createQuery("delete from Book").executeUpdate(); - entityManager.createQuery("delete from Person").executeUpdate(); + } ); + Long _personId = scope.fromTransaction( entityManager -> { + entityManager.createQuery( "delete from Book" ).executeUpdate(); + entityManager.createQuery( "delete from Person" ).executeUpdate(); //tag::pc-persist-jpa-example[] Person person = new Person(); - person.setId(1L); - person.setName("John Doe"); + person.setId( 1L ); + person.setName( "John Doe" ); - entityManager.persist(person); + entityManager.persist( person ); //end::pc-persist-jpa-example[] //tag::pc-remove-jpa-example[] - entityManager.remove(person); + entityManager.remove( person ); //end::pc-remove-jpa-example[] - entityManager.persist(person); + entityManager.persist( person ); Long personId = person.getId(); //tag::pc-get-reference-jpa-example[] Book book = new Book(); - book.setAuthor(entityManager.getReference(Person.class, personId)); + book.setAuthor( entityManager.getReference( Person.class, personId ) ); //end::pc-get-reference-jpa-example[] return personId; - }); - doInJPA(this::entityManagerFactory, entityManager -> { + } ); + scope.inTransaction( entityManager -> { Long personId = _personId; //tag::pc-find-jpa-example[] - Person person = entityManager.find(Person.class, personId); + Person person = entityManager.find( Person.class, personId ); //end::pc-find-jpa-example[] - }); - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); - entityManager.createQuery("delete from Book").executeUpdate(); - entityManager.createQuery("delete from Person").executeUpdate(); + } ); + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); + entityManager.createQuery( "delete from Book" ).executeUpdate(); + entityManager.createQuery( "delete from Person" ).executeUpdate(); //tag::pc-persist-native-example[] Person person = new Person(); - person.setId(1L); - person.setName("John Doe"); + person.setId( 1L ); + person.setName( "John Doe" ); - session.persist(person); + session.persist( person ); //end::pc-persist-native-example[] //tag::pc-remove-native-example[] - session.remove(person); + session.remove( person ); //end::pc-remove-native-example[] - session.persist(person); + session.persist( person ); Long personId = person.getId(); //tag::pc-get-reference-native-example[] Book book = new Book(); - book.setId(1L); - book.setIsbn("123-456-7890"); - entityManager.persist(book); - book.setAuthor(session.getReference(Person.class, personId)); + book.setId( 1L ); + book.setIsbn( "123-456-7890" ); + entityManager.persist( book ); + book.setAuthor( session.getReference( Person.class, personId ) ); //end::pc-get-reference-native-example[] - }); - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + } ); + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); Long personId = _personId; //tag::pc-find-native-example[] - Person person = session.get(Person.class, personId); + Person person = session.get( Person.class, personId ); //end::pc-find-native-example[] - }); - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + } ); + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); Long personId = _personId; //tag::pc-find-by-id-native-example[] - Person person = session.byId(Person.class).load(personId); + Person person = session.byId( Person.class ).load( personId ); //end::pc-find-by-id-native-example[] //tag::pc-find-optional-by-id-native-example[] - Optional optionalPerson = session.byId(Person.class).loadOptional(personId); + Optional optionalPerson = session.byId( Person.class ).loadOptional( personId ); //end::pc-find-optional-by-id-native-example[] String isbn = "123-456-7890"; //tag::pc-find-by-simple-natural-id-example[] - Book book = session.bySimpleNaturalId(Book.class).getReference(isbn); + Book book = session.bySimpleNaturalId( Book.class ).getReference( isbn ); //end::pc-find-by-simple-natural-id-example[] - assertNotNull(book); - }); - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + assertThat(book ).isNotNull(); + } ); + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); String isbn = "123-456-7890"; //tag::pc-find-by-natural-id-example[] Book book = session - .byNaturalId(Book.class) - .using("isbn", isbn) - .load(); + .byNaturalId( Book.class ) + .using( "isbn", isbn ) + .load(); //end::pc-find-by-natural-id-example[] - assertNotNull(book); + assertThat(book ).isNotNull(); //tag::pc-find-optional-by-simple-natural-id-example[] Optional optionalBook = session - .byNaturalId(Book.class) - .using("isbn", isbn) - .loadOptional(); + .byNaturalId( Book.class ) + .using( "isbn", isbn ) + .loadOptional(); //end::pc-find-optional-by-simple-natural-id-example[] - }); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Long personId = _personId; //tag::pc-managed-state-jpa-example[] - Person person = entityManager.find(Person.class, personId); - person.setName("John Doe"); + Person person = entityManager.find( Person.class, personId ); + person.setName( "John Doe" ); entityManager.flush(); //end::pc-managed-state-jpa-example[] - }); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Long personId = _personId; //tag::pc-refresh-jpa-example[] - Person person = entityManager.find(Person.class, personId); + Person person = entityManager.find( Person.class, personId ); - entityManager.createQuery("update Person set name = UPPER(name)").executeUpdate(); + entityManager.createQuery( "update Person set name = UPPER(name)" ).executeUpdate(); - entityManager.refresh(person); - assertEquals("JOHN DOE", person.getName()); + entityManager.refresh( person ); + assertThat( person.getName()).isEqualTo("JOHN DOE"); //end::pc-refresh-jpa-example[] - }); + } ); try { - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Long personId = _personId; //tag::pc-refresh-child-entity-jpa-example[] try { - Person person = entityManager.find(Person.class, personId); + Person person = entityManager.find( Person.class, personId ); Book book = new Book(); - book.setId(100L); - book.setTitle("Hibernate User Guide"); - book.setAuthor(person); - person.getBooks().add(book); + book.setId( 100L ); + book.setTitle( "Hibernate User Guide" ); + book.setAuthor( person ); + person.getBooks().add( book ); - entityManager.refresh(person); + entityManager.refresh( person ); } catch (EntityNotFoundException expected) { - log.info("Beware when cascading the refresh associations to transient entities!"); + // "Beware when cascading the refresh associations to transient entities!" } //end::pc-refresh-child-entity-jpa-example[] - }); + } ); } catch (Exception expected) { } - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); Long personId = _personId; //tag::pc-managed-state-native-example[] - Person person = session.byId(Person.class).load(personId); - person.setName("John Doe"); + Person person = session.byId( Person.class ).load( personId ); + person.setName( "John Doe" ); session.flush(); //end::pc-managed-state-native-example[] - }); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); Long personId = _personId; //tag::pc-refresh-native-example[] - Person person = session.byId(Person.class).load(personId); + Person person = session.byId( Person.class ).load( personId ); - session.doWork(connection -> { - try(Statement statement = connection.createStatement()) { - statement.executeUpdate("UPDATE Person SET name = UPPER(name)"); + session.doWork( connection -> { + try (Statement statement = connection.createStatement()) { + statement.executeUpdate( "UPDATE Person SET name = UPPER(name)" ); } - }); + } ); - session.refresh(person); - assertEquals("JOHN DOE", person.getName()); + session.refresh( person ); + assertThat( person.getName()).isEqualTo("JOHN DOE"); //end::pc-refresh-native-example[] - }); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); Long personId = _personId; - Person personDetachedReference = session.byId(Person.class).load(personId); + Person personDetachedReference = session.byId( Person.class ).load( personId ); //Clear the Session so the person entity becomes detached session.clear(); - new MergeVisualizer(session).merge(personDetachedReference); - }); + new MergeVisualizer( session ).merge( personDetachedReference ); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Long personId = _personId; //tag::pc-merge-jpa-example[] - Person person = entityManager.find(Person.class, personId); + Person person = entityManager.find( Person.class, personId ); //Clear the EntityManager so the person entity becomes detached entityManager.clear(); - person.setName("Mr. John Doe"); + person.setName( "Mr. John Doe" ); - person = entityManager.merge(person); + person = entityManager.merge( person ); //end::pc-merge-jpa-example[] //tag::pc-contains-jpa-example[] - boolean contained = entityManager.contains(person); + boolean contained = entityManager.contains( person ); //end::pc-contains-jpa-example[] - assertTrue(contained); + assertThat( contained ).isTrue(); //tag::pc-verify-lazy-jpa-example[] PersistenceUnitUtil persistenceUnitUtil = entityManager.getEntityManagerFactory().getPersistenceUnitUtil(); - boolean personInitialized = persistenceUnitUtil.isLoaded(person); + boolean personInitialized = persistenceUnitUtil.isLoaded( person ); - boolean personBooksInitialized = persistenceUnitUtil.isLoaded(person.getBooks()); + boolean personBooksInitialized = persistenceUnitUtil.isLoaded( person.getBooks() ); - boolean personNameInitialized = persistenceUnitUtil.isLoaded(person, "name"); + boolean personNameInitialized = persistenceUnitUtil.isLoaded( person, "name" ); //end::pc-verify-lazy-jpa-example[] - }); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Long personId = _personId; - Person person = entityManager.find(Person.class, personId); + Person person = entityManager.find( Person.class, personId ); //tag::pc-verify-lazy-jpa-alternative-example[] PersistenceUtil persistenceUnitUtil = Persistence.getPersistenceUtil(); - boolean personInitialized = persistenceUnitUtil.isLoaded(person); + boolean personInitialized = persistenceUnitUtil.isLoaded( person ); - boolean personBooksInitialized = persistenceUnitUtil.isLoaded(person.getBooks()); + boolean personBooksInitialized = persistenceUnitUtil.isLoaded( person.getBooks() ); - boolean personNameInitialized = persistenceUnitUtil.isLoaded(person, "name"); + boolean personNameInitialized = persistenceUnitUtil.isLoaded( person, "name" ); //end::pc-verify-lazy-jpa-alternative-example[] - }); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); Long personId = _personId; //tag::pc-merge-native-example[] - Person person = session.byId(Person.class).load(personId); + Person person = session.byId( Person.class ).load( personId ); //Clear the Session so the person entity becomes detached session.clear(); - person.setName("Mr. John Doe"); + person.setName( "Mr. John Doe" ); - person = (Person) session.merge(person); + person = (Person) session.merge( person ); //end::pc-merge-native-example[] //tag::pc-contains-native-example[] - boolean contained = session.contains(person); + boolean contained = session.contains( person ); //end::pc-contains-native-example[] - assertTrue(contained); + assertThat( contained ).isTrue(); //tag::pc-verify-lazy-native-example[] - boolean personInitialized = Hibernate.isInitialized(person); + boolean personInitialized = Hibernate.isInitialized( person ); - boolean personBooksInitialized = Hibernate.isInitialized(person.getBooks()); + boolean personBooksInitialized = Hibernate.isInitialized( person.getBooks() ); - boolean personNameInitialized = Hibernate.isPropertyInitialized(person, "name"); + boolean personNameInitialized = Hibernate.isPropertyInitialized( person, "name" ); //end::pc-verify-lazy-native-example[] - }); + } ); } public static class MergeVisualizer { @@ -340,8 +340,8 @@ public MergeVisualizer(Session session) { //tag::pc-merge-visualize-example[] public Person merge(Person detached) { - Person newReference = session.byId(Person.class).load(detached.getId()); - newReference.setName(detached.getName()); + Person newReference = session.byId( Person.class ).load( detached.getId() ); + newReference.setName( detached.getName() ); return newReference; } //end::pc-merge-visualize-example[] @@ -396,7 +396,7 @@ public static class Book { //Getters and setters are omitted for brevity - //end::pc-find-by-natural-id-entity-example[] + //end::pc-find-by-natural-id-entity-example[] public Long getId() { return id; @@ -429,7 +429,7 @@ public String getIsbn() { public void setIsbn(String isbn) { this.isbn = isbn; } - //tag::pc-find-by-natural-id-entity-example[] + //tag::pc-find-by-natural-id-entity-example[] } //end::pc-find-by-natural-id-entity-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/WhereJoinTableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/WhereJoinTableTest.java index dc472b3f27c1..7d093461aeb8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/WhereJoinTableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/WhereJoinTableTest.java @@ -4,108 +4,110 @@ */ package org.hibernate.orm.test.pc; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.JoinTable; import jakarta.persistence.ManyToMany; - import org.hibernate.Session; import org.hibernate.annotations.SQLJoinTableRestriction; import org.hibernate.dialect.H2Dialect; import org.hibernate.metamodel.CollectionClassification; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.SettingProvider; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.RequiresDialect; -import org.junit.Test; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import static org.assertj.core.api.Assertions.assertThat; import static org.hibernate.cfg.AvailableSettings.DEFAULT_LIST_SEMANTICS; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; /** * @author Vlad Mihalcea */ @RequiresDialect(H2Dialect.class) -public class WhereJoinTableTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Book.class, - Reader.class - }; - } +@Jpa( + annotatedClasses = { + WhereJoinTableTest.Book.class, + WhereJoinTableTest.Reader.class + }, + settingProviders = @SettingProvider( + settingName = DEFAULT_LIST_SEMANTICS, + provider = WhereJoinTableTest.CollectionClassificationProvider.class + ) +) +public class WhereJoinTableTest { - @Override - protected void addConfigOptions(Map options) { - super.addConfigOptions( options ); - options.put( DEFAULT_LIST_SEMANTICS, CollectionClassification.BAG.name() ); + public static class CollectionClassificationProvider implements SettingProvider.Provider { + @Override + public CollectionClassification getSetting() { + return CollectionClassification.BAG; + } } @Test - public void testLifecycle() { + public void testLifecycle(EntityManagerFactoryScope scope) { //tag::pc-where-persistence-example[] - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { - entityManager.unwrap(Session.class).doWork(connection -> { - try(Statement statement = connection.createStatement()) { + entityManager.unwrap( Session.class ).doWork( connection -> { + try (Statement statement = connection.createStatement()) { statement.executeUpdate( - "ALTER TABLE Book_Reader ADD created_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP" + "ALTER TABLE Book_Reader ADD created_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP" ); } - }); + } ); //tag::pc-where-join-table-persist-example[] Book book = new Book(); - book.setId(1L); - book.setTitle("High-Performance Java Persistence"); - book.setAuthor("Vad Mihalcea"); - entityManager.persist(book); + book.setId( 1L ); + book.setTitle( "High-Performance Java Persistence" ); + book.setAuthor( "Vad Mihalcea" ); + entityManager.persist( book ); Reader reader1 = new Reader(); - reader1.setId(1L); - reader1.setName("John Doe"); - entityManager.persist(reader1); + reader1.setId( 1L ); + reader1.setName( "John Doe" ); + entityManager.persist( reader1 ); Reader reader2 = new Reader(); - reader2.setId(2L); - reader2.setName("John Doe Jr."); - entityManager.persist(reader2); + reader2.setId( 2L ); + reader2.setName( "John Doe Jr." ); + entityManager.persist( reader2 ); //end::pc-where-join-table-persist-example[] - }); - - doInJPA(this::entityManagerFactory, entityManager -> { - entityManager.unwrap(Session.class).doWork(connection -> { - try(Statement statement = connection.createStatement()) { - //tag::pc-where-join-table-persist-example[] - - statement.executeUpdate( - "INSERT INTO Book_Reader " + - " (book_id, reader_id) " + - "VALUES " + - " (1, 1) " - ); - statement.executeUpdate( - "INSERT INTO Book_Reader " + - " (book_id, reader_id, created_on) " + - "VALUES " + - " (1, 2, DATEADD('DAY', -10, CURRENT_TIMESTAMP())) " - ); - //end::pc-where-join-table-persist-example[] - }} + } ); + + scope.inTransaction( entityManager -> { + entityManager.unwrap( Session.class ).doWork( connection -> { + try (Statement statement = connection.createStatement()) { + //tag::pc-where-join-table-persist-example[] + + statement.executeUpdate( + "INSERT INTO Book_Reader " + + " (book_id, reader_id) " + + "VALUES " + + " (1, 1) " + ); + statement.executeUpdate( + "INSERT INTO Book_Reader " + + " (book_id, reader_id, created_on) " + + "VALUES " + + " (1, 2, DATEADD('DAY', -10, CURRENT_TIMESTAMP())) " + ); + //end::pc-where-join-table-persist-example[] + } + } ); //tag::pc-where-join-table-fetch-example[] - Book book = entityManager.find(Book.class, 1L); - assertEquals(1, book.getCurrentWeekReaders().size()); + Book book = entityManager.find( Book.class, 1L ); + assertThat( book.getCurrentWeekReaders() ).hasSize( 1 ); //end::pc-where-join-table-fetch-example[] - }); + } ); } //tag::pc-where-join-table-example[] @@ -121,9 +123,9 @@ public static class Book { @ManyToMany @JoinTable( - name = "Book_Reader", - joinColumns = @JoinColumn(name = "book_id"), - inverseJoinColumns = @JoinColumn(name = "reader_id") + name = "Book_Reader", + joinColumns = @JoinColumn(name = "book_id"), + inverseJoinColumns = @JoinColumn(name = "reader_id") ) @SQLJoinTableRestriction("created_on > DATEADD('DAY', -7, CURRENT_TIMESTAMP())") private List currentWeekReaders = new ArrayList<>(); @@ -191,5 +193,5 @@ public void setName(String name) { } //tag::pc-where-join-table-example[] } - //end::pc-where-join-table-example[] + //end::pc-where-join-table-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/WhereTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/WhereTest.java index 1335ae0252cc..833e2a7aef33 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/WhereTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/WhereTest.java @@ -4,10 +4,6 @@ */ package org.hibernate.orm.test.pc; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.EnumType; @@ -15,94 +11,99 @@ import jakarta.persistence.Id; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; - import org.hibernate.annotations.SQLRestriction; import org.hibernate.metamodel.CollectionClassification; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.SettingProvider; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import java.util.ArrayList; +import java.util.List; +import static org.assertj.core.api.Assertions.assertThat; import static org.hibernate.cfg.AvailableSettings.DEFAULT_LIST_SEMANTICS; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; /** * @author Vlad Mihalcea */ -public class WhereTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Client.class, - Account.class - }; - } - - @Override - protected void addConfigOptions(Map options) { - super.addConfigOptions( options ); - options.put( DEFAULT_LIST_SEMANTICS, CollectionClassification.BAG.name() ); +@Jpa( + annotatedClasses = { + WhereTest.Client.class, + WhereTest.Account.class + }, + settingProviders = @SettingProvider( + settingName = DEFAULT_LIST_SEMANTICS, + provider = WhereTest.CollectionClassificationProvider.class + ) +) +public class WhereTest { + + public static class CollectionClassificationProvider implements SettingProvider.Provider { + @Override + public CollectionClassification getSetting() { + return CollectionClassification.BAG; + } } @Test - public void testLifecycle() { + public void testLifecycle(EntityManagerFactoryScope scope) { //tag::pc-where-persistence-example[] - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Client client = new Client(); - client.setId(1L); - client.setName("John Doe"); - entityManager.persist(client); + client.setId( 1L ); + client.setName( "John Doe" ); + entityManager.persist( client ); Account account1 = new Account(); - account1.setId(1L); - account1.setType(AccountType.CREDIT); - account1.setAmount(5000d); - account1.setRate(1.25 / 100); - account1.setActive(true); - account1.setClient(client); - client.getCreditAccounts().add(account1); - entityManager.persist(account1); + account1.setId( 1L ); + account1.setType( AccountType.CREDIT ); + account1.setAmount( 5000d ); + account1.setRate( 1.25 / 100 ); + account1.setActive( true ); + account1.setClient( client ); + client.getCreditAccounts().add( account1 ); + entityManager.persist( account1 ); Account account2 = new Account(); - account2.setId(2L); - account2.setType(AccountType.DEBIT); - account2.setAmount(0d); - account2.setRate(1.05 / 100); - account2.setActive(false); - account2.setClient(client); - client.getDebitAccounts().add(account2); - entityManager.persist(account2); + account2.setId( 2L ); + account2.setType( AccountType.DEBIT ); + account2.setAmount( 0d ); + account2.setRate( 1.05 / 100 ); + account2.setActive( false ); + account2.setClient( client ); + client.getDebitAccounts().add( account2 ); + entityManager.persist( account2 ); Account account3 = new Account(); - account3.setType(AccountType.DEBIT); - account3.setId(3L); - account3.setAmount(250d); - account3.setRate(1.05 / 100); - account3.setActive(true); - account3.setClient(client); - client.getDebitAccounts().add(account3); - entityManager.persist(account3); - }); + account3.setType( AccountType.DEBIT ); + account3.setId( 3L ); + account3.setAmount( 250d ); + account3.setRate( 1.05 / 100 ); + account3.setActive( true ); + account3.setClient( client ); + client.getDebitAccounts().add( account3 ); + entityManager.persist( account3 ); + } ); //end::pc-where-persistence-example[] //tag::pc-where-entity-query-example[] - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { List accounts = entityManager.createQuery( - "select a from Account a", Account.class) - .getResultList(); - assertEquals(2, accounts.size()); - }); + "select a from Account a", Account.class ) + .getResultList(); + assertThat( accounts ).hasSize( 2 ); + } ); //end::pc-where-entity-query-example[] //tag::pc-where-collection-query-example[] - doInJPA(this::entityManagerFactory, entityManager -> { - Client client = entityManager.find(Client.class, 1L); - assertEquals(1, client.getCreditAccounts().size()); - assertEquals(1, client.getDebitAccounts().size()); - }); + scope.inTransaction( entityManager -> { + Client client = entityManager.find( Client.class, 1L ); + assertThat( client.getCreditAccounts() ).hasSize( 1 ); + assertThat( client.getDebitAccounts() ).hasSize( 1 ); + } ); //end::pc-where-collection-query-example[] } @@ -179,7 +180,7 @@ public static class Account { //Getters and setters omitted for brevity - //end::pc-where-example[] + //end::pc-where-example[] public Long getId() { return id; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/PostgreSQLFunctionProcedureTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/PostgreSQLFunctionProcedureTest.java index e3c796cadf46..0aef95778b52 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/PostgreSQLFunctionProcedureTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/PostgreSQLFunctionProcedureTest.java @@ -4,47 +4,46 @@ */ package org.hibernate.orm.test.procedure; -import java.sql.CallableStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.sql.Types; -import java.time.LocalDateTime; -import java.time.ZoneOffset; -import java.util.List; -import java.util.Set; - +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.ParameterMode; +import jakarta.persistence.StoredProcedureQuery; import org.hibernate.Session; +import org.hibernate.SessionFactory; import org.hibernate.boot.model.relational.Database; import org.hibernate.boot.model.relational.NamedAuxiliaryDatabaseObject; import org.hibernate.boot.model.relational.Namespace; -import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.dialect.PostgreSQLDialect; import org.hibernate.dialect.PostgresPlusDialect; import org.hibernate.jpa.HibernateHints; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.jpa.boot.spi.Bootstrap; +import org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder; import org.hibernate.procedure.ProcedureCall; -import org.hibernate.type.StandardBasicTypes; - -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.EntityManagerFactoryBasedFunctionalTest; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.type.StandardBasicTypes; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import jakarta.persistence.ParameterMode; -import jakarta.persistence.StoredProcedureQuery; +import java.sql.CallableStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.sql.Types; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.Set; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Vlad Mihalcea */ @RequiresDialect(PostgreSQLDialect.class) -public class PostgreSQLFunctionProcedureTest extends BaseEntityManagerFunctionalTestCase { +public class PostgreSQLFunctionProcedureTest extends EntityManagerFactoryBasedFunctionalTest { @Override protected Class[] getAnnotatedClasses() { @@ -54,28 +53,37 @@ protected Class[] getAnnotatedClasses() { }; } + @AfterEach + public void cleanupTestData() { + entityManagerFactory().unwrap( SessionFactory.class ).getSchemaManager().truncateMappedObjects(); + } + @Override - protected void applyMetadataImplementor(MetadataImplementor metadataImplementor) { - final Database database = metadataImplementor.getDatabase(); + public EntityManagerFactory produceEntityManagerFactory() { + EntityManagerFactoryBuilder entityManagerFactoryBuilder = Bootstrap.getEntityManagerFactoryBuilder( + buildPersistenceUnitDescriptor(), + buildSettings() + ); + Database database = entityManagerFactoryBuilder.metadata().getDatabase(); final Namespace namespace = database.getDefaultNamespace(); database.addAuxiliaryDatabaseObject( new NamedAuxiliaryDatabaseObject( "fn_count_phones", namespace, "CREATE OR REPLACE FUNCTION fn_count_phones( " + - " IN personId bigint) " + - " RETURNS bigint AS " + - "$BODY$ " + - " DECLARE " + - " phoneCount bigint; " + - " BEGIN " + - " SELECT COUNT(*) INTO phoneCount " + - " FROM phone " + - " WHERE person_id = personId; " + - " RETURN phoneCount;" + - " END; " + - "$BODY$ " + - "LANGUAGE plpgsql;", + " IN personId bigint) " + + " RETURNS bigint AS " + + "$BODY$ " + + " DECLARE " + + " phoneCount bigint; " + + " BEGIN " + + " SELECT COUNT(*) INTO phoneCount " + + " FROM phone " + + " WHERE person_id = personId; " + + " RETURN phoneCount;" + + " END; " + + "$BODY$ " + + "LANGUAGE plpgsql;", "drop function fn_count_phones(bigint)", Set.of( PostgreSQLDialect.class.getName(), PostgresPlusDialect.class.getName() ) ) @@ -85,19 +93,19 @@ protected void applyMetadataImplementor(MetadataImplementor metadataImplementor) "fn_phones", namespace, "CREATE OR REPLACE FUNCTION fn_phones(personId BIGINT) " + - " RETURNS REFCURSOR AS " + - "$BODY$ " + - " DECLARE " + - " phones REFCURSOR; " + - " BEGIN " + - " OPEN phones FOR " + - " SELECT * " + - " FROM phone " + - " WHERE person_id = personId; " + - " RETURN phones; " + - " END; " + - "$BODY$ " + - "LANGUAGE plpgsql", + " RETURNS REFCURSOR AS " + + "$BODY$ " + + " DECLARE " + + " phones REFCURSOR; " + + " BEGIN " + + " OPEN phones FOR " + + " SELECT * " + + " FROM phone " + + " WHERE person_id = personId; " + + " RETURN phones; " + + " END; " + + "$BODY$ " + + "LANGUAGE plpgsql", "drop function fn_phones(bigint, bigint)", Set.of( PostgreSQLDialect.class.getName(), PostgresPlusDialect.class.getName() ) ) @@ -107,16 +115,16 @@ protected void applyMetadataImplementor(MetadataImplementor metadataImplementor) "singleRefCursor", namespace, "CREATE OR REPLACE FUNCTION singleRefCursor() " + - " RETURNS REFCURSOR AS " + - "$BODY$ " + - " DECLARE " + - " p_recordset REFCURSOR; " + - " BEGIN " + - " OPEN p_recordset FOR SELECT 1; " + - " RETURN p_recordset; " + - " END; " + - "$BODY$ " + - "LANGUAGE plpgsql;", + " RETURNS REFCURSOR AS " + + "$BODY$ " + + " DECLARE " + + " p_recordset REFCURSOR; " + + " BEGIN " + + " OPEN p_recordset FOR SELECT 1; " + + " RETURN p_recordset; " + + " END; " + + "$BODY$ " + + "LANGUAGE plpgsql;", "drop function singleRefCursor()", Set.of( PostgreSQLDialect.class.getName(), PostgresPlusDialect.class.getName() ) ) @@ -126,31 +134,32 @@ protected void applyMetadataImplementor(MetadataImplementor metadataImplementor) "fn_is_null", namespace, "CREATE OR REPLACE FUNCTION fn_is_null( " + - " IN param varchar(255)) " + - " RETURNS boolean AS " + - "$BODY$ " + - " DECLARE " + - " result boolean; " + - " BEGIN " + - " SELECT param is null INTO result; " + - " RETURN result; " + - " END; " + - "$BODY$ " + - "LANGUAGE plpgsql;", + " IN param varchar(255)) " + + " RETURNS boolean AS " + + "$BODY$ " + + " DECLARE " + + " result boolean; " + + " BEGIN " + + " SELECT param is null INTO result; " + + " RETURN result; " + + " END; " + + "$BODY$ " + + "LANGUAGE plpgsql;", "drop function fn_is_null(varchar)", Set.of( PostgreSQLDialect.class.getName(), PostgresPlusDialect.class.getName() ) ) ); + return entityManagerFactoryBuilder.build(); } - @Before + @BeforeEach public void init() { - doInJPA( this::entityManagerFactory, entityManager -> { + inTransaction( entityManager -> { Person person1 = new Person( 1L, "John Doe" ); person1.setNickName( "JD" ); person1.setAddress( "Earth" ); person1.setCreatedOn( Timestamp.from( LocalDateTime.of( 2000, 1, 1, 0, 0, 0 ) - .toInstant( ZoneOffset.UTC ) ) ); + .toInstant( ZoneOffset.UTC ) ) ); entityManager.persist( person1 ); @@ -168,7 +177,7 @@ public void init() { @Test public void testFunctionProcedureOutParameter() { - doInJPA( this::entityManagerFactory, entityManager -> { + inTransaction( entityManager -> { StoredProcedureQuery query = entityManager.createStoredProcedureQuery( "fn_count_phones", Long.class ); query.registerStoredProcedureParameter( "personId", Long.class, ParameterMode.IN ); query.setHint( HibernateHints.HINT_CALLABLE_FUNCTION, "true" ); @@ -177,27 +186,26 @@ public void testFunctionProcedureOutParameter() { query.execute(); Long phoneCount = (Long) query.getSingleResult(); - assertEquals( Long.valueOf( 2 ), phoneCount ); + assertThat( phoneCount ).isEqualTo( 2 ); } ); } @Test public void testFunctionProcedureRefCursor() { - doInJPA( this::entityManagerFactory, entityManager -> { + inTransaction( entityManager -> { StoredProcedureQuery query = entityManager.createStoredProcedureQuery( "fn_phones" ); query.registerStoredProcedureParameter( 1, Long.class, ParameterMode.IN ); query.setHint( HibernateHints.HINT_CALLABLE_FUNCTION, "true" ); query.setParameter( 1, 1L ); - List phones = query.getResultList(); - assertEquals( 2, phones.size() ); + assertThat( query.getResultList() ).hasSize( 2 ); } ); } @Test public void testFunctionProcedureRefCursorOld() { - doInJPA( this::entityManagerFactory, entityManager -> { + inTransaction( entityManager -> { StoredProcedureQuery query = entityManager.createStoredProcedureQuery( "fn_phones" ); query.registerStoredProcedureParameter( 1, void.class, ParameterMode.REF_CURSOR ); query.registerStoredProcedureParameter( 2, Long.class, ParameterMode.IN ); @@ -205,14 +213,13 @@ public void testFunctionProcedureRefCursorOld() { query.setParameter( 2, 1L ); - List phones = query.getResultList(); - assertEquals( 2, phones.size() ); + assertThat( query.getResultList() ).hasSize( 2 ); } ); } @Test public void testFunctionWithJDBC() { - doInJPA( this::entityManagerFactory, entityManager -> { + inTransaction( entityManager -> { Session session = entityManager.unwrap( Session.class ); Long phoneCount = session.doReturningWork( connection -> { CallableStatement function = null; @@ -229,7 +236,7 @@ public void testFunctionWithJDBC() { } } } ); - assertEquals( Long.valueOf( 2 ), phoneCount ); + assertThat( phoneCount ).isEqualTo( 2 ); } ); } @@ -237,7 +244,7 @@ public void testFunctionWithJDBC() { @JiraKey(value = "HHH-11863") public void testSysRefCursorAsOutParameter() { - doInJPA( this::entityManagerFactory, entityManager -> { + inTransaction( entityManager -> { Integer value = null; Session session = entityManager.unwrap( Session.class ); @@ -263,7 +270,7 @@ public void testSysRefCursorAsOutParameter() { catch (Exception e) { fail( e.getMessage() ); } - assertEquals( Integer.valueOf( 1 ), value ); + assertThat( value ).isEqualTo( 1 ); StoredProcedureQuery function = entityManager.createStoredProcedureQuery( "singleRefCursor" ); @@ -273,24 +280,24 @@ public void testSysRefCursorAsOutParameter() { value = (Integer) function.getSingleResult(); - assertEquals( Integer.valueOf( 1 ), value ); + assertThat( value ).isEqualTo( 1 ); } ); } @Test @JiraKey(value = "HHH-11863") public void testSysRefCursorAsOutParameterOld() { - doInJPA( this::entityManagerFactory, entityManager -> { + inTransaction( entityManager -> { StoredProcedureQuery function = entityManager.createStoredProcedureQuery( "singleRefCursor" ); function.registerStoredProcedureParameter( 1, void.class, ParameterMode.REF_CURSOR ); function.setHint( HibernateHints.HINT_CALLABLE_FUNCTION, "true" ); function.execute(); - assertFalse( function.hasMoreResults() ); + assertThat( function.hasMoreResults() ).isFalse(); Integer value = null; - try (ResultSet resultSet = (ResultSet) function.getOutputParameterValue( 1 ) ) { + try (ResultSet resultSet = (ResultSet) function.getOutputParameterValue( 1 )) { while ( resultSet.next() ) { value = resultSet.getInt( 1 ); } @@ -299,7 +306,7 @@ public void testSysRefCursorAsOutParameterOld() { fail( e.getMessage() ); } - assertEquals( Integer.valueOf( 1 ), value ); + assertThat( value ).isEqualTo( 1 ); } ); } @@ -307,7 +314,7 @@ public void testSysRefCursorAsOutParameterOld() { @JiraKey(value = "HHH-12905") public void testFunctionProcedureNullParameterHibernate() { - doInJPA( this::entityManagerFactory, entityManager -> { + inTransaction( entityManager -> { ProcedureCall procedureCall = entityManager.unwrap( Session.class ) .createStoredProcedureCall( "fn_is_null" ); procedureCall.registerParameter( 1, StandardBasicTypes.STRING, ParameterMode.IN ); @@ -316,10 +323,10 @@ public void testFunctionProcedureNullParameterHibernate() { Boolean result = (Boolean) procedureCall.getSingleResult(); - assertTrue( result ); + assertThat( result ).isTrue(); } ); - doInJPA( this::entityManagerFactory, entityManager -> { + inTransaction( entityManager -> { ProcedureCall procedureCall = entityManager.unwrap( Session.class ) .createStoredProcedureCall( "fn_is_null" ); procedureCall.registerParameter( 1, StandardBasicTypes.STRING, ParameterMode.IN ); @@ -328,7 +335,7 @@ public void testFunctionProcedureNullParameterHibernate() { Boolean result = (Boolean) procedureCall.getSingleResult(); - assertFalse( result ); + assertThat( result ).isFalse(); } ); } @@ -336,7 +343,7 @@ public void testFunctionProcedureNullParameterHibernate() { @JiraKey(value = "HHH-12905") public void testFunctionProcedureNullParameterHibernateWithoutEnablePassingNulls() { - doInJPA( this::entityManagerFactory, entityManager -> { + inTransaction( entityManager -> { ProcedureCall procedureCall = entityManager.unwrap( Session.class ) .createStoredProcedureCall( "fn_is_null" ); procedureCall.registerParameter( "param", StandardBasicTypes.STRING, ParameterMode.IN ); @@ -345,30 +352,24 @@ public void testFunctionProcedureNullParameterHibernateWithoutEnablePassingNulls Boolean result = (Boolean) procedureCall.getSingleResult(); - assertTrue( result ); + assertThat( result ).isTrue(); } ); } @Test public void testFunctionProcedureNullParameterHibernateWithoutSettingTheParameter() { - doInJPA( this::entityManagerFactory, entityManager -> { - try { - ProcedureCall procedureCall = entityManager.unwrap( Session.class ) - .createStoredProcedureCall( "fn_is_null" ); - procedureCall.registerParameter( "param", StandardBasicTypes.STRING, ParameterMode.IN ); - procedureCall.markAsFunctionCall( Boolean.class ); + IllegalArgumentException exception = assertThrows( IllegalArgumentException.class, + () -> inTransaction( entityManager -> { + ProcedureCall procedureCall = entityManager.unwrap( Session.class ) + .createStoredProcedureCall( "fn_is_null" ); + procedureCall.registerParameter( "param", StandardBasicTypes.STRING, ParameterMode.IN ); + procedureCall.markAsFunctionCall( Boolean.class ); - procedureCall.execute(); + procedureCall.execute(); + } ) ); - fail( "Should have thrown exception" ); - } - catch (IllegalArgumentException e) { - assertEquals( - "The parameter named [param] was not set! You need to call the setParameter method.", - e.getMessage() - ); - } - } ); + assertThat( exception.getMessage() ) + .isEqualTo( "The parameter named [param] was not set! You need to call the setParameter method." ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/property/BasicPropertyAccessorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/property/BasicPropertyAccessorTest.java index 28e54b0d9639..55771af42438 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/property/BasicPropertyAccessorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/property/BasicPropertyAccessorTest.java @@ -6,18 +6,20 @@ import org.hibernate.property.access.internal.PropertyAccessStrategyBasicImpl; import org.hibernate.property.access.spi.PropertyAccess; +import org.hibernate.testing.orm.junit.BaseUnitTest; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; /** * @author Steve Ebersole */ -public class BasicPropertyAccessorTest extends BaseUnitTestCase { +@BaseUnitTest +public class BasicPropertyAccessorTest { public static abstract class Super { public abstract Object getIt(); + public abstract void setIt(Object it); } @@ -34,7 +36,7 @@ public String getIt() { @Override public void setIt(Object it) { - this.it = ( it == null || String.class.isInstance( it ) ) + this.it = (it == null || String.class.isInstance( it )) ? (String) it : it.toString(); } @@ -72,14 +74,14 @@ public void testBridgeMethodDisregarded() { { final PropertyAccess access = accessStrategy.buildPropertyAccess( Duper.class, "it", true ); - assertEquals( String.class, access.getGetter().getReturnTypeClass() ); - assertEquals( Object.class, access.getSetter().getMethod().getParameterTypes()[0] ); + assertThat( access.getGetter().getReturnTypeClass() ).isEqualTo( String.class ); + assertThat( access.getSetter().getMethod().getParameterTypes()[0] ).isEqualTo( Object.class ); } { final PropertyAccess access = accessStrategy.buildPropertyAccess( Duper2.class, "it", true ); - assertEquals( String.class, access.getGetter().getReturnTypeClass() ); - assertEquals( String.class, access.getSetter().getMethod().getParameterTypes()[0] ); + assertThat( access.getGetter().getReturnTypeClass() ).isEqualTo( String.class ); + assertThat( access.getSetter().getMethod().getParameterTypes()[0] ).isEqualTo( String.class ); } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/property/GetAndIsVariantGetterTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/property/GetAndIsVariantGetterTest.java index e8e0ec3d73a2..9a66e5f84ddb 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/property/GetAndIsVariantGetterTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/property/GetAndIsVariantGetterTest.java @@ -9,26 +9,21 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Transient; - import org.hibernate.MappingException; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.internal.util.ReflectHelper; - import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.util.ServiceRegistryUtil; -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; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.hamcrest.CoreMatchers.endsWith; -import static org.hamcrest.CoreMatchers.startsWith; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Originally written to verify fix for HHH-10172 @@ -38,12 +33,12 @@ public class GetAndIsVariantGetterTest { private static StandardServiceRegistry ssr; - @BeforeClass + @BeforeAll public static void prepare() { ssr = ServiceRegistryUtil.serviceRegistry(); } - @AfterClass + @AfterAll public static void release() { if ( ssr != null ) { StandardServiceRegistryBuilder.destroy( ssr ); @@ -51,63 +46,57 @@ public static void release() { } @Test - @JiraKey( value = "HHH-10172" ) + @JiraKey(value = "HHH-10172") public void testHbmXml() { - try { - new MetadataSources( ssr ) - .addResource( "org/hibernate/property/TheEntity.hbm.xml" ) - .buildMetadata(); - fail( "Expecting a failure" ); - } - catch (MappingException e) { - assertThat( e.getMessage(), endsWith( "variants of getter for property 'id'" ) ); - } + MappingException mappingException = assertThrows( MappingException.class, () -> + new MetadataSources( ssr ) + .addResource( "org/hibernate/property/TheEntity.hbm.xml" ) + .buildMetadata() + ); + assertThat( mappingException.getMessage() ).endsWith( "variants of getter for property 'id'" ); } @Test - @JiraKey( value = "HHH-10172" ) + @JiraKey(value = "HHH-10172") public void testAnnotations() { - try { - new MetadataSources( ssr ) - .addAnnotatedClass( TheEntity.class ) - .buildMetadata(); - fail( "Expecting a failure" ); - } - catch (MappingException e) { - assertThat( e.getMessage(), startsWith( "Ambiguous persistent property methods" ) ); - } + MappingException mappingException = assertThrows( MappingException.class, () -> + new MetadataSources( ssr ) + .addAnnotatedClass( TheEntity.class ) + .buildMetadata() + ); + assertThat( mappingException.getMessage() ).startsWith( "Ambiguous persistent property methods" ); } @Test - @JiraKey( value = "HHH-10242" ) + @JiraKey(value = "HHH-10242") public void testAnnotationsCorrected() { Metadata metadata = new MetadataSources( ssr ) .addAnnotatedClass( TheEntity2.class ) .buildMetadata(); - assertNotNull( metadata.getEntityBinding( TheEntity2.class.getName() ).getIdentifier() ); - assertNotNull( metadata.getEntityBinding( TheEntity2.class.getName() ).getIdentifierProperty() ); + assertThat( metadata.getEntityBinding( TheEntity2.class.getName() ).getIdentifier() ).isNotNull(); + assertThat( metadata.getEntityBinding( TheEntity2.class.getName() ).getIdentifierProperty() ).isNotNull(); } @Test - @JiraKey( value = "HHH-10309" ) + @JiraKey(value = "HHH-10309") public void testAnnotationsFieldAccess() { // this one should be ok because the AccessType is FIELD Metadata metadata = new MetadataSources( ssr ) .addAnnotatedClass( AnotherEntity.class ) .buildMetadata(); - assertNotNull( metadata.getEntityBinding( AnotherEntity.class.getName() ).getIdentifier() ); - assertNotNull( metadata.getEntityBinding( AnotherEntity.class.getName() ).getIdentifierProperty() ); + assertThat( metadata.getEntityBinding( AnotherEntity.class.getName() ).getIdentifier() ).isNotNull(); + assertThat( metadata.getEntityBinding( AnotherEntity.class.getName() ).getIdentifierProperty() ).isNotNull(); } @Test - @JiraKey( value = "HHH-12046" ) + @JiraKey(value = "HHH-12046") public void testInstanceStaticConflict() { Metadata metadata = new MetadataSources( ssr ) .addAnnotatedClass( InstanceStaticEntity.class ) .buildMetadata(); - assertNotNull( metadata.getEntityBinding( InstanceStaticEntity.class.getName() ).getIdentifier() ); - assertNotNull( metadata.getEntityBinding( InstanceStaticEntity.class.getName() ).getIdentifierProperty() ); - assertTrue( metadata.getEntityBinding( InstanceStaticEntity.class.getName() ).hasProperty("foo") ); + assertThat( metadata.getEntityBinding( InstanceStaticEntity.class.getName() ).getIdentifier() ).isNotNull(); + assertThat( metadata.getEntityBinding( InstanceStaticEntity.class.getName() ).getIdentifierProperty() ).isNotNull(); + assertThat( metadata.getEntityBinding( InstanceStaticEntity.class.getName() ).hasProperty( "foo" ) ).isTrue(); ReflectHelper.findGetterMethod( InstanceStaticEntity.class, "foo" ); } @@ -178,6 +167,7 @@ public static class InstanceStaticEntity { public Integer getId() { return id; } + public void setId(Integer id) { this.id = id; } @@ -185,6 +175,7 @@ public void setId(Integer id) { public boolean isFoo() { return this.foo; } + public void setFoo(boolean foo) { this.foo = foo; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/property/PropertyAccessStrategyMapTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/property/PropertyAccessStrategyMapTest.java index cd1df486f654..9fcdd6d42f0d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/property/PropertyAccessStrategyMapTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/property/PropertyAccessStrategyMapTest.java @@ -4,20 +4,22 @@ */ package org.hibernate.orm.test.property; +import org.hibernate.property.access.internal.PropertyAccessStrategyMapImpl; +import org.hibernate.property.access.spi.PropertyAccess; +import org.hibernate.property.access.spi.Setter; +import org.hibernate.testing.orm.junit.BaseUnitTest; +import org.junit.jupiter.api.Test; + import java.util.Date; import java.util.HashMap; import java.util.Map; -import org.hibernate.property.access.internal.PropertyAccessStrategyMapImpl; -import org.hibernate.property.access.spi.PropertyAccess; - -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; -public class PropertyAccessStrategyMapTest extends BaseUnitTestCase { +@BaseUnitTest +public class PropertyAccessStrategyMapTest { @Test public void testBasicMapClass() { @@ -32,18 +34,12 @@ public void testBasicNullClass() { @Test public void testNonMap() { final var accessStrategy = PropertyAccessStrategyMapImpl.INSTANCE; - - try { - accessStrategy.buildPropertyAccess( Date.class, "time", true ); - - fail("Should throw IllegalArgumentException"); - } - catch (IllegalArgumentException e) { - assertEquals( - "Expecting class: [java.util.Map], but containerJavaType is of type: [java.util.Date] for propertyName: [time]", - e.getMessage() - ); - } + IllegalArgumentException exception = assertThrows( IllegalArgumentException.class, () -> + accessStrategy.buildPropertyAccess( Date.class, "time", true ) + ); + assertThat( exception.getMessage() ).isEqualTo( + "Expecting class: [java.util.Map], but containerJavaType is of type: [java.util.Date] for propertyName: [time]" + ); } private void testBasic(final Class clazz) { @@ -56,8 +52,10 @@ private void testBasic(final Class clazz) { final HashMap map = new HashMap<>(); - access.getSetter().set( map, value ); - assertEquals( value, map.get( key ) ); - assertEquals( value, access.getGetter().get( map ) ); + Setter setter = access.getSetter(); + assertThat( setter ).isNotNull(); + setter.set( map, value ); + assertThat( map.get( key ) ).isEqualTo( value ); + assertThat( access.getGetter().get( map ) ).isEqualTo( value ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/property/access/spi/GetterFieldImplTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/property/access/spi/GetterFieldImplTest.java index ef393f61da0e..f664e0ca85fc 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/property/access/spi/GetterFieldImplTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/property/access/spi/GetterFieldImplTest.java @@ -4,14 +4,13 @@ */ package org.hibernate.orm.test.property.access.spi; -import java.lang.reflect.Field; - import org.hibernate.property.access.spi.Getter; import org.hibernate.property.access.spi.GetterFieldImpl; +import org.junit.jupiter.api.Test; -import org.junit.Assert; -import org.junit.Test; +import java.lang.reflect.Field; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Vlad Mihalcea @@ -19,16 +18,16 @@ public class GetterFieldImplTest { @Test - public void testGet() throws Exception { + public void testGet() { Target target = new Target(); - Assert.assertEquals( true, getter( "active" ).get( target ) ); - Assert.assertEquals( (byte) 2, getter( "children" ).get( target ) ); - Assert.assertEquals( 'M', getter( "gender" ).get( target ) ); - Assert.assertEquals( Integer.MAX_VALUE, getter( "code" ).get( target ) ); - Assert.assertEquals( Long.MAX_VALUE, getter( "id" ).get( target ) ); - Assert.assertEquals( (short) 34, getter( "age" ).get( target ) ); - Assert.assertEquals( "John Doe", getter( "name" ).get( target ) ); + assertThat( getter( "active" ).get( target ) ).isEqualTo( true ); + assertThat( getter( "children" ).get( target ) ).isEqualTo( (byte) 2 ); + assertThat( getter( "gender" ).get( target ) ).isEqualTo( 'M' ); + assertThat( getter( "code" ).get( target ) ).isEqualTo( Integer.MAX_VALUE ); + assertThat( getter( "id" ).get( target ) ).isEqualTo( Long.MAX_VALUE ); + assertThat( getter( "age" ).get( target ) ).isEqualTo( (short) 34 ); + assertThat( getter( "name" ).get( target ) ).isEqualTo( "John Doe" ); } private static class Target { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/property/access/spi/GetterMethodImplTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/property/access/spi/GetterMethodImplTest.java index 6591555968a8..43a0bde45361 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/property/access/spi/GetterMethodImplTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/property/access/spi/GetterMethodImplTest.java @@ -4,6 +4,7 @@ */ package org.hibernate.orm.test.property.access.spi; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.lang.reflect.Method; @@ -12,10 +13,7 @@ import org.hibernate.internal.util.ReflectHelper; import org.hibernate.property.access.spi.Getter; import org.hibernate.property.access.spi.GetterMethodImpl; - -import org.junit.Assert; -import org.junit.Test; - +import org.junit.jupiter.api.Test; public class GetterMethodImplTest { @@ -23,13 +21,13 @@ public class GetterMethodImplTest { public void get() throws Exception { Target target = new Target(); - Assert.assertEquals( true, getter( Target.class, "active" ).get( target ) ); - Assert.assertEquals( (byte) 2, getter( Target.class, "children" ).get( target ) ); - Assert.assertEquals( 'M', getter( Target.class, "gender" ).get( target ) ); - Assert.assertEquals( Integer.MAX_VALUE, getter( Target.class, "code" ).get( target ) ); - Assert.assertEquals( Long.MAX_VALUE, getter( Target.class, "id" ).get( target ) ); - Assert.assertEquals( (short) 34, getter( Target.class, "age" ).get( target ) ); - Assert.assertEquals( "John Doe", getter( Target.class, "name" ).get( target ) ); + assertThat( getter( Target.class, "active" ).get( target ) ).isEqualTo( true ); + assertThat( getter( Target.class, "children" ).get( target ) ).isEqualTo( (byte) 2 ); + assertThat( getter( Target.class, "gender" ).get( target ) ).isEqualTo( 'M' ); + assertThat( getter( Target.class, "code" ).get( target ) ).isEqualTo( Integer.MAX_VALUE ); + assertThat( getter( Target.class, "id" ).get( target ) ).isEqualTo( Long.MAX_VALUE ); + assertThat( getter( Target.class, "age" ).get( target ) ).isEqualTo( (short) 34 ); + assertThat( getter( Target.class, "name" ).get( target ) ).isEqualTo( "John Doe" ); } private static class Target { @@ -85,14 +83,14 @@ public void getThrowing() { assertThatThrownBy( () -> runtimeException.get( target ) ) .isInstanceOf( PropertyAccessException.class ) .hasMessage( "Exception occurred inside: '" + TargetThrowingExceptions.class.getName() +".runtimeException' (getter)" ) - .getCause() // Not the root cause, the *direct* cause! We don't want extra wrapping. + .cause() // Not the root cause, the *direct* cause! We don't want extra wrapping. .isExactlyInstanceOf( RuntimeException.class ); Getter checkedException = getter( TargetThrowingExceptions.class, "checkedException" ); assertThatThrownBy( () -> checkedException.get( target ) ) .isInstanceOf( PropertyAccessException.class ) .hasMessage( "Exception occurred inside: '" + TargetThrowingExceptions.class.getName() +".checkedException' (getter)" ) - .getCause() // Not the root cause, the *direct* cause! We don't want extra wrapping. + .cause() // Not the root cause, the *direct* cause! We don't want extra wrapping. .isExactlyInstanceOf( Exception.class ); Getter error = getter( TargetThrowingExceptions.class, "error" ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/property/access/spi/SetterMethodImplTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/property/access/spi/SetterMethodImplTest.java index e8a1665302c4..273c41a523a8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/property/access/spi/SetterMethodImplTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/property/access/spi/SetterMethodImplTest.java @@ -4,17 +4,17 @@ */ package org.hibernate.orm.test.property.access.spi; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.lang.reflect.Method; - import org.hibernate.PropertyAccessException; import org.hibernate.internal.util.ReflectHelper; import org.hibernate.property.access.spi.Setter; import org.hibernate.property.access.spi.SetterMethodImpl; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Method; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; -import org.junit.Assert; -import org.junit.Test; public class SetterMethodImplTest { @@ -23,19 +23,19 @@ public void set() throws Exception { Target target = new Target(); setter( Target.class, "active", boolean.class ).set( target, true ); - Assert.assertEquals( true, target.active ); + assertThat( target.active ).isEqualTo( true ); setter( Target.class, "children", byte.class ).set( target, (byte) 2 ); - Assert.assertEquals( (byte) 2, target.children ); + assertThat( target.children ).isEqualTo( (byte) 2 ); setter( Target.class, "gender", char.class ).set( target, 'M' ); - Assert.assertEquals( 'M', target.gender ); + assertThat( target.gender ).isEqualTo( 'M' ); setter( Target.class, "code", int.class ).set( target, Integer.MAX_VALUE ); - Assert.assertEquals( Integer.MAX_VALUE, target.code ); + assertThat( target.code ).isEqualTo( Integer.MAX_VALUE ); setter( Target.class, "id", long.class ).set( target, Long.MAX_VALUE ); - Assert.assertEquals( Long.MAX_VALUE, target.id ); + assertThat( target.id ).isEqualTo( Long.MAX_VALUE ); setter( Target.class, "age", short.class ).set( target, (short) 34 ); - Assert.assertEquals( (short) 34, target.age ); + assertThat( target.age ).isEqualTo( (short) 34 ); setter( Target.class, "name", String.class ).set( target, "John Doe" ); - Assert.assertEquals( "John Doe", target.name ); + assertThat( target.name ).isEqualTo( "John Doe" ); } private static class Target { @@ -90,15 +90,17 @@ public void setThrowing() { Setter runtimeException = setter( TargetThrowingExceptions.class, "runtimeException", String.class ); assertThatThrownBy( () -> runtimeException.set( target, "foo" ) ) .isInstanceOf( PropertyAccessException.class ) - .hasMessage( "Exception occurred inside: '" + TargetThrowingExceptions.class.getName() +".runtimeException' (setter)" ) - .getCause() // Not the root cause, the *direct* cause! We don't want extra wrapping. + .hasMessage( + "Exception occurred inside: '" + TargetThrowingExceptions.class.getName() + ".runtimeException' (setter)" ) + .cause() // Not the root cause, the *direct* cause! We don't want extra wrapping. .isExactlyInstanceOf( RuntimeException.class ); Setter checkedException = setter( TargetThrowingExceptions.class, "checkedException", String.class ); assertThatThrownBy( () -> checkedException.set( target, "foo" ) ) .isInstanceOf( PropertyAccessException.class ) - .hasMessage( "Exception occurred inside: '" + TargetThrowingExceptions.class.getName() +".checkedException' (setter)" ) - .getCause() // Not the root cause, the *direct* cause! We don't want extra wrapping. + .hasMessage( + "Exception occurred inside: '" + TargetThrowingExceptions.class.getName() + ".checkedException' (setter)" ) + .cause() // Not the root cause, the *direct* cause! We don't want extra wrapping. .isExactlyInstanceOf( Exception.class ); Setter error = setter( TargetThrowingExceptions.class, "error", String.class ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/Container.java b/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/Container.java index be7b578b253f..93710994cd28 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/Container.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/Container.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.proxy; + import java.io.Serializable; import java.util.HashSet; import java.util.Set; @@ -15,7 +16,7 @@ public class Container implements Serializable { private String name; private Owner owner; private Info info; - private Set dataPoints = new HashSet(); + private Set dataPoints = new HashSet<>(); public Container() { } @@ -56,11 +57,11 @@ public void setInfo(Info info) { this.info = info; } - public Set getDataPoints() { + public Set getDataPoints() { return dataPoints; } - public void setDataPoints(Set dataPoints) { + public void setDataPoints(Set dataPoints) { this.dataPoints = dataPoints; } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/MultipleSessionFactoriesProxyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/MultipleSessionFactoriesProxyTest.java index ca82420f621c..65aa651e4adc 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/MultipleSessionFactoriesProxyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/MultipleSessionFactoriesProxyTest.java @@ -4,21 +4,22 @@ */ package org.hibernate.orm.test.proxy; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.math.BigDecimal; - import org.hibernate.Hibernate; -import org.hibernate.Session; -import org.hibernate.Transaction; +import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.internal.util.SerializationHelper; - +import org.hibernate.orm.test.annotations.embeddables.Investor; +import org.hibernate.orm.test.annotations.embeddables.InvestorTypeContributor; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.util.ServiceRegistryUtil; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.math.BigDecimal; + +import static org.assertj.core.api.Assertions.assertThat; /** * This integration test verifies that serialized entities @@ -30,67 +31,76 @@ * * @author Marcel Overdijk */ -public class MultipleSessionFactoriesProxyTest extends BaseCoreFunctionalTestCase { - - @Override - public String[] getMappings() { - return new String[] { "proxy/DataPoint.hbm.xml" }; - } - - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } - - @Override - public void configure(Configuration cfg) { - super.configure( cfg ); - cfg.setProperty( Environment.SESSION_FACTORY_NAME, "sf-name" ); // explicitly define the session factory name - cfg.setProperty( Environment.SESSION_FACTORY_NAME_IS_JNDI, false ); // do not bind it to jndi +public class MultipleSessionFactoriesProxyTest { + + private SessionFactory produceSessionFactory() { + try (InputStream is = Thread.currentThread().getContextClassLoader() + .getResourceAsStream( "org/hibernate/orm/test/proxy/DataPoint.hbm.xml" )) { + final Configuration cfg = new Configuration() + .addInputStream( is ) + .addAnnotatedClass( Investor.class ) + .registerTypeContributor( new InvestorTypeContributor() ) + .setProperty( Environment.HBM2DDL_AUTO, "create-drop" ) + .setProperty( Environment.SESSION_FACTORY_NAME, "sf-name" ) + .setProperty( Environment.SESSION_FACTORY_NAME, "sf-name" ); + ServiceRegistryUtil.applySettings( cfg.getStandardServiceRegistryBuilder() ); + return cfg.buildSessionFactory(); + } + catch (IOException e) { + throw new IllegalArgumentException( e ); + } } @Test @JiraKey(value = "HHH-17172") public void testProxySerializationWithMultipleSessionFactories() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Container container = new Container( "container" ); - container.setOwner( new Owner( "owner" ) ); - container.setInfo( new Info( "blah blah blah" ) ); - container.getDataPoints().add( new DataPoint( new BigDecimal( 1 ), new BigDecimal( 1 ), "first data point" ) ); - container.getDataPoints().add( new DataPoint( new BigDecimal( 2 ), new BigDecimal( 2 ), "second data point" ) ); - s.persist( container ); - s.flush(); - s.clear(); - - container = s.getReference( Container.class, container.getId() ); - assertFalse( Hibernate.isInitialized( container ) ); - container.getId(); - assertFalse( Hibernate.isInitialized( container ) ); - container.getName(); - assertTrue( Hibernate.isInitialized( container ) ); - - t.commit(); - s.close(); - - // Serialize the container. - byte[] bytes = SerializationHelper.serialize( container ); - - // Now deserialize, which works at this stage, because the session factory UUID in the - // serialized object is the same as the current session factory. - SerializationHelper.deserialize( bytes ); - - // Now rebuild the session factory (it will get a new unique UUID). - // As configured for this test an explicit session factory name is used ("sf-name"), - // so we would expect the deserialization to work after rebuilding the session factory. - // Rebuilding the session factory simulates multiple JVM instances with different session - // factories (different UUID's, but same name!) trying to deserialize objects from a - // centralized cache (e.g. Hazelcast). - rebuildSessionFactory(); - - // And this should be possible now: even though we lack of a matching session factory by - // UUID, it should seek a match by using the session factory name as valid alternative. - SerializationHelper.deserialize( bytes ); + SessionFactory sf = produceSessionFactory(); + try { + Container c = sf.fromTransaction( + session -> { + Container container = new Container( "container" ); + container.setOwner( new Owner( "owner" ) ); + container.setInfo( new Info( "blah blah blah" ) ); + container.getDataPoints() + .add( new DataPoint( new BigDecimal( 1 ), new BigDecimal( 1 ), "first data point" ) ); + container.getDataPoints() + .add( new DataPoint( new BigDecimal( 2 ), new BigDecimal( 2 ), "second data point" ) ); + session.persist( container ); + session.flush(); + session.clear(); + + container = session.getReference( Container.class, container.getId() ); + assertThat( Hibernate.isInitialized( container ) ).isFalse(); + container.getId(); + assertThat( Hibernate.isInitialized( container ) ).isFalse(); + container.getName(); + assertThat( Hibernate.isInitialized( container ) ).isTrue(); + return container; + } + ); + // Serialize the container. + byte[] bytes = SerializationHelper.serialize( c ); + + // Now deserialize, which works at this stage, because the session factory UUID in the + // serialized object is the same as the current session factory. + SerializationHelper.deserialize( bytes ); + + // Now rebuild the session factory (it will get a new unique UUID). + // As configured for this test an explicit session factory name is used ("sf-name"), + // so we would expect the deserialization to work after rebuilding the session factory. + // Rebuilding the session factory simulates multiple JVM instances with different session + // factories (different UUID's, but same name!) trying to deserialize objects from a + // centralized cache (e.g. Hazelcast). + sf.close(); + produceSessionFactory(); + + // And this should be possible now: even though we lack of a matching session factory by + // UUID, it should seek a match by using the session factory name as valid alternative. + SerializationHelper.deserialize( bytes ); + } + finally { + sf.close(); + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/ProxyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/ProxyTest.java index 479474e945af..be7adc1e5664 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/ProxyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/ProxyTest.java @@ -10,553 +10,555 @@ import org.hibernate.LockMode; import org.hibernate.ObjectNotFoundException; import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.internal.SessionImpl; import org.hibernate.internal.util.SerializationHelper; import org.hibernate.proxy.HibernateProxy; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -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.math.BigDecimal; import java.util.List; -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.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Gavin King */ -public class ProxyTest extends BaseCoreFunctionalTestCase { - @Override - public String[] getMappings() { - return new String[] { "proxy/DataPoint.hbm.xml" }; - } - - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } - - @Override - public void configure(Configuration cfg) { - super.configure( cfg ); - cfg.setProperty( Environment.STATEMENT_BATCH_SIZE, 0 ); // problem on HSQLDB (go figure) +@DomainModel( + xmlMappings = "org/hibernate/orm/test/proxy/DataPoint.hbm.xml" +) +@SessionFactory +@ServiceRegistry( + settings = @Setting(name = Environment.STATEMENT_BATCH_SIZE, value = "0") +) +public class ProxyTest { + + @AfterEach + public void tearDown(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Test - public void testFinalizeFiltered() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - DataPoint dp = new DataPoint(); - dp.setDescription("a data point"); - dp.setX( new BigDecimal("1.0") ); - dp.setY( new BigDecimal("2.0") ); - s.persist(dp); - s.flush(); - s.clear(); - - dp = s.getReference(DataPoint.class, dp.getId()); - assertFalse( Hibernate.isInitialized(dp) ); - - try { - dp.getClass().getDeclaredMethod( "finalize", (Class[]) null ); - fail(); - - } - catch (NoSuchMethodException e) {} - - s.remove(dp); - t.commit(); - s.close(); - + public void testFinalizeFiltered(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + DataPoint dp = new DataPoint(); + dp.setDescription( "a data point" ); + dp.setX( new BigDecimal( "1.0" ) ); + dp.setY( new BigDecimal( "2.0" ) ); + session.persist( dp ); + session.flush(); + session.clear(); + + DataPoint d = session.getReference( DataPoint.class, dp.getId() ); + assertThat( Hibernate.isInitialized( d ) ).isFalse(); + + assertThrows( NoSuchMethodException.class, () -> + d.getClass().getDeclaredMethod( "finalize", (Class[]) null ) + ); + + session.remove( d ); + } + ); } @Test - public void testProxyException() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - DataPoint dp = new DataPoint(); - dp.setDescription("a data point"); - dp.setX( new BigDecimal("1.0") ); - dp.setY( new BigDecimal("2.0") ); - s.persist(dp); - s.flush(); - s.clear(); - - dp = s.getReference( DataPoint.class, dp.getId() ); - assertFalse( Hibernate.isInitialized(dp) ); - - try { - dp.exception(); - fail(); - } - catch (Exception e) { - assertTrue( e.getClass()==Exception.class ); - } - s.remove(dp); - t.commit(); - s.close(); + public void testProxyException(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + DataPoint dp = new DataPoint(); + dp.setDescription( "a data point" ); + dp.setX( new BigDecimal( "1.0" ) ); + dp.setY( new BigDecimal( "2.0" ) ); + session.persist( dp ); + session.flush(); + session.clear(); + + DataPoint d = session.getReference( DataPoint.class, dp.getId() ); + assertThat( Hibernate.isInitialized( d ) ).isFalse(); + + assertThrows( Exception.class, () -> d.exception() ); + + session.remove( d ); + } + ); } @Test - public void testProxyExceptionWithNewGetReference() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - DataPoint dp = new DataPoint(); - dp.setDescription("a data point"); - dp.setX( new BigDecimal("1.0") ); - dp.setY( new BigDecimal("2.0") ); - s.persist(dp); - s.flush(); - s.clear(); - - dp = s.getReference(dp); - assertFalse( Hibernate.isInitialized(dp) ); - - try { - dp.exception(); - fail(); - } - catch (Exception e) { - assertTrue( e.getClass()==Exception.class ); - } - s.remove(dp); - t.commit(); - s.close(); + public void testProxyExceptionWithNewGetReference(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + DataPoint dp = new DataPoint(); + dp.setDescription( "a data point" ); + dp.setX( new BigDecimal( "1.0" ) ); + dp.setY( new BigDecimal( "2.0" ) ); + session.persist( dp ); + session.flush(); + session.clear(); + + DataPoint d = session.getReference( dp ); + assertThat( Hibernate.isInitialized( d ) ).isFalse(); + + assertThrows( Exception.class, () -> d.exception() ); + + session.remove( d ); + } + ); } @Test - public void testProxyExceptionWithOldGetReference() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - DataPoint dp = new DataPoint(); - dp.setDescription("a data point"); - dp.setX( new BigDecimal("1.0") ); - dp.setY( new BigDecimal("2.0") ); - s.persist(dp); - s.flush(); - s.clear(); - - dp = s.getReference( DataPoint.class, dp.getId() ); - assertFalse( Hibernate.isInitialized(dp) ); - - try { - dp.exception(); - fail(); - } - catch (Exception e) { - assertTrue( e.getClass()==Exception.class ); - } - s.remove(dp); - t.commit(); - s.close(); + public void testProxyExceptionWithOldGetReference(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + DataPoint dp = new DataPoint(); + dp.setDescription( "a data point" ); + dp.setX( new BigDecimal( "1.0" ) ); + dp.setY( new BigDecimal( "2.0" ) ); + session.persist( dp ); + session.flush(); + session.clear(); + + DataPoint d = session.getReference( DataPoint.class, dp.getId() ); + assertThat( Hibernate.isInitialized( d ) ).isFalse(); + + assertThrows( Exception.class, () -> d.exception() ); + + session.remove( d ); + } + ); } @Test - public void testProxySerializationAfterSessionClosed() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - DataPoint dp = new DataPoint(); - dp.setDescription("a data point"); - dp.setX( new BigDecimal("1.0") ); - dp.setY( new BigDecimal("2.0") ); - s.persist(dp); - s.flush(); - s.clear(); - - dp = s.getReference( DataPoint.class, dp.getId()); - assertFalse( Hibernate.isInitialized(dp) ); - s.close(); - SerializationHelper.clone( dp ); + public void testProxySerializationAfterSessionClosed(SessionFactoryScope scope) { + DataPoint d = scope.fromTransaction( + session -> { + DataPoint dp = new DataPoint(); + dp.setDescription( "a data point" ); + dp.setX( new BigDecimal( "1.0" ) ); + dp.setY( new BigDecimal( "2.0" ) ); + session.persist( dp ); + session.flush(); + session.clear(); + + dp = session.getReference( DataPoint.class, dp.getId() ); + assertThat( Hibernate.isInitialized( dp ) ).isFalse(); + return dp; + } + ); + SerializationHelper.clone( d ); - s = openSession(); - t = s.beginTransaction(); - s.remove( dp ); - t.commit(); - s.close(); + scope.inTransaction( session -> session.remove( d ) ); } @Test - public void testInitializedProxySerializationAfterSessionClosed() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - DataPoint dp = new DataPoint(); - dp.setDescription("a data point"); - dp.setX( new BigDecimal("1.0") ); - dp.setY( new BigDecimal("2.0") ); - s.persist(dp); - s.flush(); - s.clear(); + public void testInitializedProxySerializationAfterSessionClosed(SessionFactoryScope scope) { + DataPoint d = scope.fromTransaction( + session -> { + DataPoint dp = new DataPoint(); + dp.setDescription( "a data point" ); + dp.setX( new BigDecimal( "1.0" ) ); + dp.setY( new BigDecimal( "2.0" ) ); + session.persist( dp ); + session.flush(); + session.clear(); + + dp = session.getReference( DataPoint.class, dp.getId() ); + assertThat( Hibernate.isInitialized( dp ) ).isFalse(); + Hibernate.initialize( dp ); + assertThat( Hibernate.isInitialized( dp ) ).isTrue(); + return dp; + } + ); + SerializationHelper.clone( d ); - dp = s.getReference( DataPoint.class, dp.getId()); - assertFalse( Hibernate.isInitialized(dp) ); - Hibernate.initialize( dp ); - assertTrue( Hibernate.isInitialized(dp) ); - s.close(); - SerializationHelper.clone( dp ); - - s = openSession(); - t = s.beginTransaction(); - s.remove( dp ); - t.commit(); - s.close(); + scope.inTransaction( session -> session.remove( d ) ); } @Test - public void testProxySerialization() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - DataPoint dp = new DataPoint(); - dp.setDescription("a data point"); - dp.setX( new BigDecimal("1.0") ); - dp.setY( new BigDecimal("2.0") ); - s.persist(dp); - s.flush(); - s.clear(); - - dp = s.getReference( DataPoint.class, dp.getId()); - assertFalse( Hibernate.isInitialized(dp) ); - dp.getId(); - assertFalse( Hibernate.isInitialized(dp) ); - dp.getDescription(); - assertTrue( Hibernate.isInitialized(dp) ); - Object none = s.getReference( DataPoint.class, 666L); - assertFalse( Hibernate.isInitialized(none) ); - - t.commit(); - s.unwrap( SessionImplementor.class ).getJdbcCoordinator().getLogicalConnection().manualDisconnect(); - - Object[] holder = new Object[] { s, dp, none }; + public void testProxySerialization(SessionFactoryScope scope) { + Session s = scope.getSessionFactory().openSession(); + Session sclone = null; + try { + s.beginTransaction(); + DataPoint dp = new DataPoint(); + Object none = null; + try { + dp.setDescription( "a data point" ); + dp.setX( new BigDecimal( "1.0" ) ); + dp.setY( new BigDecimal( "2.0" ) ); + s.persist( dp ); + s.flush(); + s.clear(); + + dp = s.getReference( DataPoint.class, dp.getId() ); + assertThat( Hibernate.isInitialized( dp ) ).isFalse(); + dp.getId(); + assertThat( Hibernate.isInitialized( dp ) ).isFalse(); + dp.getDescription(); + assertThat( Hibernate.isInitialized( dp ) ).isTrue(); + none = s.getReference( DataPoint.class, 666L ); + + assertThat( Hibernate.isInitialized( none ) ).isFalse(); + + s.getTransaction().commit(); + } + finally { + if ( s.getTransaction().isActive() ) { + s.getTransaction().rollback(); + } + } + s.unwrap( SessionImplementor.class ).getJdbcCoordinator().getLogicalConnection().manualDisconnect(); - holder = (Object[]) SerializationHelper.clone(holder); - Session sclone = (Session) holder[0]; - dp = (DataPoint) holder[1]; - none = holder[2]; + Object[] holder = new Object[] {s, dp, none}; - //close the original: - s.close(); + holder = (Object[]) SerializationHelper.clone( holder ); + sclone = (Session) holder[0]; + dp = (DataPoint) holder[1]; + none = holder[2]; - t = sclone.beginTransaction(); + //close the original: + s.close(); + try { + sclone.beginTransaction(); - DataPoint sdp = sclone.getReference( DataPoint.class, dp.getId()); - assertSame(dp, sdp); - assertFalse(sdp instanceof HibernateProxy); - Object snone = sclone.getReference( DataPoint.class, 666L); - assertSame(none, snone); - assertTrue(snone instanceof HibernateProxy); + DataPoint sdp = sclone.getReference( DataPoint.class, dp.getId() ); + assertThat( sdp ).isSameAs( dp ); + assertThat( sdp ).isNotInstanceOf( HibernateProxy.class ); + Object snone = sclone.getReference( DataPoint.class, 666L ); + assertThat( snone ).isSameAs( none ); + assertThat( snone ).isInstanceOf( HibernateProxy.class ); - sclone.remove(dp); + sclone.remove( dp ); - t.commit(); - sclone.close(); + sclone.getTransaction().commit(); + } + finally { + if ( sclone.getTransaction().isActive() ) { + sclone.getTransaction().rollback(); + } + } + } + finally { + if ( s.isOpen() ) { + s.close(); + } + if ( sclone != null && sclone.isOpen() ) { + sclone.close(); + } + } } @Test - public void testProxy() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - DataPoint dp = new DataPoint(); - dp.setDescription("a data point"); - dp.setX( new BigDecimal("1.0") ); - dp.setY( new BigDecimal("2.0") ); - s.persist(dp); - s.flush(); - s.clear(); - - dp = s.getReference( DataPoint.class, dp.getId()); - assertFalse( Hibernate.isInitialized(dp) ); - DataPoint dp2 = s.get( DataPoint.class, dp.getId()); - assertSame(dp, dp2); - assertTrue( Hibernate.isInitialized(dp) ); - s.clear(); - - dp = s.getReference( DataPoint.class, dp.getId()); - assertFalse( Hibernate.isInitialized(dp) ); - dp2 = s.getReference( DataPoint.class, dp.getId() ); - assertSame(dp, dp2); - assertFalse( Hibernate.isInitialized(dp) ); - s.clear(); - - dp = s.getReference( DataPoint.class, dp.getId()); - assertFalse( Hibernate.isInitialized(dp) ); - dp2 = s.get( DataPoint.class, dp.getId(), LockMode.READ ); - assertSame(dp, dp2); - assertTrue( Hibernate.isInitialized(dp) ); - s.clear(); - - dp = s.getReference( DataPoint.class, dp.getId()); - assertFalse( Hibernate.isInitialized(dp) ); - dp2 = s.find( DataPoint.class, dp.getId(), LockMode.READ ); - assertSame(dp, dp2); - assertTrue( Hibernate.isInitialized(dp) ); - s.clear(); - - dp = s.getReference( DataPoint.class, dp.getId()); - assertFalse( Hibernate.isInitialized(dp) ); - dp2 = (DataPoint) s.createQuery("from DataPoint").uniqueResult(); - assertSame(dp, dp2); - assertTrue( Hibernate.isInitialized(dp) ); - s.remove( dp ); - t.commit(); - s.close(); + public void testProxy(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + DataPoint dp = new DataPoint(); + dp.setDescription( "a data point" ); + dp.setX( new BigDecimal( "1.0" ) ); + dp.setY( new BigDecimal( "2.0" ) ); + session.persist( dp ); + session.flush(); + session.clear(); + + dp = session.getReference( DataPoint.class, dp.getId() ); + assertThat( Hibernate.isInitialized( dp ) ).isFalse(); + DataPoint dp2 = session.get( DataPoint.class, dp.getId() ); + assertThat( dp2 ).isSameAs( dp ); + assertThat( Hibernate.isInitialized( dp ) ).isTrue(); + session.clear(); + + dp = session.getReference( DataPoint.class, dp.getId() ); + assertThat( Hibernate.isInitialized( dp ) ).isFalse(); + dp2 = session.getReference( DataPoint.class, dp.getId() ); + assertThat( dp2 ).isSameAs( dp ); + assertThat( Hibernate.isInitialized( dp ) ).isFalse(); + session.clear(); + + dp = session.getReference( DataPoint.class, dp.getId() ); + assertThat( Hibernate.isInitialized( dp ) ).isFalse(); + dp2 = session.get( DataPoint.class, dp.getId(), LockMode.READ ); + assertThat( dp2 ).isSameAs( dp ); + assertThat( Hibernate.isInitialized( dp ) ).isTrue(); + session.clear(); + + dp = session.getReference( DataPoint.class, dp.getId() ); + assertThat( Hibernate.isInitialized( dp ) ).isFalse(); + dp2 = session.find( DataPoint.class, dp.getId(), LockMode.READ ); + assertThat( dp2 ).isSameAs( dp ); + assertThat( Hibernate.isInitialized( dp ) ).isTrue(); + session.clear(); + + dp = session.getReference( DataPoint.class, dp.getId() ); + assertThat( Hibernate.isInitialized( dp ) ).isFalse(); + dp2 = session.createQuery( "from DataPoint", DataPoint.class ).uniqueResult(); + assertThat( dp2 ).isSameAs( dp ); + assertThat( Hibernate.isInitialized( dp ) ).isTrue(); + session.remove( dp ); + } + ); } @Test - public void testProxyWithGetReference() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - DataPoint dp = new DataPoint(); - dp.setDescription("a data point"); - dp.setX( new BigDecimal("1.0") ); - dp.setY( new BigDecimal("2.0") ); - s.persist(dp); - s.flush(); - s.clear(); - - dp = s.getReference( DataPoint.class, dp.getId() ); - assertFalse( Hibernate.isInitialized(dp) ); - DataPoint dp2 = s.get( DataPoint.class, dp.getId() ); - assertSame(dp, dp2); - assertTrue( Hibernate.isInitialized(dp) ); - s.clear(); - - dp = s.getReference( DataPoint.class, dp.getId() ); - assertFalse( Hibernate.isInitialized(dp) ); - dp2 = s.getReference( DataPoint.class, dp.getId() ); - assertSame(dp, dp2); - assertFalse( Hibernate.isInitialized(dp) ); - s.clear(); - - dp = s.getReference( dp ); - assertFalse( Hibernate.isInitialized(dp) ); - dp2 = s.getReference( dp ); - assertSame(dp, dp2); - assertFalse( Hibernate.isInitialized(dp) ); - s.clear(); - - dp = s.getReference( DataPoint.class, dp.getId() ); - assertFalse( Hibernate.isInitialized(dp) ); - dp2 = s.find( DataPoint.class, dp.getId(), LockMode.READ ); - assertSame(dp, dp2); - assertTrue( Hibernate.isInitialized(dp) ); - s.clear(); - - dp = s.getReference( DataPoint.class, dp.getId() ); - assertFalse( Hibernate.isInitialized(dp) ); - dp2 = (DataPoint) s.createQuery("from DataPoint").uniqueResult(); - assertSame(dp, dp2); - assertTrue( Hibernate.isInitialized(dp) ); - s.remove( dp ); - t.commit(); - s.close(); + public void testProxyWithGetReference(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + DataPoint dp = new DataPoint(); + dp.setDescription( "a data point" ); + dp.setX( new BigDecimal( "1.0" ) ); + dp.setY( new BigDecimal( "2.0" ) ); + session.persist( dp ); + session.flush(); + session.clear(); + + dp = session.getReference( DataPoint.class, dp.getId() ); + assertThat( Hibernate.isInitialized( dp ) ).isFalse(); + DataPoint dp2 = session.get( DataPoint.class, dp.getId() ); + assertThat( dp2 ).isSameAs( dp ); + assertThat( Hibernate.isInitialized( dp ) ).isTrue(); + session.clear(); + + dp = session.getReference( DataPoint.class, dp.getId() ); + assertThat( Hibernate.isInitialized( dp ) ).isFalse(); + dp2 = session.getReference( DataPoint.class, dp.getId() ); + assertThat( dp2 ).isSameAs( dp ); + assertThat( Hibernate.isInitialized( dp ) ).isFalse(); + session.clear(); + + dp = session.getReference( dp ); + assertThat( Hibernate.isInitialized( dp ) ).isFalse(); + dp2 = session.getReference( dp ); + assertThat( dp2 ).isSameAs( dp ); + assertThat( Hibernate.isInitialized( dp ) ).isFalse(); + session.clear(); + + dp = session.getReference( DataPoint.class, dp.getId() ); + assertThat( Hibernate.isInitialized( dp ) ).isFalse(); + dp2 = session.find( DataPoint.class, dp.getId(), LockMode.READ ); + assertThat( dp2 ).isSameAs( dp ); + assertThat( Hibernate.isInitialized( dp ) ).isTrue(); + session.clear(); + + dp = session.getReference( DataPoint.class, dp.getId() ); + assertThat( Hibernate.isInitialized( dp ) ).isFalse(); + dp2 = session.createQuery( "from DataPoint", DataPoint.class ).uniqueResult(); + assertThat( dp2 ).isSameAs( dp ); + assertThat( Hibernate.isInitialized( dp ) ).isTrue(); + session.remove( dp ); + } + ); } @Test - public void testSubsequentNonExistentProxyAccess() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - DataPoint proxy = s.getReference( DataPoint.class, (long) -1); - assertFalse( Hibernate.isInitialized( proxy ) ); - try { - proxy.getDescription(); - fail( "proxy access did not fail on non-existent proxy" ); - } - catch( ObjectNotFoundException onfe ) { - // expected - } - catch( Throwable e ) { - fail( "unexpected exception type on non-existent proxy access : " + e ); - } - // try it a second (subsequent) time... - try { - proxy.getDescription(); - fail( "proxy access did not fail on non-existent proxy" ); - } - catch( ObjectNotFoundException onfe ) { - // expected - } - catch( Throwable e ) { - fail( "unexpected exception type on non-existent proxy access : " + e ); - } - - t.commit(); - s.close(); + public void testSubsequentNonExistentProxyAccess(SessionFactoryScope scope) { + + scope.inTransaction( + session -> { + DataPoint proxy = session.getReference( DataPoint.class, (long) -1 ); + assertThat( Hibernate.isInitialized( proxy ) ).isFalse(); + try { + proxy.getDescription(); + fail( "proxy access did not fail on non-existent proxy" ); + } + catch (ObjectNotFoundException onfe) { + // expected + } + catch (Throwable e) { + fail( "unexpected exception type on non-existent proxy access : " + e ); + } + // try it a second (subsequent) time... + try { + proxy.getDescription(); + fail( "proxy access did not fail on non-existent proxy" ); + } + catch (ObjectNotFoundException onfe) { + // expected + } + catch (Throwable e) { + fail( "unexpected exception type on non-existent proxy access : " + e ); + } + } + ); } - @SuppressWarnings( {"unchecked"}) + @SuppressWarnings({"unchecked"}) @Test - public void testProxyEviction() { - Session s = openSession(); - Transaction t = s.beginTransaction(); + public void testProxyEviction(SessionFactoryScope scope) { Container container = new Container( "container" ); - container.setOwner( new Owner( "owner" ) ); - container.setInfo( new Info( "blah blah blah" ) ); - container.getDataPoints().add( new DataPoint( new BigDecimal( 1 ), new BigDecimal( 1 ), "first data point" ) ); - container.getDataPoints().add( new DataPoint( new BigDecimal( 2 ), new BigDecimal( 2 ), "second data point" ) ); - s.persist( container ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - Container c = s.getReference( Container.class, container.getId() ); - assertFalse( Hibernate.isInitialized( c ) ); - s.evict( c ); - try { - c.getName(); - fail( "expecting LazyInitializationException" ); - } - catch( LazyInitializationException e ) { - // expected result - } - - c = s.getReference( Container.class, container.getId() ); - assertFalse( Hibernate.isInitialized( c ) ); - Info i = c.getInfo(); - assertTrue( Hibernate.isInitialized( c ) ); - assertFalse( Hibernate.isInitialized( i ) ); - s.evict( c ); - try { - i.getDetails(); - fail( "expecting LazyInitializationException" ); - } - catch( LazyInitializationException e ) { - // expected result - } - - s.remove( c ); + scope.inTransaction( + session -> { + container.setOwner( new Owner( "owner" ) ); + container.setInfo( new Info( "blah blah blah" ) ); + container.getDataPoints() + .add( new DataPoint( new BigDecimal( 1 ), new BigDecimal( 1 ), "first data point" ) ); + container.getDataPoints() + .add( new DataPoint( new BigDecimal( 2 ), new BigDecimal( 2 ), "second data point" ) ); + session.persist( container ); + } + ); - t.commit(); - s.close(); + scope.inTransaction( + session -> { + Container c = session.getReference( Container.class, container.getId() ); + assertThat( Hibernate.isInitialized( c ) ).isFalse(); + session.evict( c ); + try { + c.getName(); + fail( "expecting LazyInitializationException" ); + } + catch (LazyInitializationException e) { + // expected result + } + + c = session.getReference( Container.class, container.getId() ); + assertThat( Hibernate.isInitialized( c ) ).isFalse(); + Info i = c.getInfo(); + assertThat( Hibernate.isInitialized( c ) ).isTrue(); + assertThat( Hibernate.isInitialized( i ) ).isFalse(); + session.evict( c ); + try { + i.getDetails(); + fail( "expecting LazyInitializationException" ); + } + catch (LazyInitializationException e) { + // expected result + } + + session.remove( c ); + } + ); } @Test - public void testFullyLoadedPCSerialization() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Long lastContainerId = null; + public void testFullyLoadedPCSerialization(SessionFactoryScope scope) { int containerCount = 10; int nestedDataPointCount = 5; - for ( int c_indx = 0; c_indx < containerCount; c_indx++ ) { - Owner owner = new Owner( "Owner #" + c_indx ); - Container container = new Container( "Container #" + c_indx ); - container.setOwner( owner ); - for ( int dp_indx = 0; dp_indx < nestedDataPointCount; dp_indx++ ) { - DataPoint dp = new DataPoint(); - dp.setDescription( "data-point [" + c_indx + ", " + dp_indx + "]" ); -// more HSQLDB fun... -// dp.setX( new BigDecimal( c_indx ) ); - dp.setX( new BigDecimal( c_indx + dp_indx ) ); - dp.setY( new BigDecimal( dp_indx ) ); - container.getDataPoints().add( dp ); - } - s.persist( container ); - lastContainerId = container.getId(); - } - t.commit(); - s.close(); - - s = openSession(); - s.setHibernateFlushMode( FlushMode.MANUAL ); - t = s.beginTransaction(); - // load the last container as a proxy - Container proxy = s.getReference( Container.class, lastContainerId ); - assertFalse( Hibernate.isInitialized( proxy ) ); - // load the rest back into the PC - List all = s.createQuery( "from Container as c inner join fetch c.owner inner join fetch c.dataPoints where c.id <> :l" ) - .setParameter( "l", lastContainerId.longValue() ) - .list(); - Container container = ( Container ) all.get( 0 ); - s.remove( container ); - // force a snapshot retrieval of the proxied container - SessionImpl sImpl = ( SessionImpl ) s; - sImpl.getPersistenceContext().getDatabaseSnapshot( - lastContainerId, - sImpl.getFactory().getMappingMetamodel().getEntityDescriptor(Container.class.getName()) + Long lastContainerId = scope.fromTransaction( + session -> { + Long last = 0L; + for ( int c_indx = 0; c_indx < containerCount; c_indx++ ) { + Owner owner = new Owner( "Owner #" + c_indx ); + Container container = new Container( "Container #" + c_indx ); + container.setOwner( owner ); + for ( int dp_indx = 0; dp_indx < nestedDataPointCount; dp_indx++ ) { + DataPoint dp = new DataPoint(); + dp.setDescription( "data-point [" + c_indx + ", " + dp_indx + "]" ); + // more HSQLDB fun... + // dp.setX( new BigDecimal( c_indx ) ); + dp.setX( new BigDecimal( c_indx + dp_indx ) ); + dp.setY( new BigDecimal( dp_indx ) ); + container.getDataPoints().add( dp ); + } + session.persist( container ); + last = container.getId(); + } + return last; + } + ); + + scope.inSession( + session -> { + session.setHibernateFlushMode( FlushMode.MANUAL ); + try { + session.beginTransaction(); + // load the last container as a proxy + Container proxy = session.getReference( Container.class, lastContainerId ); + assertThat( Hibernate.isInitialized( proxy ) ).isFalse(); + // load the rest back into the PC + List all = session.createQuery( + "from Container as c inner join fetch c.owner inner join fetch c.dataPoints where c.id <> :l", + Container.class ) + .setParameter( "l", lastContainerId ) + .list(); + Container container = (Container) all.get( 0 ); + session.remove( container ); + // force a snapshot retrieval of the proxied container + SessionImpl sImpl = (SessionImpl) session; + sImpl.getPersistenceContext().getDatabaseSnapshot( + lastContainerId, + sImpl.getFactory().getMappingMetamodel() + .getEntityDescriptor( Container.class.getName() ) + ); + assertThat( Hibernate.isInitialized( proxy ) ).isFalse(); + session.getTransaction().commit(); + byte[] bytes = SerializationHelper.serialize( session ); + SerializationHelper.deserialize( bytes ); + + session.beginTransaction(); + int count = session.createMutationQuery( "delete DataPoint" ).executeUpdate(); + assertThat( count ) + .describedAs( "unexpected DP delete count" ) + .isEqualTo( containerCount * nestedDataPointCount ); + count = session.createMutationQuery( "delete Container" ).executeUpdate(); + assertThat( count ) + .describedAs( "unexpected container delete count" ) + .isEqualTo( containerCount ); + count = session.createMutationQuery( "delete Owner" ).executeUpdate(); + assertThat( count ) + .describedAs( "unexpected owner delete count" ) + .isEqualTo( containerCount ); + session.getTransaction().commit(); + } + finally { + if ( session.getTransaction().isActive() ) { + session.getTransaction().rollback(); + } + } + } ); - assertFalse( Hibernate.isInitialized( proxy ) ); - t.commit(); - -// int iterations = 50; -// long cumulativeTime = 0; -// long cumulativeSize = 0; -// for ( int i = 0; i < iterations; i++ ) { -// final long start = System.currentTimeMillis(); -// byte[] bytes = SerializationHelper.serialize( s ); -// SerializationHelper.deserialize( bytes ); -// final long end = System.currentTimeMillis(); -// cumulativeTime += ( end - start ); -// int size = bytes.length; -// cumulativeSize += size; -//// System.out.println( "Iteration #" + i + " took " + ( end - start ) + " ms : size = " + size + " bytes" ); -// } -// System.out.println( "Average time : " + ( cumulativeTime / iterations ) + " ms" ); -// System.out.println( "Average size : " + ( cumulativeSize / iterations ) + " bytes" ); - - byte[] bytes = SerializationHelper.serialize( s ); - SerializationHelper.deserialize( bytes ); - - t = s.beginTransaction(); - int count = s.createQuery( "delete DataPoint" ).executeUpdate(); - assertEquals( "unexpected DP delete count", ( containerCount * nestedDataPointCount ), count ); - count = s.createQuery( "delete Container" ).executeUpdate(); - assertEquals( "unexpected container delete count", containerCount, count ); - count = s.createQuery( "delete Owner" ).executeUpdate(); - assertEquals( "unexpected owner delete count", containerCount, count ); - t.commit(); - s.close(); } @Test - public void testRefreshLockInitializedProxy() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - DataPoint dp = newPersistentDataPoint( s ); + public void testRefreshLockInitializedProxy(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + DataPoint dp = newPersistentDataPoint( session ); - dp = s.getReference( DataPoint.class, dp.getId()); - dp.getX(); - assertTrue( Hibernate.isInitialized( dp ) ); + dp = session.getReference( DataPoint.class, dp.getId() ); + dp.getX(); + assertThat( Hibernate.isInitialized( dp ) ).isTrue(); - s.refresh( dp, LockMode.PESSIMISTIC_WRITE ); - assertSame( LockMode.PESSIMISTIC_WRITE, s.getCurrentLockMode( dp ) ); + session.refresh( dp, LockMode.PESSIMISTIC_WRITE ); + assertThat( session.getCurrentLockMode( dp ) ).isSameAs( LockMode.PESSIMISTIC_WRITE ); - s.remove( dp ); - t.commit(); - s.close(); + session.remove( dp ); + } + ); } @Test - @JiraKey( "HHH-1645" ) - public void testRefreshLockUninitializedProxy() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - DataPoint dp = newPersistentDataPoint( s ); + @JiraKey("HHH-1645") + public void testRefreshLockUninitializedProxy(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + DataPoint dp = newPersistentDataPoint( session ); - dp = s.getReference( DataPoint.class, dp.getId()); - assertFalse( Hibernate.isInitialized( dp ) ); + dp = session.getReference( DataPoint.class, dp.getId() ); + assertThat( Hibernate.isInitialized( dp ) ).isFalse(); - s.refresh( dp, LockMode.PESSIMISTIC_WRITE ); - assertSame( LockMode.PESSIMISTIC_WRITE, s.getCurrentLockMode( dp ) ); + session.refresh( dp, LockMode.PESSIMISTIC_WRITE ); + assertThat( session.getCurrentLockMode( dp ) ).isSameAs( LockMode.PESSIMISTIC_WRITE ); - s.remove( dp ); - t.commit(); - s.close(); + session.remove( dp ); + } + ); } private static DataPoint newPersistentDataPoint(Session s) { DataPoint dp = new DataPoint(); dp.setDescription( "a data point" ); - dp.setX( new BigDecimal("1.0") ); - dp.setY( new BigDecimal("2.0") ); + dp.setX( new BigDecimal( "1.0" ) ); + dp.setY( new BigDecimal( "2.0" ) ); s.persist( dp ); s.flush(); s.clear(); @@ -564,36 +566,36 @@ private static DataPoint newPersistentDataPoint(Session s) { } @Test - @JiraKey( "HHH-1645" ) - public void testRefreshLockUninitializedProxyThenRead() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - DataPoint dp = newPersistentDataPoint( s ); - - dp = s.getReference( DataPoint.class, dp.getId()); - assertFalse( Hibernate.isInitialized( dp ) ); - s.refresh( dp, LockMode.PESSIMISTIC_WRITE ); - dp.getX(); - assertSame( LockMode.PESSIMISTIC_WRITE, s.getCurrentLockMode( dp ) ); - - s.remove( dp ); - t.commit(); - s.close(); + @JiraKey("HHH-1645") + public void testRefreshLockUninitializedProxyThenRead(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + DataPoint dp = newPersistentDataPoint( session ); + + dp = session.getReference( DataPoint.class, dp.getId() ); + assertThat( Hibernate.isInitialized( dp ) ).isFalse(); + session.refresh( dp, LockMode.PESSIMISTIC_WRITE ); + dp.getX(); + assertThat( session.getCurrentLockMode( dp ) ).isSameAs( LockMode.PESSIMISTIC_WRITE ); + + session.remove( dp ); + } + ); } @Test - public void testLockUninitializedProxy() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - DataPoint dp = newPersistentDataPoint( s ); - - dp = s.getReference( DataPoint.class, dp.getId()); - assertFalse( Hibernate.isInitialized( dp ) ); - s.lock( dp, LockMode.PESSIMISTIC_WRITE ); - assertSame( LockMode.PESSIMISTIC_WRITE, s.getCurrentLockMode( dp ) ); - - s.remove( dp ); - t.commit(); - s.close(); + public void testLockUninitializedProxy(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + DataPoint dp = newPersistentDataPoint( session ); + + dp = session.getReference( DataPoint.class, dp.getId() ); + assertThat( Hibernate.isInitialized( dp ) ).isFalse(); + session.lock( dp, LockMode.PESSIMISTIC_WRITE ); + assertThat( session.getCurrentLockMode( dp ) ).isSameAs( LockMode.PESSIMISTIC_WRITE ); + + session.remove( dp ); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/concrete/BytecodeConcreteProxyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/concrete/BytecodeConcreteProxyTest.java deleted file mode 100644 index 0d3710295a6e..000000000000 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/concrete/BytecodeConcreteProxyTest.java +++ /dev/null @@ -1,17 +0,0 @@ -/* - * SPDX-License-Identifier: Apache-2.0 - * Copyright Red Hat Inc. and Hibernate Authors - */ -package org.hibernate.orm.test.proxy.concrete; - -import org.hibernate.testing.bytecode.enhancement.BytecodeEnhancerRunner; -import org.junit.runner.RunWith; - -/** - * Version of {@link AbstractConcreteProxyTest} using bytecode-enhanced {@linkplain org.hibernate.proxy.HibernateProxy proxies}. - * - * @author Marco Belladelli - */ -@RunWith( BytecodeEnhancerRunner.class ) -public class BytecodeConcreteProxyTest extends AbstractConcreteProxyTest { -} diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/concrete/AbstractConcreteProxyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/concrete/ConcreteProxyTest.java similarity index 78% rename from hibernate-core/src/test/java/org/hibernate/orm/test/proxy/concrete/AbstractConcreteProxyTest.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/proxy/concrete/ConcreteProxyTest.java index d36c164c4d97..d75af65975f2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/concrete/AbstractConcreteProxyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/concrete/ConcreteProxyTest.java @@ -4,18 +4,6 @@ */ package org.hibernate.orm.test.proxy.concrete; -import org.hibernate.Hibernate; -import org.hibernate.annotations.ConcreteProxy; -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.SessionFactoryBuilder; -import org.hibernate.sql.ast.SqlAstJoinType; - -import org.hibernate.testing.jdbc.SQLStatementInspector; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - import jakarta.persistence.CascadeType; import jakarta.persistence.DiscriminatorColumn; import jakarta.persistence.Entity; @@ -24,6 +12,17 @@ import jakarta.persistence.Inheritance; import jakarta.persistence.InheritanceType; import jakarta.persistence.ManyToOne; +import org.hibernate.Hibernate; +import org.hibernate.annotations.ConcreteProxy; +import org.hibernate.sql.ast.SqlAstJoinType; +import org.hibernate.testing.bytecode.enhancement.extension.BytecodeEnhanced; +import org.hibernate.testing.jdbc.SQLStatementInspector; +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.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.instanceOf; @@ -32,13 +31,42 @@ /** * @author Marco Belladelli */ -public abstract class AbstractConcreteProxyTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + ConcreteProxyTest.SingleParent.class, + ConcreteProxyTest.SingleBase.class, + ConcreteProxyTest.SingleChild1.class, + ConcreteProxyTest.SingleSubChild1.class, + ConcreteProxyTest.SingleChild2.class, + ConcreteProxyTest.JoinedParent.class, + ConcreteProxyTest.JoinedBase.class, + ConcreteProxyTest.JoinedChild1.class, + ConcreteProxyTest.JoinedSubChild1.class, + ConcreteProxyTest.JoinedChild2.class, + ConcreteProxyTest.JoinedDiscParent.class, + ConcreteProxyTest.JoinedDiscBase.class, + ConcreteProxyTest.JoinedDiscChild1.class, + ConcreteProxyTest.JoinedDiscSubChild1.class, + ConcreteProxyTest.JoinedDiscChild2.class, + ConcreteProxyTest.UnionParent.class, + ConcreteProxyTest.UnionBase.class, + ConcreteProxyTest.UnionChild1.class, + ConcreteProxyTest.UnionSubChild1.class, + ConcreteProxyTest.UnionChild2.class + } +) +@SessionFactory( + statementInspectorClass = SQLStatementInspector.class +) +@BytecodeEnhanced(runNotEnhancedAsWell = true) +public class ConcreteProxyTest { + @Test - public void testSingleTable() { - final SQLStatementInspector inspector = getStatementInspector(); + public void testSingleTable(SessionFactoryScope scope) { + final SQLStatementInspector inspector = scope.getStatementInspector( SQLStatementInspector.class ); inspector.clear(); // test find and association - inSession( session -> { + scope.inSession( session -> { //tag::entity-concrete-proxy-find[] final SingleParent parent1 = session.find( SingleParent.class, 1L ); assertThat( parent1.getSingle(), instanceOf( SingleSubChild1.class ) ); @@ -52,7 +80,7 @@ public void testSingleTable() { } ); inspector.clear(); // test query and association - inSession( session -> { + scope.inSession( session -> { final SingleParent parent2 = session.createQuery( "from SingleParent where id = 2", SingleParent.class @@ -67,7 +95,7 @@ public void testSingleTable() { } ); inspector.clear(); // test get reference - inSession( session -> { + scope.inSession( session -> { //tag::entity-concrete-proxy-reference[] final SingleChild1 proxy1 = session.getReference( SingleChild1.class, 1L ); assertThat( proxy1, instanceOf( SingleSubChild1.class ) ); @@ -87,11 +115,11 @@ public void testSingleTable() { } @Test - public void testJoined() { - final SQLStatementInspector inspector = getStatementInspector(); + public void testJoined(SessionFactoryScope scope) { + final SQLStatementInspector inspector = scope.getStatementInspector( SQLStatementInspector.class ); inspector.clear(); // test find and association - inSession( session -> { + scope.inSession( session -> { final JoinedParent parent1 = session.find( JoinedParent.class, 1L ); assertThat( Hibernate.isInitialized( parent1.getJoined() ), is( false ) ); assertThat( parent1.getJoined(), instanceOf( JoinedSubChild1.class ) ); @@ -102,7 +130,7 @@ public void testJoined() { } ); inspector.clear(); // test query and association - inSession( session -> { + scope.inSession( session -> { final JoinedParent parent2 = session.createQuery( "from JoinedParent where id = 2", JoinedParent.class @@ -116,7 +144,7 @@ public void testJoined() { } ); inspector.clear(); // test get reference - inSession( session -> { + scope.inSession( session -> { final JoinedChild1 proxy1 = session.getReference( JoinedChild1.class, 1L ); assertThat( proxy1, instanceOf( JoinedSubChild1.class ) ); assertThat( Hibernate.isInitialized( proxy1 ), is( false ) ); @@ -132,11 +160,11 @@ public void testJoined() { } @Test - public void testJoinedDisc() { - final SQLStatementInspector inspector = getStatementInspector(); + public void testJoinedDisc(SessionFactoryScope scope) { + final SQLStatementInspector inspector = scope.getStatementInspector( SQLStatementInspector.class ); inspector.clear(); // test find and association - inSession( session -> { + scope.inSession( session -> { final JoinedDiscParent parent1 = session.find( JoinedDiscParent.class, 1L ); assertThat( Hibernate.isInitialized( parent1.getJoinedDisc() ), is( false ) ); assertThat( parent1.getJoinedDisc(), instanceOf( JoinedDiscSubChild1.class ) ); @@ -148,7 +176,7 @@ public void testJoinedDisc() { } ); inspector.clear(); // test query and association - inSession( session -> { + scope.inSession( session -> { final JoinedDiscParent parent2 = session.createQuery( "from JoinedDiscParent where id = 2", JoinedDiscParent.class @@ -163,7 +191,7 @@ public void testJoinedDisc() { } ); inspector.clear(); // test get reference - inSession( session -> { + scope.inSession( session -> { final JoinedDiscChild1 proxy1 = session.getReference( JoinedDiscChild1.class, 1L ); assertThat( proxy1, instanceOf( JoinedDiscSubChild1.class ) ); assertThat( Hibernate.isInitialized( proxy1 ), is( false ) ); @@ -181,11 +209,11 @@ public void testJoinedDisc() { } @Test - public void testUnion() { - final SQLStatementInspector inspector = getStatementInspector(); + public void testUnion(SessionFactoryScope scope) { + final SQLStatementInspector inspector = scope.getStatementInspector( SQLStatementInspector.class ); inspector.clear(); // test find and association - inSession( session -> { + scope.inSession( session -> { final UnionParent parent1 = session.find( UnionParent.class, 1L ); assertThat( Hibernate.isInitialized( parent1.getUnion() ), is( false ) ); assertThat( parent1.getUnion(), instanceOf( UnionSubChild1.class ) ); @@ -197,7 +225,7 @@ public void testUnion() { } ); inspector.clear(); // test query and association - inSession( session -> { + scope.inSession( session -> { final UnionParent parent2 = session.createQuery( "from UnionParent where id = 2", UnionParent.class @@ -212,7 +240,7 @@ public void testUnion() { } ); inspector.clear(); // test get reference - inSession( session -> { + scope.inSession( session -> { final UnionChild1 proxy1 = session.getReference( UnionChild1.class, 1L ); assertThat( proxy1, instanceOf( UnionSubChild1.class ) ); assertThat( Hibernate.isInitialized( proxy1 ), is( false ) ); @@ -227,9 +255,9 @@ public void testUnion() { } ); } - @Before - public void setUp() { - inTransaction( session -> { + @BeforeAll + public void setUp(SessionFactoryScope scope) { + scope.inTransaction( session -> { session.persist( new SingleParent( 1L, new SingleSubChild1( 1L, "1", "1" ) ) ); session.persist( new JoinedParent( 1L, new JoinedSubChild1( 1L, "1", "1" ) ) ); session.persist( new JoinedDiscParent( 1L, new JoinedDiscSubChild1( 1L, "1", "1" ) ) ); @@ -241,64 +269,20 @@ public void setUp() { } ); } - @After - public void tearDown() { - inTransaction( session -> { - session.createMutationQuery( "delete from SingleParent" ).executeUpdate(); - session.createMutationQuery( "delete from SingleBase" ).executeUpdate(); - session.createMutationQuery( "delete from JoinedParent" ).executeUpdate(); - session.createMutationQuery( "delete from JoinedBase" ).executeUpdate(); - session.createMutationQuery( "delete from JoinedDiscParent" ).executeUpdate(); - session.createMutationQuery( "delete from JoinedDiscBase" ).executeUpdate(); - session.createMutationQuery( "delete from UnionParent" ).executeUpdate(); - session.createMutationQuery( "delete from UnionBase" ).executeUpdate(); - } ); - } - - @Override - protected void applyMetadataSources(MetadataSources sources) { - sources.addAnnotatedClasses( - SingleParent.class, - SingleBase.class, - SingleChild1.class, - SingleSubChild1.class, - SingleChild2.class, - JoinedParent.class, - JoinedBase.class, - JoinedChild1.class, - JoinedSubChild1.class, - JoinedChild2.class, - JoinedDiscParent.class, - JoinedDiscBase.class, - JoinedDiscChild1.class, - JoinedDiscSubChild1.class, - JoinedDiscChild2.class, - UnionParent.class, - UnionBase.class, - UnionChild1.class, - UnionSubChild1.class, - UnionChild2.class - ); - } - - @Override - protected void configureSessionFactoryBuilder(SessionFactoryBuilder sfb) { - sfb.applyStatementInspector( new SQLStatementInspector() ); - } - - protected SQLStatementInspector getStatementInspector() { - return (SQLStatementInspector) sessionFactory().getSessionFactoryOptions().getStatementInspector(); + @AfterAll + public void tearDown(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } // InheritanceType.SINGLE_TABLE //tag::entity-concrete-proxy-mapping[] - @Entity( name = "SingleParent" ) + @Entity(name = "SingleParent") public static class SingleParent { @Id private Long id; - @ManyToOne( fetch = FetchType.LAZY, cascade = CascadeType.PERSIST ) + @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST) private SingleBase single; public SingleParent() { @@ -314,9 +298,9 @@ public SingleBase getSingle() { } } - @Entity( name = "SingleBase" ) - @Inheritance( strategy = InheritanceType.SINGLE_TABLE ) - @DiscriminatorColumn( name = "disc_col" ) + @Entity(name = "SingleBase") + @Inheritance(strategy = InheritanceType.SINGLE_TABLE) + @DiscriminatorColumn(name = "disc_col") @ConcreteProxy public static class SingleBase { @Id @@ -330,7 +314,7 @@ public SingleBase(Long id) { } } - @Entity( name = "SingleChild1" ) + @Entity(name = "SingleChild1") public static class SingleChild1 extends SingleBase { private String child1Prop; @@ -343,7 +327,7 @@ public SingleChild1(Long id, String child1Prop) { } } - @Entity( name = "SingleSubChild1" ) + @Entity(name = "SingleSubChild1") public static class SingleSubChild1 extends SingleChild1 { private String subChild1Prop; @@ -359,7 +343,7 @@ public SingleSubChild1(Long id, String child1Prop, String subChild1Prop) { // Other subtypes omitted for brevity //end::entity-concrete-proxy-mapping[] - @Entity( name = "SingleChild2" ) + @Entity(name = "SingleChild2") public static class SingleChild2 extends SingleBase { private Integer child2Prop; @@ -374,12 +358,12 @@ public SingleChild2(Long id, Integer child2Prop) { // InheritanceType.JOINED - @Entity( name = "JoinedParent" ) + @Entity(name = "JoinedParent") public static class JoinedParent { @Id private Long id; - @ManyToOne( fetch = FetchType.LAZY, cascade = CascadeType.PERSIST ) + @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST) private JoinedBase joined; public JoinedParent() { @@ -395,8 +379,8 @@ public JoinedBase getJoined() { } } - @Entity( name = "JoinedBase" ) - @Inheritance( strategy = InheritanceType.JOINED ) + @Entity(name = "JoinedBase") + @Inheritance(strategy = InheritanceType.JOINED) @ConcreteProxy public static class JoinedBase { @Id @@ -410,7 +394,7 @@ public JoinedBase(Long id) { } } - @Entity( name = "JoinedChild1" ) + @Entity(name = "JoinedChild1") public static class JoinedChild1 extends JoinedBase { private String child1Prop; @@ -423,7 +407,7 @@ public JoinedChild1(Long id, String child1Prop) { } } - @Entity( name = "JoinedSubChild1" ) + @Entity(name = "JoinedSubChild1") public static class JoinedSubChild1 extends JoinedChild1 { private String subChild1Prop; @@ -436,7 +420,7 @@ public JoinedSubChild1(Long id, String child1Prop, String subChild1Prop) { } } - @Entity( name = "JoinedChild2" ) + @Entity(name = "JoinedChild2") public static class JoinedChild2 extends JoinedBase { private Integer child2Prop; @@ -451,12 +435,12 @@ public JoinedChild2(Long id, Integer child2Prop) { // InheritanceType.JOINED + @DiscriminatorColumn - @Entity( name = "JoinedDiscParent" ) + @Entity(name = "JoinedDiscParent") public static class JoinedDiscParent { @Id private Long id; - @ManyToOne( fetch = FetchType.LAZY, cascade = CascadeType.PERSIST ) + @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST) private JoinedDiscBase joinedDisc; public JoinedDiscParent() { @@ -472,9 +456,9 @@ public JoinedDiscBase getJoinedDisc() { } } - @Entity( name = "JoinedDiscBase" ) - @Inheritance( strategy = InheritanceType.JOINED ) - @DiscriminatorColumn( name = "disc_col" ) + @Entity(name = "JoinedDiscBase") + @Inheritance(strategy = InheritanceType.JOINED) + @DiscriminatorColumn(name = "disc_col") @ConcreteProxy public static class JoinedDiscBase { @Id @@ -488,7 +472,7 @@ public JoinedDiscBase(Long id) { } } - @Entity( name = "JoinedDiscChild1" ) + @Entity(name = "JoinedDiscChild1") public static class JoinedDiscChild1 extends JoinedDiscBase { private String child1Prop; @@ -501,7 +485,7 @@ public JoinedDiscChild1(Long id, String child1Prop) { } } - @Entity( name = "JoinedDiscSubChild1" ) + @Entity(name = "JoinedDiscSubChild1") public static class JoinedDiscSubChild1 extends JoinedDiscChild1 { private String subChild1Prop; @@ -514,7 +498,7 @@ public JoinedDiscSubChild1(Long id, String child1Prop, String subChild1Prop) { } } - @Entity( name = "JoinedDiscChild2" ) + @Entity(name = "JoinedDiscChild2") public static class JoinedDiscChild2 extends JoinedDiscBase { private Integer child2Prop; @@ -529,12 +513,12 @@ public JoinedDiscChild2(Long id, Integer child2Prop) { // InheritanceType.TABLE_PER_CLASS - @Entity( name = "UnionParent" ) + @Entity(name = "UnionParent") public static class UnionParent { @Id private Long id; - @ManyToOne( fetch = FetchType.LAZY, cascade = CascadeType.PERSIST ) + @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST) private UnionBase union; public UnionParent() { @@ -550,8 +534,8 @@ public UnionBase getUnion() { } } - @Entity( name = "UnionBase" ) - @Inheritance( strategy = InheritanceType.TABLE_PER_CLASS ) + @Entity(name = "UnionBase") + @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) @ConcreteProxy public static class UnionBase { @Id @@ -565,7 +549,7 @@ public UnionBase(Long id) { } } - @Entity( name = "UnionChild1" ) + @Entity(name = "UnionChild1") public static class UnionChild1 extends UnionBase { private String child1Prop; @@ -578,7 +562,7 @@ public UnionChild1(Long id, String child1Prop) { } } - @Entity( name = "UnionSubChild1" ) + @Entity(name = "UnionSubChild1") public static class UnionSubChild1 extends UnionChild1 { private String subChild1Prop; @@ -591,7 +575,7 @@ public UnionSubChild1(Long id, String child1Prop, String subChild1Prop) { } } - @Entity( name = "UnionChild2" ) + @Entity(name = "UnionChild2") public static class UnionChild2 extends UnionBase { private Integer child2Prop; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/concrete/ProxyConcreteProxyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/concrete/ProxyConcreteProxyTest.java deleted file mode 100644 index 9235c2cb852c..000000000000 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/concrete/ProxyConcreteProxyTest.java +++ /dev/null @@ -1,13 +0,0 @@ -/* - * SPDX-License-Identifier: Apache-2.0 - * Copyright Red Hat Inc. and Hibernate Authors - */ -package org.hibernate.orm.test.proxy.concrete; - -/** - * Version of {@link AbstractConcreteProxyTest} using normal {@linkplain org.hibernate.proxy.HibernateProxy proxies}. - * - * @author Marco Belladelli - */ -public class ProxyConcreteProxyTest extends AbstractConcreteProxyTest { -} diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/OneToManyLazyAndEagerProxyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/OneToManyLazyAndEagerProxyTest.java index f639e95e30a8..c26955e70fe1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/OneToManyLazyAndEagerProxyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/OneToManyLazyAndEagerProxyTest.java @@ -4,48 +4,45 @@ */ package org.hibernate.orm.test.query; -import java.util.HashSet; -import java.util.Set; - -import org.hibernate.Hibernate; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.hibernate.proxy.HibernateProxy; - -import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - import jakarta.persistence.Entity; import jakarta.persistence.FetchType; import jakarta.persistence.Id; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; +import org.hibernate.Hibernate; +import org.hibernate.SessionFactory; +import org.hibernate.proxy.HibernateProxy; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.Jpa; +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.assertj.core.api.Assertions.assertThat; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * @author Marco Belladelli * @author Tomas Cerskus */ @JiraKey(value = "HHH-16136") -public class OneToManyLazyAndEagerProxyTest extends BaseEntityManagerFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - User.class, - Order.class, - OrderItem.class - }; - } +@Jpa( + annotatedClasses = { + OneToManyLazyAndEagerProxyTest.User.class, + OneToManyLazyAndEagerProxyTest.Order.class, + OneToManyLazyAndEagerProxyTest.OrderItem.class + } +) +public class OneToManyLazyAndEagerProxyTest { - @Before - public void prepare() { - doInJPA( this::entityManagerFactory, em -> { + @BeforeEach + public void prepare(EntityManagerFactoryScope scope) { + scope.inTransaction( em -> { final User user = new User( "User 1", "Marco" ); final User targetUser = new User( "User 2", "Andrea" ); final Order order = new Order( "Order 1", user, targetUser ); @@ -58,30 +55,32 @@ public void prepare() { } ); } - @After - public void tearDown() { - doInJPA( this::entityManagerFactory, em -> { - em.createQuery( "delete from OrderItem" ).executeUpdate(); - em.createQuery( "delete from Order" ).executeUpdate(); - em.createQuery( "delete from User" ).executeUpdate(); - }); + @AfterEach + public void tearDown(EntityManagerFactoryScope scope) { + scope.getEntityManagerFactory().unwrap( SessionFactory.class ).getSchemaManager().truncateMappedObjects(); } @Test - public void testHibernateProxy() { - doInJPA( this::entityManagerFactory, em -> { + public void testHibernateProxy(EntityManagerFactoryScope scope) { + scope.inTransaction( em -> { // get reference to get a lazy proxy instance final User userRef = em.getReference( User.class, "User 1" ); - assertTrue( userRef instanceof HibernateProxy ); - assertFalse( "Proxy should not be initialized", Hibernate.isInitialized( userRef ) ); + assertThat( userRef ).isInstanceOf( HibernateProxy.class ); + assertThat( Hibernate.isInitialized( userRef ) ) + .describedAs( "Proxy should not be initialized" ) + .isFalse(); // query eager order.user and check that same instance was initialized final Order order = em.createQuery( "select o from Order o", Order.class ) .getResultList() .get( 0 ); final User user = order.getUser(); - assertEquals( "Proxy instance should be the same", userRef, user ); - assertTrue( "Proxy should be initialized", Hibernate.isInitialized( user ) ); - assertEquals( "Marco", user.getName() ); + assertThat( user ) + .describedAs( "Proxy instance should be the same" ) + .isEqualTo( userRef ); + assertThat( Hibernate.isInitialized( user ) ) + .describedAs( "Proxy should be initialized" ) + .isTrue(); + assertThat( user.getName() ).isEqualTo( "Marco" ); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/QueryTimeOutTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/QueryTimeOutTest.java index 910707eb511e..0d364dc7c367 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/QueryTimeOutTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/QueryTimeOutTest.java @@ -4,71 +4,70 @@ */ package org.hibernate.orm.test.query; -import java.sql.Statement; -import java.sql.Types; -import java.util.List; -import java.util.Map; - +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.AvailableSettings; import org.hibernate.dialect.AbstractTransactSQLDialect; import org.hibernate.dialect.DmlTargetColumnQualifierSupport; import org.hibernate.dialect.OracleDialect; import org.hibernate.dialect.SybaseDialect; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; +import org.hibernate.engine.spi.SessionFactoryImplementor; +import org.hibernate.query.MutationQuery; import org.hibernate.query.NativeQuery; -import org.hibernate.query.Query; -import org.hibernate.type.descriptor.java.StringJavaType; -import org.hibernate.type.descriptor.jdbc.JdbcType; - -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; import org.hibernate.testing.orm.jdbc.PreparedStatementSpyConnectionProvider; +import org.hibernate.testing.orm.junit.BaseSessionFactoryFunctionalTest; import org.hibernate.testing.orm.junit.DialectContext; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DialectFeatureChecks; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.hibernate.type.descriptor.java.StringJavaType; +import org.hibernate.type.descriptor.jdbc.JdbcType; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import jakarta.persistence.Entity; -import jakarta.persistence.Id; -import jakarta.persistence.Table; +import java.sql.Statement; +import java.sql.Types; +import java.util.List; import static org.hibernate.jpa.SpecHints.HINT_SPEC_QUERY_TIMEOUT; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Gail Badner */ -@RequiresDialectFeature(DialectChecks.SupportsJdbcDriverProxying.class) -public class QueryTimeOutTest extends BaseNonConfigCoreFunctionalTestCase { +@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsJdbcDriverProxying.class) +public class QueryTimeOutTest extends BaseSessionFactoryFunctionalTest { - private static final PreparedStatementSpyConnectionProvider CONNECTION_PROVIDER = new PreparedStatementSpyConnectionProvider( - ); + private static final PreparedStatementSpyConnectionProvider CONNECTION_PROVIDER = + new PreparedStatementSpyConnectionProvider(); private static final String QUERY = "update AnEntity set name='abc'"; - private String expectedSqlQuery; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { AnEntity.class }; + return new Class[] {AnEntity.class}; } @Override - protected void addSettings(Map settings) { - if ( settings.containsKey( AvailableSettings.CONNECTION_PROVIDER ) ) { - CONNECTION_PROVIDER.setConnectionProvider( (ConnectionProvider) settings.get( AvailableSettings.CONNECTION_PROVIDER ) ); - } - settings.put( AvailableSettings.CONNECTION_PROVIDER, CONNECTION_PROVIDER ); + protected void applySettings(StandardServiceRegistryBuilder builer) { + ConnectionProvider connectionProvider = (ConnectionProvider) builer.getSettings() + .get( AvailableSettings.CONNECTION_PROVIDER ); + CONNECTION_PROVIDER.setConnectionProvider( connectionProvider ); + builer.applySetting( AvailableSettings.CONNECTION_PROVIDER, CONNECTION_PROVIDER ); } - @Before + @BeforeEach public void before() { CONNECTION_PROVIDER.clear(); - final JdbcType jdbcType = sessionFactory().getTypeConfiguration().getJdbcTypeRegistry().getDescriptor( - Types.VARCHAR - ); + SessionFactoryImplementor sessionFactoryImplementor = sessionFactory(); + final JdbcType jdbcType = sessionFactoryImplementor.getTypeConfiguration().getJdbcTypeRegistry() + .getDescriptor( + Types.VARCHAR + ); final String baseQuery; if ( DialectContext.getDialect() instanceof OracleDialect ) { baseQuery = "update AnEntity ae1_0 set ae1_0.name=?"; @@ -79,7 +78,8 @@ else if ( DialectContext.getDialect() instanceof SybaseDialect ) { else if ( DialectContext.getDialect() instanceof AbstractTransactSQLDialect ) { baseQuery = "update ae1_0 set name=? from AnEntity ae1_0"; } - else if ( DialectContext.getDialect().getDmlTargetColumnQualifierSupport() == DmlTargetColumnQualifierSupport.NONE ) { + else if ( DialectContext.getDialect() + .getDmlTargetColumnQualifierSupport() == DmlTargetColumnQualifierSupport.NONE ) { baseQuery = "update AnEntity set name=?"; } else { @@ -90,8 +90,8 @@ else if ( DialectContext.getDialect().getDmlTargetColumnQualifierSupport() == Dm jdbcType.getJdbcLiteralFormatter( StringJavaType.INSTANCE ) .toJdbcLiteral( "abc", - sessionFactory().getJdbcServices().getDialect(), - sessionFactory().getWrapperOptions() + sessionFactoryImplementor.getJdbcServices().getDialect(), + sessionFactoryImplementor.getWrapperOptions() ) ); } @@ -99,9 +99,8 @@ else if ( DialectContext.getDialect().getDmlTargetColumnQualifierSupport() == Dm @Test @JiraKey(value = "HHH-12075") public void testCreateQuerySetTimeout() { - doInHibernate( - this::sessionFactory, session -> { - Query query = session.createQuery( QUERY ); + inTransaction( session -> { + MutationQuery query = session.createMutationQuery( QUERY ); query.setTimeout( 123 ); query.executeUpdate(); @@ -115,7 +114,7 @@ public void testCreateQuerySetTimeout() { assertEquals( 0, setQueryTimeoutCalls.get( 1 )[0] ); } catch (Exception ex) { - fail( "should not have thrown exception" ); + fail( "should not have thrown exceptioinTransaction( session -> {n" ); } } ); @@ -124,9 +123,8 @@ public void testCreateQuerySetTimeout() { @Test @JiraKey(value = "HHH-12075") public void testCreateQuerySetTimeoutHint() { - doInHibernate( - this::sessionFactory, session -> { - Query query = session.createQuery( QUERY ); + inTransaction( session -> { + MutationQuery query = session.createMutationQuery( QUERY ); query.setHint( HINT_SPEC_QUERY_TIMEOUT, 123000 ); query.executeUpdate(); @@ -149,8 +147,7 @@ public void testCreateQuerySetTimeoutHint() { @Test @JiraKey(value = "HHH-12075") public void testCreateNativeQuerySetTimeout() { - doInHibernate( - this::sessionFactory, session -> { + inTransaction( session -> { NativeQuery query = session.createNativeQuery( QUERY ); query.setTimeout( 123 ); query.executeUpdate(); @@ -174,8 +171,7 @@ public void testCreateNativeQuerySetTimeout() { @Test @JiraKey(value = "HHH-12075") public void testCreateNativeQuerySetTimeoutHint() { - doInHibernate( - this::sessionFactory, session -> { + inTransaction( session -> { NativeQuery query = session.createNativeQuery( QUERY ); query.setHint( HINT_SPEC_QUERY_TIMEOUT, 123000 ); query.executeUpdate(); @@ -199,8 +195,7 @@ public void testCreateNativeQuerySetTimeoutHint() { @Test @JiraKey(value = "HHH-12075") public void testCreateSQLQuerySetTimeout() { - doInHibernate( - this::sessionFactory, session -> { + inTransaction( session -> { NativeQuery query = session.createNativeQuery( QUERY ); query.setTimeout( 123 ); query.executeUpdate(); @@ -224,8 +219,7 @@ public void testCreateSQLQuerySetTimeout() { @Test @JiraKey(value = "HHH-12075") public void testCreateSQLQuerySetTimeoutHint() { - doInHibernate( - this::sessionFactory, session -> { + inTransaction( session -> { NativeQuery query = session.createNativeQuery( QUERY ); query.setHint( HINT_SPEC_QUERY_TIMEOUT, 123000 ); query.executeUpdate(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaPrimitiveIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaPrimitiveIdTest.java index 960d2cefdbba..02dad99f12e8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaPrimitiveIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaPrimitiveIdTest.java @@ -4,15 +4,6 @@ */ package org.hibernate.orm.test.query.criteria; -import static org.assertj.core.api.Assertions.assertThat; - -import org.hibernate.Session; -import org.hibernate.query.Query; - -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; - import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.criteria.CriteriaBuilder; @@ -21,31 +12,43 @@ import jakarta.persistence.criteria.Root; import jakarta.persistence.metamodel.EntityType; import jakarta.persistence.metamodel.SingularAttribute; +import org.hibernate.Session; +import org.hibernate.query.Query; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; -@JiraKey(value = "HHH-15073") -public class CriteriaPrimitiveIdTest extends BaseCoreFunctionalTestCase { +import static org.assertj.core.api.Assertions.assertThat; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { MyEntity.class }; - } +@JiraKey(value = "HHH-15073") +@DomainModel( + annotatedClasses = { + CriteriaPrimitiveIdTest.MyEntity.class + } +) +@SessionFactory +public class CriteriaPrimitiveIdTest { @Test - public void test() { - inTransaction( session -> { + public void test(SessionFactoryScope scope) { + scope.inTransaction( session -> { session.persist( new MyEntity( 1L ) ); session.persist( new MyEntity( 2L ) ); session.persist( new MyEntity( 3L ) ); } ); - inTransaction( session -> { - EntityType type = sessionFactory().getJpaMetamodel().entity( MyEntity.class ); + + scope.inTransaction( session -> { + EntityType type = scope.getSessionFactory().getJpaMetamodel().entity( MyEntity.class ); SingularAttribute idAttribute = type.getId( long.class ); Query query = createQueryForIdentifierListing( session, type, idAttribute ); assertThat( query.list() ).containsExactlyInAnyOrder( 1L, 2L, 3L ); } ); } - private Query createQueryForIdentifierListing(Session session, + private Query createQueryForIdentifierListing( + Session session, EntityType type, SingularAttribute idAttribute) { CriteriaBuilder criteriaBuilder = session.getSessionFactory().getCriteriaBuilder(); CriteriaQuery criteriaQuery = criteriaBuilder.createQuery( idAttribute.getJavaType() ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaStringInlineLiteralTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaStringInlineLiteralTest.java index c169eb5bb1f5..3a50a809aa22 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaStringInlineLiteralTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaStringInlineLiteralTest.java @@ -5,44 +5,47 @@ package org.hibernate.orm.test.query.criteria; import jakarta.persistence.Entity; -import jakarta.persistence.EntityManager; import jakarta.persistence.Id; import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Expression; import jakarta.persistence.criteria.Root; - -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Michiel Haisma * @author Nathan Xu */ -@JiraKey( value = "HHH-13889" ) -public class CriteriaStringInlineLiteralTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Animal.class }; - } +@JiraKey(value = "HHH-13889") +@Jpa( + annotatedClasses = { + CriteriaStringInlineLiteralTest.Animal.class + } +) +public class CriteriaStringInlineLiteralTest { @Test - public void testCriteriaInlineStringLiteralRendering() { - EntityManager entityManager = getOrCreateEntityManager(); - CriteriaBuilder cb = entityManager.getCriteriaBuilder(); - CriteriaQuery criteriaQuery = cb.createQuery( String.class ); - - Root animalRoot = criteriaQuery.from( Animal.class ); - CriteriaBuilder.Case sCase = cb.selectCase(); - Expression caseSelect = - sCase.when( cb.equal( animalRoot.get( "name" ), cb.literal( "kitty" ) ), cb.literal( "Cat" ) ) - .otherwise("escapez'moi" ); - criteriaQuery.multiselect( caseSelect ); - criteriaQuery.where( cb.equal( animalRoot.get( "name" ), "myFavoriteAnimal" ) ); - entityManager.createQuery( criteriaQuery); // would throw exception for unescaped otherwise literal in HHH-13889 + public void testCriteriaInlineStringLiteralRendering(EntityManagerFactoryScope scope) { + scope.inEntityManager( + entityManager -> { + CriteriaBuilder cb = entityManager.getCriteriaBuilder(); + CriteriaQuery criteriaQuery = cb.createQuery( String.class ); + + Root animalRoot = criteriaQuery.from( Animal.class ); + CriteriaBuilder.Case sCase = cb.selectCase(); + Expression caseSelect = + sCase.when( cb.equal( animalRoot.get( "name" ), cb.literal( "kitty" ) ), + cb.literal( "Cat" ) ) + .otherwise( "escapez'moi" ); + criteriaQuery.multiselect( caseSelect ); + criteriaQuery.where( cb.equal( animalRoot.get( "name" ), "myFavoriteAnimal" ) ); + entityManager.createQuery( + criteriaQuery ); // would throw exception for unescaped otherwise literal in HHH-13889 + } + ); } @Entity(name = "Animal") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaTest.java index 9ef98899e862..51f93f1e3cb1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaTest.java @@ -4,11 +4,19 @@ */ package org.hibernate.orm.test.query.criteria; -import java.math.BigDecimal; -import java.time.LocalDateTime; -import java.util.List; - -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Tuple; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Fetch; +import jakarta.persistence.criteria.Join; +import jakarta.persistence.criteria.ParameterExpression; +import jakarta.persistence.criteria.Path; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; +import org.hibernate.SessionFactory; import org.hibernate.testing.orm.domain.userguide.Account; import org.hibernate.testing.orm.domain.userguide.AddressType; import org.hibernate.testing.orm.domain.userguide.Call; @@ -21,380 +29,374 @@ import org.hibernate.testing.orm.domain.userguide.PhoneType; import org.hibernate.testing.orm.domain.userguide.Phone_; import org.hibernate.testing.orm.domain.userguide.WireTransferPayment; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.junit.Before; -import org.junit.Test; - -import jakarta.persistence.Entity; -import jakarta.persistence.Id; -import jakarta.persistence.Tuple; -import jakarta.persistence.TypedQuery; -import jakarta.persistence.criteria.CriteriaBuilder; -import jakarta.persistence.criteria.CriteriaQuery; -import jakarta.persistence.criteria.Fetch; -import jakarta.persistence.criteria.Join; -import jakarta.persistence.criteria.ParameterExpression; -import jakarta.persistence.criteria.Path; -import jakarta.persistence.criteria.Predicate; -import jakarta.persistence.criteria.Root; +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Vlad Mihalcea */ -public class CriteriaTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Partner.class, - Phone.class, - Call.class, - CreditCardPayment.class, - WireTransferPayment.class, - Account.class, - Event.class - }; - } - - @Before - public void init() { - doInJPA(this::entityManagerFactory, entityManager -> { - Person person1 = new Person("John Doe"); - person1.setNickName("JD"); - person1.setAddress("Earth"); - person1.setCreatedOn(LocalDateTime.of(2000, 1, 1, 0, 0, 0)) ; - person1.getAddresses().put(AddressType.HOME, "Home address"); - person1.getAddresses().put(AddressType.OFFICE, "Office address"); - entityManager.persist(person1); - - Person person2 = new Person("Mrs. John Doe"); - person2.setAddress("Earth"); - person2.setCreatedOn(LocalDateTime.of(2000, 1, 2, 12, 0, 0)) ; - entityManager.persist(person2); - - Person person3 = new Person("Dr_ John Doe"); - entityManager.persist(person3); - - Phone phone1 = new Phone("123-456-7890"); - phone1.setId(1L); - phone1.setType(PhoneType.MOBILE); - person1.addPhone(phone1); - phone1.getRepairTimestamps().add(LocalDateTime.of(2005, 1, 1, 12, 0, 0)); - phone1.getRepairTimestamps().add(LocalDateTime.of(2006, 1, 1, 12, 0, 0)); +@Jpa( + annotatedClasses = { + Person.class, + Partner.class, + Phone.class, + Call.class, + CreditCardPayment.class, + WireTransferPayment.class, + Account.class, + CriteriaTest.Event.class + } +) +public class CriteriaTest { + + @BeforeEach + public void init(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Person person1 = new Person( "John Doe" ); + person1.setNickName( "JD" ); + person1.setAddress( "Earth" ); + person1.setCreatedOn( LocalDateTime.of( 2000, 1, 1, 0, 0, 0 ) ); + person1.getAddresses().put( AddressType.HOME, "Home address" ); + person1.getAddresses().put( AddressType.OFFICE, "Office address" ); + entityManager.persist( person1 ); + + Person person2 = new Person( "Mrs. John Doe" ); + person2.setAddress( "Earth" ); + person2.setCreatedOn( LocalDateTime.of( 2000, 1, 2, 12, 0, 0 ) ); + entityManager.persist( person2 ); + + Person person3 = new Person( "Dr_ John Doe" ); + entityManager.persist( person3 ); + + Phone phone1 = new Phone( "123-456-7890" ); + phone1.setId( 1L ); + phone1.setType( PhoneType.MOBILE ); + person1.addPhone( phone1 ); + phone1.getRepairTimestamps().add( LocalDateTime.of( 2005, 1, 1, 12, 0, 0 ) ); + phone1.getRepairTimestamps().add( LocalDateTime.of( 2006, 1, 1, 12, 0, 0 ) ); Call call11 = new Call(); - call11.setDuration(12); - call11.setTimestamp(LocalDateTime.of(2000, 1, 1, 0, 0, 0)); + call11.setDuration( 12 ); + call11.setTimestamp( LocalDateTime.of( 2000, 1, 1, 0, 0, 0 ) ); Call call12 = new Call(); - call12.setDuration(33); - call12.setTimestamp(LocalDateTime.of(2000, 1, 1, 1, 0, 0)); + call12.setDuration( 33 ); + call12.setTimestamp( LocalDateTime.of( 2000, 1, 1, 1, 0, 0 ) ); - phone1.addCall(call11); - phone1.addCall(call12); + phone1.addCall( call11 ); + phone1.addCall( call12 ); - Phone phone2 = new Phone("098_765-4321"); - phone2.setId(2L); - phone2.setType(PhoneType.LAND_LINE); + Phone phone2 = new Phone( "098_765-4321" ); + phone2.setId( 2L ); + phone2.setType( PhoneType.LAND_LINE ); - Phone phone3 = new Phone("098-765-4320"); - phone3.setId(3L); - phone3.setType(PhoneType.LAND_LINE); + Phone phone3 = new Phone( "098-765-4320" ); + phone3.setId( 3L ); + phone3.setType( PhoneType.LAND_LINE ); - person2.addPhone(phone2); - person2.addPhone(phone3); + person2.addPhone( phone2 ); + person2.addPhone( phone3 ); CreditCardPayment creditCardPayment = new CreditCardPayment(); - creditCardPayment.setCompleted(true); - creditCardPayment.setAmount(BigDecimal.ZERO); - creditCardPayment.setPerson(person1); + creditCardPayment.setCompleted( true ); + creditCardPayment.setAmount( BigDecimal.ZERO ); + creditCardPayment.setPerson( person1 ); WireTransferPayment wireTransferPayment = new WireTransferPayment(); - wireTransferPayment.setCompleted(true); - wireTransferPayment.setAmount(BigDecimal.valueOf(100)); - wireTransferPayment.setPerson(person2); + wireTransferPayment.setCompleted( true ); + wireTransferPayment.setAmount( BigDecimal.valueOf( 100 ) ); + wireTransferPayment.setPerson( person2 ); - entityManager.persist(creditCardPayment); - entityManager.persist(wireTransferPayment); + entityManager.persist( creditCardPayment ); + entityManager.persist( wireTransferPayment ); - Partner partner = new Partner("John Doe"); - entityManager.persist(partner); - }); + Partner partner = new Partner( "John Doe" ); + entityManager.persist( partner ); + } ); } - @Test - public void test_criteria_typedquery_entity_example() { + @AfterEach + public void cleanup(EntityManagerFactoryScope scope) { + scope.getEntityManagerFactory().unwrap( SessionFactory.class ).getSchemaManager().truncateMappedObjects(); + } - doInJPA(this::entityManagerFactory, entityManager -> { + @Test + public void test_criteria_typedquery_entity_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::criteria-typedquery-entity-example[] CriteriaBuilder builder = entityManager.getCriteriaBuilder(); - CriteriaQuery criteria = builder.createQuery(Person.class); - Root root = criteria.from(Person.class); - criteria.select(root); - criteria.where(builder.equal(root.get(Person_.name), "John Doe")); + CriteriaQuery criteria = builder.createQuery( Person.class ); + Root root = criteria.from( Person.class ); + criteria.select( root ); + criteria.where( builder.equal( root.get( Person_.name ), "John Doe" ) ); - List persons = entityManager.createQuery(criteria).getResultList(); + List persons = entityManager.createQuery( criteria ).getResultList(); //end::criteria-typedquery-entity-example[] - assertEquals(1, persons.size()); - }); + assertThat( persons ).hasSize( 1 ); + } ); } @Test - public void test_criteria_typedquery_expression_example() { + public void test_criteria_typedquery_expression_example(EntityManagerFactoryScope scope) { - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::criteria-typedquery-expression-example[] CriteriaBuilder builder = entityManager.getCriteriaBuilder(); - CriteriaQuery criteria = builder.createQuery(String.class); - Root root = criteria.from(Person.class); - criteria.select(root.get(Person_.nickName)); - criteria.where(builder.equal(root.get(Person_.name), "John Doe")); + CriteriaQuery criteria = builder.createQuery( String.class ); + Root root = criteria.from( Person.class ); + criteria.select( root.get( Person_.nickName ) ); + criteria.where( builder.equal( root.get( Person_.name ), "John Doe" ) ); - List nickNames = entityManager.createQuery(criteria).getResultList(); + List nickNames = entityManager.createQuery( criteria ).getResultList(); //end::criteria-typedquery-expression-example[] - assertEquals(1, nickNames.size()); - }); + assertThat( nickNames ).hasSize( 1 ); + } ); } @Test - public void test_criteria_typedquery_multiselect_explicit_array_example() { + public void test_criteria_typedquery_multiselect_explicit_array_example(EntityManagerFactoryScope scope) { - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::criteria-typedquery-multiselect-array-explicit-example[] CriteriaBuilder builder = entityManager.getCriteriaBuilder(); - CriteriaQuery criteria = builder.createQuery(Object[].class); - Root root = criteria.from(Person.class); + CriteriaQuery criteria = builder.createQuery( Object[].class ); + Root root = criteria.from( Person.class ); - Path idPath = root.get(Person_.id); - Path nickNamePath = root.get(Person_.nickName); + Path idPath = root.get( Person_.id ); + Path nickNamePath = root.get( Person_.nickName ); - criteria.select(builder.array(idPath, nickNamePath)); - criteria.where(builder.equal(root.get(Person_.name), "John Doe")); + criteria.select( builder.array( idPath, nickNamePath ) ); + criteria.where( builder.equal( root.get( Person_.name ), "John Doe" ) ); - List idAndNickNames = entityManager.createQuery(criteria).getResultList(); + List idAndNickNames = entityManager.createQuery( criteria ).getResultList(); //end::criteria-typedquery-multiselect-array-explicit-example[] - assertEquals(1, idAndNickNames.size()); - }); + assertThat( idAndNickNames ).hasSize( 1 ); + } ); } @Test - public void test_criteria_typedquery_multiselect_implicit_array_example() { + public void test_criteria_typedquery_multiselect_implicit_array_example(EntityManagerFactoryScope scope) { - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::criteria-typedquery-multiselect-array-implicit-example[] CriteriaBuilder builder = entityManager.getCriteriaBuilder(); - CriteriaQuery criteria = builder.createQuery(Object[].class); - Root root = criteria.from(Person.class); + CriteriaQuery criteria = builder.createQuery( Object[].class ); + Root root = criteria.from( Person.class ); - Path idPath = root.get(Person_.id); - Path nickNamePath = root.get(Person_.nickName); + Path idPath = root.get( Person_.id ); + Path nickNamePath = root.get( Person_.nickName ); - criteria.multiselect(idPath, nickNamePath); - criteria.where(builder.equal(root.get(Person_.name), "John Doe")); + criteria.multiselect( idPath, nickNamePath ); + criteria.where( builder.equal( root.get( Person_.name ), "John Doe" ) ); - List idAndNickNames = entityManager.createQuery(criteria).getResultList(); + List idAndNickNames = entityManager.createQuery( criteria ).getResultList(); //end::criteria-typedquery-multiselect-array-implicit-example[] - assertEquals(1, idAndNickNames.size()); - }); + assertThat( idAndNickNames ).hasSize( 1 ); + } ); } @Test - public void test_criteria_typedquery_wrapper_example() { + public void test_criteria_typedquery_wrapper_example(EntityManagerFactoryScope scope) { - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::criteria-typedquery-wrapper-example[] CriteriaBuilder builder = entityManager.getCriteriaBuilder(); - CriteriaQuery criteria = builder.createQuery(PersonWrapper.class); - Root root = criteria.from(Person.class); + CriteriaQuery criteria = builder.createQuery( PersonWrapper.class ); + Root root = criteria.from( Person.class ); - Path idPath = root.get(Person_.id); - Path nickNamePath = root.get(Person_.nickName); + Path idPath = root.get( Person_.id ); + Path nickNamePath = root.get( Person_.nickName ); - criteria.select(builder.construct(PersonWrapper.class, idPath, nickNamePath)); - criteria.where(builder.equal(root.get(Person_.name), "John Doe")); + criteria.select( builder.construct( PersonWrapper.class, idPath, nickNamePath ) ); + criteria.where( builder.equal( root.get( Person_.name ), "John Doe" ) ); - List wrappers = entityManager.createQuery(criteria).getResultList(); + List wrappers = entityManager.createQuery( criteria ).getResultList(); //end::criteria-typedquery-wrapper-example[] - assertEquals(1, wrappers.size()); - }); + assertThat( wrappers ).hasSize( 1 ); + } ); } @Test - public void test_criteria_tuple_example() { + public void test_criteria_tuple_example(EntityManagerFactoryScope scope) { - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::criteria-tuple-example[] CriteriaBuilder builder = entityManager.getCriteriaBuilder(); - CriteriaQuery criteria = builder.createQuery(Tuple.class); - Root root = criteria.from(Person.class); + CriteriaQuery criteria = builder.createQuery( Tuple.class ); + Root root = criteria.from( Person.class ); - Path idPath = root.get(Person_.id); - Path nickNamePath = root.get(Person_.nickName); + Path idPath = root.get( Person_.id ); + Path nickNamePath = root.get( Person_.nickName ); - criteria.multiselect(idPath, nickNamePath); - criteria.where(builder.equal(root.get(Person_.name), "John Doe")); + criteria.multiselect( idPath, nickNamePath ); + criteria.where( builder.equal( root.get( Person_.name ), "John Doe" ) ); - List tuples = entityManager.createQuery(criteria).getResultList(); + List tuples = entityManager.createQuery( criteria ).getResultList(); - for (Tuple tuple : tuples) { - Long id = tuple.get(idPath); - String nickName = tuple.get(nickNamePath); + for ( Tuple tuple : tuples ) { + Long id = tuple.get( idPath ); + String nickName = tuple.get( nickNamePath ); } //or using indices - for (Tuple tuple : tuples) { - Long id = (Long) tuple.get(0); - String nickName = (String) tuple.get(1); + for ( Tuple tuple : tuples ) { + Long id = (Long) tuple.get( 0 ); + String nickName = (String) tuple.get( 1 ); } //end::criteria-tuple-example[] - assertEquals(1, tuples.size()); - }); + assertThat( tuples ).hasSize( 1 ); + } ); } @Test - public void test_criteria_from_root_example() { + public void test_criteria_from_root_example(EntityManagerFactoryScope scope) { - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::criteria-from-root-example[] CriteriaBuilder builder = entityManager.getCriteriaBuilder(); - CriteriaQuery criteria = builder.createQuery(Person.class); - Root root = criteria.from(Person.class); + CriteriaQuery criteria = builder.createQuery( Person.class ); + Root root = criteria.from( Person.class ); //end::criteria-from-root-example[] - }); + } ); } @Test - public void test_criteria_from_multiple_root_example() { + public void test_criteria_from_multiple_root_example(EntityManagerFactoryScope scope) { - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { String address = "Earth"; String prefix = "J%"; //tag::criteria-from-multiple-root-example[] CriteriaBuilder builder = entityManager.getCriteriaBuilder(); - CriteriaQuery criteria = builder.createQuery(Tuple.class); + CriteriaQuery criteria = builder.createQuery( Tuple.class ); - Root personRoot = criteria.from(Person.class); - Root partnerRoot = criteria.from(Partner.class); - criteria.multiselect(personRoot, partnerRoot); + Root personRoot = criteria.from( Person.class ); + Root partnerRoot = criteria.from( Partner.class ); + criteria.multiselect( personRoot, partnerRoot ); Predicate personRestriction = builder.and( - builder.equal(personRoot.get(Person_.address), address), - builder.isNotEmpty(personRoot.get(Person_.phones)) + builder.equal( personRoot.get( Person_.address ), address ), + builder.isNotEmpty( personRoot.get( Person_.phones ) ) ); Predicate partnerRestriction = builder.and( - builder.like(partnerRoot.get(Partner_.name), prefix), - builder.equal(partnerRoot.get(Partner_.version), 0) + builder.like( partnerRoot.get( Partner_.name ), prefix ), + builder.equal( partnerRoot.get( Partner_.version ), 0 ) ); - criteria.where(builder.and(personRestriction, partnerRestriction)); + criteria.where( builder.and( personRestriction, partnerRestriction ) ); - List tuples = entityManager.createQuery(criteria).getResultList(); + List tuples = entityManager.createQuery( criteria ).getResultList(); //end::criteria-from-multiple-root-example[] - assertEquals(2, tuples.size()); - }); + assertThat( tuples ).hasSize( 2 ); + } ); } @Test - public void test_criteria_from_join_example() { + public void test_criteria_from_join_example(EntityManagerFactoryScope scope) { - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::criteria-from-join-example[] CriteriaBuilder builder = entityManager.getCriteriaBuilder(); - CriteriaQuery criteria = builder.createQuery(Phone.class); - Root root = criteria.from(Phone.class); + CriteriaQuery criteria = builder.createQuery( Phone.class ); + Root root = criteria.from( Phone.class ); // Phone.person is a @ManyToOne - Join personJoin = root.join(Phone_.person); + Join personJoin = root.join( Phone_.person ); // Person.addresses is an @ElementCollection - Join addressesJoin = personJoin.join(Person_.addresses); + Join addressesJoin = personJoin.join( Person_.addresses ); - criteria.where(builder.isNotEmpty(root.get(Phone_.calls))); + criteria.where( builder.isNotEmpty( root.get( Phone_.calls ) ) ); - List phones = entityManager.createQuery(criteria).getResultList(); + List phones = entityManager.createQuery( criteria ).getResultList(); //end::criteria-from-join-example[] - assertEquals(1, phones.size()); - }); + assertThat( phones ).hasSize( 1 ); + } ); } @Test - public void test_criteria_from_fetch_example() { + public void test_criteria_from_fetch_example(EntityManagerFactoryScope scope) { - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::criteria-from-fetch-example[] CriteriaBuilder builder = entityManager.getCriteriaBuilder(); - CriteriaQuery criteria = builder.createQuery(Phone.class); - Root root = criteria.from(Phone.class); + CriteriaQuery criteria = builder.createQuery( Phone.class ); + Root root = criteria.from( Phone.class ); // Phone.person is a @ManyToOne - Fetch personFetch = root.fetch(Phone_.person); + Fetch personFetch = root.fetch( Phone_.person ); // Person.addresses is an @ElementCollection - Fetch addressesJoin = personFetch.fetch(Person_.addresses); + Fetch addressesJoin = personFetch.fetch( Person_.addresses ); - criteria.where(builder.isNotEmpty(root.get(Phone_.calls))); + criteria.where( builder.isNotEmpty( root.get( Phone_.calls ) ) ); - List phones = entityManager.createQuery(criteria).getResultList(); + List phones = entityManager.createQuery( criteria ).getResultList(); //end::criteria-from-fetch-example[] - assertEquals(1, phones.size()); - }); + assertThat( phones ).hasSize( 1 ); + } ); } @Test - public void test_criteria_param_example() { + public void test_criteria_param_example(EntityManagerFactoryScope scope) { - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::criteria-param-example[] CriteriaBuilder builder = entityManager.getCriteriaBuilder(); - CriteriaQuery criteria = builder.createQuery(Person.class); - Root root = criteria.from(Person.class); + CriteriaQuery criteria = builder.createQuery( Person.class ); + Root root = criteria.from( Person.class ); - ParameterExpression nickNameParameter = builder.parameter(String.class); - criteria.where(builder.equal(root.get(Person_.nickName), nickNameParameter)); + ParameterExpression nickNameParameter = builder.parameter( String.class ); + criteria.where( builder.equal( root.get( Person_.nickName ), nickNameParameter ) ); - TypedQuery query = entityManager.createQuery(criteria); - query.setParameter(nickNameParameter, "JD"); + TypedQuery query = entityManager.createQuery( criteria ); + query.setParameter( nickNameParameter, "JD" ); List persons = query.getResultList(); //end::criteria-param-example[] - assertEquals(1, persons.size()); - }); + assertThat( persons ).hasSize( 1 ); + } ); } @Test - public void test_criteria_group_by_example() { + public void test_criteria_group_by_example(EntityManagerFactoryScope scope) { - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::criteria-group-by-example[] CriteriaBuilder builder = entityManager.getCriteriaBuilder(); - CriteriaQuery criteria = builder.createQuery(Tuple.class); - Root root = criteria.from(Person.class); + CriteriaQuery criteria = builder.createQuery( Tuple.class ); + Root root = criteria.from( Person.class ); - criteria.groupBy(root.get("address")); - criteria.multiselect(root.get("address"), builder.count(root)); + criteria.groupBy( root.get( "address" ) ); + criteria.multiselect( root.get( "address" ), builder.count( root ) ); - List tuples = entityManager.createQuery(criteria).getResultList(); + List tuples = entityManager.createQuery( criteria ).getResultList(); - for (Tuple tuple : tuples) { - String name = (String) tuple.get(0); - Long count = (Long) tuple.get(1); + for ( Tuple tuple : tuples ) { + String name = (String) tuple.get( 0 ); + Long count = (Long) tuple.get( 1 ); } //end::criteria-group-by-example[] - assertEquals(2, tuples.size()); - }); + assertThat( tuples ).hasSize( 2 ); + } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/HHH13884Test.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/HHH13884Test.java index 88486efae3db..8c946c821714 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/HHH13884Test.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/HHH13884Test.java @@ -5,23 +5,20 @@ package org.hibernate.orm.test.query.criteria.internal; import jakarta.persistence.criteria.Order; - import org.hibernate.query.sqm.tree.expression.SqmExpression; import org.hibernate.query.sqm.tree.select.SqmSortSpecification; - +import org.hibernate.testing.orm.junit.BaseUnitTest; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** * @author seregamorph */ @JiraKey(value = "HHH-13884") +@BaseUnitTest public class HHH13884Test { @Test @@ -30,14 +27,20 @@ public void testDefaultReversedOrderImpl() { SqmSortSpecification order = new SqmSortSpecification( expression ); - assertEquals( expression, order.getExpression() ); - assertTrue( "Order should be ascending by default", order.isAscending() ); + assertThat( order.getExpression() ).isEqualTo( expression ); + assertThat( order.isAscending() ) + .describedAs( "Order should be ascending by default" ) + .isTrue(); Order reversed = order.reverse(); - assertEquals( expression, reversed.getExpression() ); - assertFalse( "Reversed Order should be descending", reversed.isAscending() ); + assertThat( reversed.getExpression() ).isEqualTo( expression ); + assertThat( reversed.isAscending() ) + .describedAs( "Reversed Order should be descending" ) + .isFalse(); - assertNotSame( "Order.reverse() should create new instance by the contract", order, reversed ); + assertThat( reversed ) + .describedAs( "Order.reverse() should create new instance by the contract" ) + .isNotSameAs( order ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/hhh11877/HHH111877Test.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/hhh11877/HHH111877Test.java index 24f0d9f3d116..973e397f4306 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/hhh11877/HHH111877Test.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/hhh11877/HHH111877Test.java @@ -8,32 +8,29 @@ import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Root; - -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.DialectFeatureChecks; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.junit.jupiter.api.Test; /** * @author Archie Cobbs * @author Nathan Xu */ -@JiraKey( value = "HHH-11877" ) -@RequiresDialectFeature(DialectChecks.SupportsIdentityColumns.class) -public class HHH111877Test extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Foo.class }; - } +@JiraKey(value = "HHH-11877") +@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsIdentityColumns.class) +@Jpa( + annotatedClasses = { + Foo.class + } +) +public class HHH111877Test { @Test - public void testNoExceptionThrow() { - doInJPA( this::entityManagerFactory, entityManager -> { + public void testNoExceptionThrow(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); final CriteriaQuery cq = cb.createQuery( Foo.class ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/hhh13058/HHH13058Test.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/hhh13058/HHH13058Test.java index 402967f01345..693a70694a0d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/hhh13058/HHH13058Test.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/hhh13058/HHH13058Test.java @@ -4,33 +4,40 @@ */ package org.hibernate.orm.test.query.criteria.internal.hhh13058; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.From; import jakarta.persistence.criteria.JoinType; import jakarta.persistence.criteria.Root; import jakarta.persistence.criteria.Subquery; - -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - +import org.hibernate.SessionFactory; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; -import static org.hamcrest.CoreMatchers.is; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Archie Cobbs * @author Nathan Xu */ -@JiraKey( value = "HHH-13058" ) -public class HHH13058Test extends BaseEntityManagerFunctionalTestCase { +@JiraKey(value = "HHH-13058") +@Jpa( + annotatedClasses = { + Task.class, + Patient.class, + Site.class + } +) +public class HHH13058Test { private Set validSites; @@ -41,18 +48,9 @@ public class HHH13058Test extends BaseEntityManagerFunctionalTestCase { private Task taskWithPatient3WithValidSite2; private Task taskWithPatientWithInvalidSite; - @Override - public Class[] getAnnotatedClasses() { - return new Class[] { - Task.class, - Patient.class, - Site.class - }; - } - - @Before - public void setUp() { - doInJPA( this::entityManagerFactory, entityManager -> { + @BeforeEach + public void setUp(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { final Site validSite1 = new Site(); final Site validSite2 = new Site(); final Site invalidSite = new Site(); @@ -102,9 +100,14 @@ public void setUp() { } ); } + @AfterEach + public void tearDown(EntityManagerFactoryScope scope) { + scope.getEntityManagerFactory().unwrap( SessionFactory.class ).getSchemaManager().truncateMappedObjects(); + } + @Test - public void testCorrelateSubQueryLeftJoin() { - doInJPA( this::entityManagerFactory, entityManager -> { + public void testCorrelateSubQueryLeftJoin(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { final CriteriaBuilder builder = entityManager.getCriteriaBuilder(); final CriteriaQuery outerQuery = builder.createQuery( Task.class ); final Root outerTask = outerQuery.from( Task.class ); @@ -118,19 +121,20 @@ public void testCorrelateSubQueryLeftJoin() { subquery.select( subtask ) .where( builder.or( - patient.isNull(), - site.in( validSites ) + patient.isNull(), + site.in( validSites ) ) ) ) ); final List tasks = entityManager.createQuery( outerQuery ).getResultList(); - assertThat( new HashSet<>( tasks ), is( new HashSet<>( Arrays.asList( - taskWithoutPatient, - taskWithPatient1WithValidSite1, - taskWithPatient2WithValidSite1, - taskWithPatient3WithValidSite2 - ) ) ) ); + assertThat( new HashSet<>( tasks ) ) + .isEqualTo( new HashSet<>( Arrays.asList( + taskWithoutPatient, + taskWithPatient1WithValidSite1, + taskWithPatient2WithValidSite1, + taskWithPatient3WithValidSite2 + ) ) ); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/hhh13908/HHH13908Test.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/hhh13908/HHH13908Test.java index 4d624835fdb2..edf61cf0a483 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/hhh13908/HHH13908Test.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/hhh13908/HHH13908Test.java @@ -7,32 +7,29 @@ import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Root; - import org.hibernate.dialect.MySQLDialect; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.junit.jupiter.api.Test; /** * @author Archie Cobbs * @author Nathan Xu */ -@RequiresDialect( value = MySQLDialect.class, strictMatching = true ) -public class HHH13908Test extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Foo.class }; - } +@RequiresDialect(value = MySQLDialect.class) +@Jpa( + annotatedClasses = { + Foo.class + } +) +public class HHH13908Test { @Test - @JiraKey( value = "HHH-13908" ) - public void testTimeFunctionNotThrowException() { - doInJPA( this::entityManagerFactory, entityManager -> { + @JiraKey(value = "HHH-13908") + public void testTimeFunctionNotThrowException(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); final CriteriaQuery cq = cb.createQuery( Foo.class ); final Root foo = cq.from( Foo.class ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/hhh14197/HHH14197Test.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/hhh14197/HHH14197Test.java index db5a0909a013..e6de48584495 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/hhh14197/HHH14197Test.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/hhh14197/HHH14197Test.java @@ -9,37 +9,32 @@ import jakarta.persistence.criteria.Root; import jakarta.persistence.criteria.SetJoin; import jakarta.persistence.criteria.Subquery; - -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.DialectFeatureChecks; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.junit.jupiter.api.Test; /** * @author Archie Cobbs * @author Nathan Xu */ -@JiraKey( value = "HHH-14197" ) -@RequiresDialectFeature(DialectChecks.SupportsIdentityColumns.class) -public class HHH14197Test extends BaseEntityManagerFunctionalTestCase { - - @Override - public Class[] getAnnotatedClasses() { - return new Class[] { +@JiraKey(value = "HHH-14197") +@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsIdentityColumns.class) +@Jpa( + annotatedClasses = { Department.class, Employee.class - }; - } + } +) +public class HHH14197Test { @Test - public void testValidSQLGenerated() { + public void testValidSQLGenerated(EntityManagerFactoryScope scope) { // without fixing HHH-14197, invalid SQL would be generated without root // "... where exists (select employee0_.id as id1_1_ from where ...) ... " - doInJPA( this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); final CriteriaQuery query = cb.createQuery( Employee.class ); final Root employee = query.from( Employee.class ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh13670/HHH13670Test.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh13670/HHH13670Test.java index 6b797017d132..66c472e195a7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh13670/HHH13670Test.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh13670/HHH13670Test.java @@ -4,11 +4,6 @@ */ package org.hibernate.orm.test.query.hhh13670; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Before; -import org.junit.Test; - import jakarta.persistence.Column; import jakarta.persistence.ConstraintMode; import jakarta.persistence.Entity; @@ -20,155 +15,186 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.Tuple; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.JiraKey; +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.Test; + import java.util.List; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; + @JiraKey(value = "HHH-13670") -public class HHH13670Test extends BaseCoreFunctionalTestCase { - - @Before - public void setUp() { - doInJPA(this::sessionFactory, em -> { - SubA a_1 = new SubA(1L); - SubA a_2 = new SubA(2L); - SubA a_3 = new SubA(3L); - SubA a_14 = em.getReference(SubA.class, 10L); - SubB b_4 = new SubB(4L, null); - SubB b_5 = new SubB(5L, a_3); - SubB b_6 = new SubB(6L, b_4); - SubB b_7 = new SubB(7L, a_14); - - em.merge(a_1); - em.merge(a_2); - em.merge(a_3); - em.merge(b_4); - em.merge(b_5); - em.merge(b_6); - em.merge(b_7); - }); +@DomainModel( + annotatedClasses = { + HHH13670Test.Super.class, + HHH13670Test.SubA.class, + HHH13670Test.SubB.class + } +) +@SessionFactory +public class HHH13670Test { + + @BeforeAll + public void setUp(SessionFactoryScope scope) { + scope.inTransaction( em -> { + SubA a_1 = new SubA( 1L ); + SubA a_2 = new SubA( 2L ); + SubA a_3 = new SubA( 3L ); + SubA a_14 = em.getReference( SubA.class, 10L ); + SubB b_4 = new SubB( 4L, null ); + SubB b_5 = new SubB( 5L, a_3 ); + SubB b_6 = new SubB( 6L, b_4 ); + SubB b_7 = new SubB( 7L, a_14 ); + + em.merge( a_1 ); + em.merge( a_2 ); + em.merge( a_3 ); + em.merge( b_4 ); + em.merge( b_5 ); + em.merge( b_6 ); + em.merge( b_7 ); + } ); } @Test - public void testDereferenceSuperClassAttributeInWithClause() { - doInJPA(this::sessionFactory, em -> { - em.createQuery("SELECT subB_0.id FROM SubB subB_0 LEFT JOIN subB_0.other subA_0 ON subA_0.id = subB_0.parent.id", Tuple.class).getResultList(); - }); + public void testDereferenceSuperClassAttributeInWithClause(SessionFactoryScope scope) { + scope.inTransaction( session -> { + session.createQuery( + "SELECT subB_0.id FROM SubB subB_0 LEFT JOIN subB_0.other subA_0 ON subA_0.id = subB_0.parent.id", + Tuple.class ).getResultList(); + } ); } @Test - public void testRootTypeJoinWithGroupJoins() { - doInJPA(this::sessionFactory, em -> { - List resultList = em.createQuery("SELECT subB_0.id, subA_0.id, subB_0.id, subA_0.id FROM SubB subB_0 LEFT JOIN Super subA_0 ON subA_0.id = subB_0.parent.id ORDER BY subB_0.id ASC, subA_0.id ASC", Tuple.class) + public void testRootTypeJoinWithGroupJoins(SessionFactoryScope scope) { + scope.inTransaction( session -> { + List resultList = session.createQuery( + "SELECT subB_0.id, subA_0.id, subB_0.id, subA_0.id FROM SubB subB_0 LEFT JOIN Super subA_0 ON subA_0.id = subB_0.parent.id ORDER BY subB_0.id ASC, subA_0.id ASC", + Tuple.class ) .getResultList(); - - assertEquals("Rows omitted despite optional association should have rendered a left join", 4, resultList.size()); - - assertEquals((Long) 4L , resultList.get(0).get(0)); - assertEquals((Long) 5L , resultList.get(1).get(0)); - assertEquals((Long) 6L , resultList.get(2).get(0)); - assertEquals((Long) 7L , resultList.get(3).get(0)); - - assertNull(resultList.get(0).get(1, Long.class)); - assertEquals((Long) 3L , resultList.get(1).get(1, Long.class)); - assertEquals((Long) 4L , resultList.get(2).get(1, Long.class)); - assertNull("Missing entry in foreign table should not be returned", resultList.get(3).get(1, Long.class)); - }); + assertThat( resultList ) + .describedAs( "Rows omitted despite optional association should have rendered a left join" ) + .hasSize( 4 ); + + assertThat( resultList.get( 0 ).get( 0 ) ).isEqualTo( 4L ); + assertThat( resultList.get( 1 ).get( 0 ) ).isEqualTo( 5L ); + assertThat( resultList.get( 2 ).get( 0 ) ).isEqualTo( 6L ); + assertThat( resultList.get( 3 ).get( 0 ) ).isEqualTo( 7L ); + + assertThat( resultList.get( 0 ).get( 1, Long.class ) ).isNull(); + assertThat( resultList.get( 1 ).get( 1, Long.class ) ).isEqualTo( 3L ); + assertThat( resultList.get( 2 ).get( 1, Long.class ) ).isEqualTo( 4L ); + assertThat( resultList.get( 3 ).get( 1, Long.class ) ) + .describedAs( "Missing entry in foreign table should not be returned" ) + .isNull(); + } ); } @Test - public void testSubTypeJoinWithTableGroupJoins() { - doInJPA(this::sessionFactory, em -> { - List resultList = em.createQuery("SELECT subB_0.id, subA_0.id, subB_0.id, subA_0.id FROM SubB subB_0 LEFT JOIN SubA subA_0 ON subA_0.id = subB_0.parent.id ORDER BY subB_0.id ASC, subA_0.id ASC", Tuple.class) + public void testSubTypeJoinWithTableGroupJoins(SessionFactoryScope scope) { + scope.inTransaction( session -> { + List resultList = session.createQuery( + "SELECT subB_0.id, subA_0.id, subB_0.id, subA_0.id FROM SubB subB_0 LEFT JOIN SubA subA_0 ON subA_0.id = subB_0.parent.id ORDER BY subB_0.id ASC, subA_0.id ASC", + Tuple.class ) .getResultList(); - assertEquals("Rows omitted despite optional association should have rendered a left join", 4, resultList.size()); - - assertEquals((Long) 4L, resultList.get(0).get(0)); - assertEquals((Long) 5L, resultList.get(1).get(0)); - assertEquals((Long) 6L, resultList.get(2).get(0)); - assertEquals((Long) 7L, resultList.get(3).get(0)); - - assertNull(resultList.get(0).get(1, Long.class)); - assertEquals((Long) 3L, resultList.get(1).get(1, Long.class)); - assertNull("Another subtype than queried for was returned", resultList.get(2).get(1)); - assertNull("Missing entry in foreign table should not be returned", resultList.get(3).get(1, Long.class)); - }); + assertThat( resultList ) + .describedAs( "Rows omitted despite optional association should have rendered a left join" ) + .hasSize( 4 ); + + assertThat( resultList.get( 0 ).get( 0 ) ).isEqualTo( 4L ); + assertThat( resultList.get( 1 ).get( 0 ) ).isEqualTo( 5L ); + assertThat( resultList.get( 2 ).get( 0 ) ).isEqualTo( 6L ); + assertThat( resultList.get( 3 ).get( 0 ) ).isEqualTo( 7L ); + + assertThat( resultList.get( 0 ).get( 1, Long.class ) ).isNull(); + assertThat( resultList.get( 1 ).get( 1, Long.class ) ).isEqualTo( 3L ); + assertThat( resultList.get( 2 ).get( 1 ) ) + .describedAs( "Another subtype than queried for was returned" ) + .isNull(); + assertThat( resultList.get( 3 ).get( 1, Long.class ) ) + .describedAs( "Missing entry in foreign table should not be returned" ) + .isNull(); + } ); } @Test - public void testSubTypePropertyReferencedFromEntityJoinInSyntheticSubquery() { - doInJPA(this::sessionFactory, em -> { - List resultList = em.createQuery( - "SELECT subB_0.id, subA_0.id, subB_0.id, subA_0.id FROM SubB subB_0 INNER JOIN SubA subA_0 ON 1=1 WHERE (EXISTS (SELECT 1 FROM subB_0.parent _synth_subquery_0 WHERE subA_0.id = _synth_subquery_0.id)) ORDER BY subB_0.id ASC, subA_0.id ASC", Tuple.class) + public void testSubTypePropertyReferencedFromEntityJoinInSyntheticSubquery(SessionFactoryScope scope) { + scope.inTransaction( session -> { + List resultList = session.createQuery( + "SELECT subB_0.id, subA_0.id, subB_0.id, subA_0.id FROM SubB subB_0 INNER JOIN SubA subA_0 ON 1=1 WHERE (EXISTS (SELECT 1 FROM subB_0.parent _synth_subquery_0 WHERE subA_0.id = _synth_subquery_0.id)) ORDER BY subB_0.id ASC, subA_0.id ASC", + Tuple.class ) .getResultList(); - assertEquals(1, resultList.size()); - }); + assertThat( resultList ).hasSize( 1 ); + } ); } @Test - public void testSubTypePropertyReferencedFromEntityJoinInSyntheticSubquery2() { - doInJPA(this::sessionFactory, em -> { - List resultList = em.createQuery( - "SELECT subB_0.id, subA_0.id, subB_0.id, subA_0.id FROM SubB subB_0 INNER JOIN SubA subA_0 ON 1=1 WHERE (EXISTS (SELECT 1 FROM Super s WHERE subA_0.id = s.parent.id)) ORDER BY subB_0.id ASC, subA_0.id ASC", Tuple.class) + public void testSubTypePropertyReferencedFromEntityJoinInSyntheticSubquery2(SessionFactoryScope scope) { + scope.inTransaction( session -> { + List resultList = session.createQuery( + "SELECT subB_0.id, subA_0.id, subB_0.id, subA_0.id FROM SubB subB_0 INNER JOIN SubA subA_0 ON 1=1 WHERE (EXISTS (SELECT 1 FROM Super s WHERE subA_0.id = s.parent.id)) ORDER BY subB_0.id ASC, subA_0.id ASC", + Tuple.class ) .getResultList(); - assertEquals(4, resultList.size()); - }); + assertThat( resultList ).hasSize( 4 ); + } ); } @Test - public void testSubTypePropertyReferencedFromEntityJoinInSyntheticSubquery3() { - doInJPA(this::sessionFactory, em -> { - List resultList = em.createQuery( - "SELECT subB_0.id, subA_0.id, subB_0.id, subA_0.id FROM SubB subB_0 INNER JOIN SubA subA_0 ON 1=1 WHERE (EXISTS (SELECT 1 FROM Super s WHERE s.id = subB_0.parent.id)) ORDER BY subB_0.id ASC, subA_0.id ASC", Tuple.class) + public void testSubTypePropertyReferencedFromEntityJoinInSyntheticSubquery3(SessionFactoryScope scope) { + scope.inTransaction( session -> { + List resultList = session.createQuery( + "SELECT subB_0.id, subA_0.id, subB_0.id, subA_0.id FROM SubB subB_0 INNER JOIN SubA subA_0 ON 1=1 WHERE (EXISTS (SELECT 1 FROM Super s WHERE s.id = subB_0.parent.id)) ORDER BY subB_0.id ASC, subA_0.id ASC", + Tuple.class ) .getResultList(); - assertEquals(6, resultList.size()); - }); + assertThat( resultList ).hasSize( 6 ); + } ); } @Test - public void testSubTypePropertyReferencedFromEntityJoinInSyntheticSubquery4() { - doInJPA(this::sessionFactory, em -> { - List resultList = em.createQuery( - "SELECT subB_0.id, subA_0.id, subB_0.id, subA_0.id FROM SubB subB_0 INNER JOIN SubA subA_0 ON 1=1 WHERE (EXISTS (SELECT 1 FROM Super s WHERE s.id = subA_0.parent.id)) ORDER BY subB_0.id ASC, subA_0.id ASC", Tuple.class) + public void testSubTypePropertyReferencedFromEntityJoinInSyntheticSubquery4(SessionFactoryScope scope) { + scope.inTransaction( session -> { + List resultList = session.createQuery( + "SELECT subB_0.id, subA_0.id, subB_0.id, subA_0.id FROM SubB subB_0 INNER JOIN SubA subA_0 ON 1=1 WHERE (EXISTS (SELECT 1 FROM Super s WHERE s.id = subA_0.parent.id)) ORDER BY subB_0.id ASC, subA_0.id ASC", + Tuple.class ) .getResultList(); - assertEquals(0, resultList.size()); - }); + assertThat( resultList ).hasSize( 0 ); + } ); } @Test - public void testSubTypePropertyReferencedFromWhereClause() { - doInJPA(this::sessionFactory, em -> { - List resultList = em.createQuery("SELECT subB_0.id FROM SubB subB_0 WHERE subB_0.parent.id IS NOT NULL", Tuple.class) + public void testSubTypePropertyReferencedFromWhereClause(SessionFactoryScope scope) { + scope.inTransaction( session -> { + List resultList = session.createQuery( + "SELECT subB_0.id FROM SubB subB_0 WHERE subB_0.parent.id IS NOT NULL", Tuple.class ) .getResultList(); - }); + } ); } @Test - public void testSubTypePropertyReferencedFromGroupByClause() { - doInJPA(this::sessionFactory, em -> { - List resultList = em.createQuery("SELECT subB_0.id FROM SubB subB_0 GROUP BY subB_0.id , subB_0.parent.id", Tuple.class) + public void testSubTypePropertyReferencedFromGroupByClause(SessionFactoryScope scope) { + scope.inTransaction( session -> { + List resultList = session.createQuery( + "SELECT subB_0.id FROM SubB subB_0 GROUP BY subB_0.id , subB_0.parent.id", Tuple.class ) .getResultList(); - }); + } ); } @Test - public void testSubTypePropertyReferencedFromOrderByClause() { - doInJPA(this::sessionFactory, em -> { - List resultList = em.createQuery("SELECT subB_0.id FROM SubB subB_0 ORDER BY subB_0.id , subB_0.parent.id", Tuple.class) + public void testSubTypePropertyReferencedFromOrderByClause(SessionFactoryScope scope) { + scope.inTransaction( session -> { + List resultList = session.createQuery( + "SELECT subB_0.id FROM SubB subB_0 ORDER BY subB_0.id , subB_0.parent.id", Tuple.class ) .getResultList(); - }); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Super.class, SubA.class, SubB.class }; + } ); } @Entity(name = "Super") @@ -188,7 +214,8 @@ public static class Super { @Entity(name = "SubA") public static class SubA extends Super { - SubA() {} + SubA() { + } SubA(Long id) { this.id = id; @@ -202,7 +229,8 @@ public static class SubB extends Super { @ManyToOne(fetch = FetchType.LAZY) Super other; - SubB() {} + SubB() { + } SubB(Long id, Super parent) { this.id = id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh14112/HHH14112Test.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh14112/HHH14112Test.java index 10fb447e8328..5c03635b7c71 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh14112/HHH14112Test.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh14112/HHH14112Test.java @@ -10,32 +10,36 @@ import jakarta.persistence.Id; import jakarta.persistence.Inheritance; import jakarta.persistence.InheritanceType; - import org.hibernate.annotations.SQLRestriction; - +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.hibernate.testing.transaction.TransactionUtil.doInJPA; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Ganesh Tiwari * @author Nathan Xu */ @JiraKey(value = "HHH-14112") -public class HHH14112Test extends BaseCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + HHH14112Test.Super.class, + HHH14112Test.SubObject.class + } +) +@SessionFactory +public class HHH14112Test { @Test - public void testCountSubObjectNotThrownExceptionBecauseOfWhere() { - doInJPA(this::sessionFactory, em -> { - em.createQuery( "SELECT count(*) FROM SubObject", Long.class).getSingleResult(); - }); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Super.class, SubObject.class }; + public void testCountSubObjectNotThrownExceptionBecauseOfWhere(SessionFactoryScope scope) { + scope.inTransaction( session -> { + Long result = session.createQuery( "SELECT count(*) FROM SubObject", Long.class ).getSingleResult(); + assertThat( result ).isEqualTo( 0L ); + } + ); } @Entity(name = "Super") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh14116/HHH14116Test.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh14116/HHH14116Test.java index 3b9f5fc1cab5..89bdc130afa7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh14116/HHH14116Test.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh14116/HHH14116Test.java @@ -4,7 +4,6 @@ */ package org.hibernate.orm.test.query.hhh14116; -import java.util.Set; import jakarta.persistence.ElementCollection; import jakarta.persistence.Entity; import jakarta.persistence.EnumType; @@ -15,33 +14,41 @@ import jakarta.persistence.ManyToMany; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; - +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 java.util.List; +import java.util.Set; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Beikov * @author Nathan Xu */ -@JiraKey( value = "HHH-14116" ) -public class HHH14116Test extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { User.class, Group.class }; - } +@JiraKey(value = "HHH-14116") +@DomainModel( + annotatedClasses = { + HHH14116Test.User.class, + HHH14116Test.Group.class + } +) +@SessionFactory +public class HHH14116Test { @Test - public void testNoExceptionThrown() { - doInJPA( this::sessionFactory, em -> { - em.createQuery( - "SELECT g FROM User u JOIN u.groups g JOIN FETCH g.permissions JOIN FETCH g.tenant where u.id = ?1", Group.class ) - .setParameter(1, 1L ) - .getResultList(); - } + public void testNoExceptionThrown(SessionFactoryScope scope) { + scope.inTransaction( session -> { + List resultList = session.createQuery( + "SELECT g FROM User u JOIN u.groups g JOIN FETCH g.permissions JOIN FETCH g.tenant where u.id = ?1", + Group.class ) + .setParameter( 1, 1L ) + .getResultList(); + assertThat( resultList ).hasSize( 0 ); + } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh14154/HHH14154Test.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh14154/HHH14154Test.java index 89c8b47093a4..fcabf0d22350 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh14154/HHH14154Test.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh14154/HHH14154Test.java @@ -4,52 +4,51 @@ */ package org.hibernate.orm.test.query.hhh14154; -import java.util.Date; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Root; - import org.hibernate.dialect.H2Dialect; - -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import java.util.Date; /** * @author Archie Cobbs * @author Nathan Xu */ -@RequiresDialect( H2Dialect.class ) -@JiraKey( value = "HHH-14154" ) -public class HHH14154Test extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Foo.class }; - } +@RequiresDialect(H2Dialect.class) +@JiraKey(value = "HHH-14154") +@Jpa( + annotatedClasses = { + HHH14154Test.Foo.class + } +) +public class HHH14154Test { @Test - public void testNoExceptionThrown() { - doInJPA( this::sessionFactory, em -> { + public void testNoExceptionThrown(EntityManagerFactoryScope scope) { + scope.inTransaction( em -> { final CriteriaBuilder cb = em.getCriteriaBuilder(); final CriteriaQuery cq = cb.createQuery( Foo.class ); final Root foo = cq.from( Foo.class ); - cq.select(foo) - .where( - cb.lessThanOrEqualTo( - cb.concat( - cb.function( "FORMATDATETIME", String.class, foo.get( "startTime" ), cb.literal( "HH:mm:ss" ) ), - "" - ), - "17:00:00" - ) - ); + cq.select( foo ) + .where( + cb.lessThanOrEqualTo( + cb.concat( + cb.function( "FORMATDATETIME", String.class, foo.get( "startTime" ), + cb.literal( "HH:mm:ss" ) ), + "" + ), + "17:00:00" + ) + ); em.createQuery( cq ).getResultList(); } ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh14156/HHH14156Test.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh14156/HHH14156Test.java index 36aa93d2ec49..6e3ece7c23ea 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh14156/HHH14156Test.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh14156/HHH14156Test.java @@ -7,30 +7,33 @@ import java.io.Serializable; import java.util.Objects; +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.Embeddable; import jakarta.persistence.EmbeddedId; import jakarta.persistence.Entity; import jakarta.persistence.Table; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; /** * @author Nathan Xu * @author Christian Beikov */ @JiraKey( value = "HHH-14156" ) -public class HHH14156Test extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { EntityWithCompositeId.class }; - } +@DomainModel( + annotatedClasses = { + HHH14156Test.EntityWithCompositeId.class + } +) +@SessionFactory +public class HHH14156Test{ @Test - public void testNoExceptionThrown() { - inTransaction( session -> + public void testNoExceptionThrown(SessionFactoryScope scope) { + scope.inTransaction( session -> session.createQuery( "from EntityWithCompositeId e where e in (select e2 from EntityWithCompositeId e2)", EntityWithCompositeId.class diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/CountExpressionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/CountExpressionTest.java index a3be60506bf6..a9d25d9411ca 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/CountExpressionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/CountExpressionTest.java @@ -4,9 +4,6 @@ */ package org.hibernate.orm.test.query.hql; -import java.util.HashMap; -import java.util.List; -import java.util.Map; import jakarta.persistence.CollectionTable; import jakarta.persistence.ElementCollection; import jakarta.persistence.Entity; @@ -14,76 +11,83 @@ import jakarta.persistence.Id; import jakarta.persistence.MapKeyColumn; import jakarta.persistence.OneToMany; - import org.hibernate.community.dialect.InformixDialect; +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.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.testing.orm.junit.SkipForDialect; -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.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Beikov */ -public class CountExpressionTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Document.class, - Person.class, - CountDistinctTestEntity.class - }; - } +@DomainModel( + annotatedClasses = { + CountExpressionTest.Document.class, + CountExpressionTest.Person.class, + CountExpressionTest.CountDistinctTestEntity.class + } +) +@SessionFactory +public class CountExpressionTest { - @Override - protected void prepareTest() throws Exception { - doInHibernate( this::sessionFactory, session -> { + @BeforeEach + public void prepareTest(SessionFactoryScope scope) throws Exception { + scope.inTransaction( session -> { Document document = new Document(); document.setId( 1 ); Person p1 = new Person(); Person p2 = new Person(); - p1.getLocalized().put(1, "p1.1"); - p1.getLocalized().put(2, "p1.2"); - p2.getLocalized().put(1, "p2.1"); - p2.getLocalized().put(2, "p2.2"); + p1.getLocalized().put( 1, "p1.1" ); + p1.getLocalized().put( 2, "p1.2" ); + p2.getLocalized().put( 1, "p2.1" ); + p2.getLocalized().put( 2, "p2.2" ); - document.getContacts().put(1, p1); - document.getContacts().put(2, p2); + document.getContacts().put( 1, p1 ); + document.getContacts().put( 2, p2 ); - session.persist(p1); - session.persist(p2); - session.persist(document); + session.persist( p1 ); + session.persist( p2 ); + session.persist( document ); } ); } - @Override - protected boolean isCleanupTestDataRequired() { - return true; + @AfterEach + public void tearDown(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } + @Test @JiraKey(value = "HHH-9182") - public void testCountDistinctExpression() { - doInHibernate( this::sessionFactory, session -> { + public void testCountDistinctExpression(SessionFactoryScope scope) { + scope.inTransaction( session -> { List results = session.createQuery( - "SELECT " + - " d.id, " + - " COUNT(DISTINCT CONCAT(CAST(KEY(l) AS String), 'test')) " + - "FROM Document d " + - "LEFT JOIN d.contacts c " + - "LEFT JOIN c.localized l " + - "GROUP BY d.id") - .getResultList(); - - assertEquals(1, results.size()); + "SELECT " + + " d.id, " + + " COUNT(DISTINCT CONCAT(CAST(KEY(l) AS String), 'test')) " + + "FROM Document d " + + "LEFT JOIN d.contacts c " + + "LEFT JOIN c.localized l " + + "GROUP BY d.id" ) + .getResultList(); + + assertThat( results ).hasSize( 1 ); + Object[] tuple = (Object[]) results.get( 0 ); - assertEquals(1, tuple[0]); - assertEquals(2L, tuple[1]); + assertThat( tuple[0] ).isEqualTo( 1 ); + assertThat( tuple[1] ).isEqualTo( 2L ); } ); } @@ -91,22 +95,23 @@ public void testCountDistinctExpression() { @JiraKey(value = "HHH-11042") @SkipForDialect(dialectClass = InformixDialect.class, reason = "Informix allows only one column in count(distinct)") - public void testCountDistinctTuple() { - doInHibernate( this::sessionFactory, session -> { + public void testCountDistinctTuple(SessionFactoryScope scope) { + scope.inTransaction( session -> { List results = session.createQuery( "SELECT " + - " d.id, " + - " COUNT(DISTINCT (KEY(l), l)) " + - "FROM Document d " + - "LEFT JOIN d.contacts c " + - "LEFT JOIN c.localized l " + - "GROUP BY d.id") + " d.id, " + + " COUNT(DISTINCT (KEY(l), l)) " + + "FROM Document d " + + "LEFT JOIN d.contacts c " + + "LEFT JOIN c.localized l " + + "GROUP BY d.id" ) .getResultList(); - assertEquals(1, results.size()); + assertThat( results ).hasSize( 1 ); + Object[] tuple = (Object[]) results.get( 0 ); - assertEquals(1, tuple[0]); - assertEquals(4L, tuple[1]); + assertThat( tuple[0] ).isEqualTo( 1 ); + assertThat( tuple[1] ).isEqualTo( 4L ); } ); } @@ -114,22 +119,22 @@ public void testCountDistinctTuple() { @JiraKey(value = "HHH-11042") @SkipForDialect(dialectClass = InformixDialect.class, reason = "Informix allows only one column in count(distinct)") - public void testCountDistinctTupleSanity() { - doInHibernate( this::sessionFactory, session -> { + public void testCountDistinctTupleSanity(SessionFactoryScope scope) { + scope.inTransaction( session -> { // A simple concatenation of tuple arguments would produce a distinct count of 1 in this case // This test checks if the chr(0) count tuple distinct emulation works correctly - session.persist( new CountDistinctTestEntity("10", "1") ); - session.persist( new CountDistinctTestEntity("1", "01") ); - List results = session.createQuery("SELECT count(distinct (t.x,t.y)) FROM CountDistinctTestEntity t", Long.class) + session.persist( new CountDistinctTestEntity( "10", "1" ) ); + session.persist( new CountDistinctTestEntity( "1", "01" ) ); + List results = session.createQuery( "SELECT count(distinct (t.x,t.y)) FROM CountDistinctTestEntity t", + Long.class ) .getResultList(); - assertEquals(1, results.size()); - assertEquals( 2L, results.get( 0 ).longValue() ); + assertThat( results ).hasSize( 1 ); + assertThat( results.get( 0 ) ).isEqualTo( 2L ); } ); } - @Entity(name = "Document") public static class Document { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/OrderByTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/OrderByTests.java index 638befdf6677..2c6150620a5f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/OrderByTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/OrderByTests.java @@ -3,37 +3,51 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.query.hql; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.junit.Test; import org.hibernate.Hibernate; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; - -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; - import org.hibernate.orm.test.hql.Address; import org.hibernate.orm.test.hql.Human; import org.hibernate.orm.test.hql.Mammal; import org.hibernate.orm.test.hql.Name; import org.hibernate.orm.test.hql.StateProvince; import org.hibernate.orm.test.hql.Zoo; +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.junit.jupiter.api.Timeout; + +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * Tests AST parser processing of ORDER BY clauses. * * @author Gail Badner */ -public class OrderByTests extends BaseCoreFunctionalTestCase { +@DomainModel( + xmlMappings = "org/hibernate/orm/test/hql/Animal.hbm.xml" +) +@SessionFactory( + generateStatistics = true +) +@ServiceRegistry( + settings = { + @Setting(name = Environment.USE_QUERY_CACHE, value = "false"), + } +) +public class OrderByTests { StateProvince stateProvince; private Zoo zoo1; private Zoo zoo2; @@ -46,26 +60,9 @@ public class OrderByTests extends BaseCoreFunctionalTestCase { Human zoo2Director1; Human zoo2Director2; - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } - - @Override - public String[] getMappings() { - return new String[] { - "hql/Animal.hbm.xml", - }; - } - @Override - public void configure(Configuration cfg) { - super.configure( cfg ); - cfg.setProperty( Environment.USE_QUERY_CACHE, false ); - cfg.setProperty( Environment.GENERATE_STATISTICS, true ); - } - - private void createData() { + @BeforeEach + private void createData(SessionFactoryScope scope) { stateProvince = new StateProvince(); stateProvince.setName( "IL" ); @@ -81,11 +78,11 @@ private void createData() { zoo1Mammal1 = new Mammal(); zoo1Mammal1.setDescription( "zoo1Mammal1" ); zoo1Mammal1.setZoo( zoo1 ); - zoo1.getMammals().put( "type1", zoo1Mammal1); + zoo1.getMammals().put( "type1", zoo1Mammal1 ); zoo1Mammal2 = new Mammal(); zoo1Mammal2.setDescription( "zoo1Mammal2" ); zoo1Mammal2.setZoo( zoo1 ); - zoo1.getMammals().put( "type1", zoo1Mammal2); + zoo1.getMammals().put( "type1", zoo1Mammal2 ); zoo2 = new Zoo(); zoo2.setName( "A Zoo" ); @@ -123,420 +120,371 @@ private void createData() { address4.setCountry( "USA" ); zoo4.setAddress( address4 ); - Session s = openSession(); - Transaction t = s.beginTransaction(); - s.persist( stateProvince ); - s.persist( zoo1Mammal1 ); - s.persist( zoo1Mammal2 ); - s.persist( zoo1 ); - s.persist( zoo2Director1 ); - s.persist( zoo2Director2 ); - s.persist( zoo2 ); - s.persist( zoo3 ); - s.persist( zoo4 ); - t.commit(); - s.close(); - - zoosWithSameName = new HashSet( 2 ); + scope.inTransaction( + session -> { + session.persist( stateProvince ); + session.persist( zoo1Mammal1 ); + session.persist( zoo1Mammal2 ); + session.persist( zoo1 ); + session.persist( zoo2Director1 ); + session.persist( zoo2Director2 ); + session.persist( zoo2 ); + session.persist( zoo3 ); + session.persist( zoo4 ); + } + ); + + zoosWithSameName = new HashSet<>( 2 ); zoosWithSameName.add( zoo1 ); zoosWithSameName.add( zoo3 ); - zoosWithSameAddress = new HashSet( 2 ); + zoosWithSameAddress = new HashSet<>( 2 ); zoosWithSameAddress.add( zoo1 ); zoosWithSameAddress.add( zoo2 ); } - private void cleanupData() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - if ( zoo1 != null ) { - s.remove( zoo1 ); - zoo1 = null; - } - if ( zoo2 != null ) { - s.remove( zoo2 ); - zoo2 = null; - } - if ( zoo3 != null ) { - s.remove( zoo3 ); - zoo3 = null; - } - if ( zoo4 != null ) { - s.remove( zoo4 ); - zoo4 = null; - } - if ( zoo1Mammal1 != null ) { - s.remove( zoo1Mammal1 ); - zoo1Mammal1 = null; - } - if ( zoo1Mammal2 != null ) { - s.remove( zoo1Mammal2 ); - zoo1Mammal2 = null; - } - if ( zoo2Director1 != null ) { - s.remove( zoo2Director1 ); - zoo2Director1 = null; - } - if ( zoo2Director2 != null ) { - s.remove( zoo2Director2 ); - zoo2Director2 = null; - } - if ( stateProvince != null ) { - s.remove( stateProvince ); - } - t.commit(); - s.close(); + @AfterEach + private void cleanupData(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Test - public void testOrderByOnJoinedSubclassPropertyWhoseColumnIsNotInDrivingTable() { + public void testOrderByOnJoinedSubclassPropertyWhoseColumnIsNotInDrivingTable(SessionFactoryScope scope) { // this is simply a syntax check - Session s = openSession(); - Transaction t = s.beginTransaction(); - s.createQuery( "from Human h order by h.bodyWeight" ).list(); - s.getTransaction().commit(); - s.close(); + scope.inTransaction( + session -> + session.createQuery( "from Human h order by h.bodyWeight" ).list() + ); } @Test - public void testOrderByNoSelectAliasRef() { - createData(); - - Session s = openSession(); - Transaction t = s.beginTransaction(); - - // ordered by name, address: - // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA - // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA - // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA - // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA - checkTestOrderByResults( - s.createQuery( - "select name, address from Zoo order by name, address", - Object[].class - ).list(), - zoo2, zoo4, zoo3, zoo1, null - ); - checkTestOrderByResults( - s.createQuery( - "select z.name, z.address from Zoo z order by z.name, z.address", - Object[].class - ).list(), - zoo2, zoo4, zoo3, zoo1, null - ); - checkTestOrderByResults( - s.createQuery( - "select z2.name, z2.address from Zoo z2 where z2.name in ( select name from Zoo ) order by z2.name, z2.address", - Object[].class - ).list(), - zoo2, zoo4, zoo3, zoo1, null - ); - // using ASC - checkTestOrderByResults( - s.createQuery( - "select name, address from Zoo order by name ASC, address ASC", - Object[].class - ).list(), - zoo2, zoo4, zoo3, zoo1, null - ); - checkTestOrderByResults( - s.createQuery( - "select z.name, z.address from Zoo z order by z.name ASC, z.address ASC", - Object[].class - ).list(), - zoo2, zoo4, zoo3, zoo1, null + public void testOrderByNoSelectAliasRef(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + // ordered by name, address: + // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA + // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA + // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA + // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA + checkTestOrderByResults( + session.createQuery( + "select name, address from Zoo order by name, address", + Object[].class + ).list(), + zoo2, zoo4, zoo3, zoo1, null + ); + checkTestOrderByResults( + session.createQuery( + "select z.name, z.address from Zoo z order by z.name, z.address", + Object[].class + ).list(), + zoo2, zoo4, zoo3, zoo1, null + ); + checkTestOrderByResults( + session.createQuery( + "select z2.name, z2.address from Zoo z2 where z2.name in ( select name from Zoo ) order by z2.name, z2.address", + Object[].class + ).list(), + zoo2, zoo4, zoo3, zoo1, null + ); + // using ASC + checkTestOrderByResults( + session.createQuery( + "select name, address from Zoo order by name ASC, address ASC", + Object[].class + ).list(), + zoo2, zoo4, zoo3, zoo1, null + ); + checkTestOrderByResults( + session.createQuery( + "select z.name, z.address from Zoo z order by z.name ASC, z.address ASC", + Object[].class + ).list(), + zoo2, zoo4, zoo3, zoo1, null + ); + checkTestOrderByResults( + session.createQuery( + "select z2.name, z2.address from Zoo z2 where z2.name in ( select name from Zoo ) order by z2.name ASC, z2.address ASC", + Object[].class + ).list(), + zoo2, zoo4, zoo3, zoo1, null + ); + + // ordered by address, name: + // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA + // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA + // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA + // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA + + // NOTE (6.0) : the above illustration is based on 5.x code. but the outcome + // is ultimately based on the order in which we render the attributes of + // the Address component. In 6.0 this has been made consistent and easily + // explainable, whereas that was not previously the case. + // checkTestOrderByResults( + // s.createQuery( + // "select z.name, z.address from Zoo z order by z.address, z.name" + // ).list(), + // zoo3, zoo4, zoo2, zoo1, null + // ); + + // NOTE (6.0) - continued : this is functionally equivalent to the 5.x case + checkTestOrderByResults( + session.createQuery( + "select z.name, z.address " + + "from Zoo z " + + "order by z.address.street," + + " z.address.city," + + " z.address.postalCode, " + + " z.address.country," + + " z.name", + Object[].class + ).list(), + zoo3, zoo4, zoo2, zoo1, null + ); + + // NOTE (6.0) - continued 2 : this is the 6.x functionally + // ordered by address, name: + // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA + // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA + // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA + // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA + checkTestOrderByResults( + session.createQuery( + "select z.name, z.address from Zoo z order by z.address, z.name", + Object[].class + ).list(), + zoo3, zoo2, zoo1, zoo4, null + ); + + // NOTE (6.0) - continued 3 : and the functionally equiv "full ordering" + checkTestOrderByResults( + session.createQuery( + "select z.name, z.address from Zoo z order by z.address.city, z.address.country, z.address.stateProvince, z.address.street, z.name", + Object[].class + ).list(), + zoo3, zoo2, zoo1, zoo4, null + ); + + checkTestOrderByResults( + session.createQuery( + "select name, address from Zoo order by address, name", + Object[].class + ).list(), + zoo3, zoo2, zoo1, zoo4, null + ); + + // ordered by address: + // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA + // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA + // unordered: + // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA + // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA + // + // NOTE 6.0 : these results are not well defined. Because we primarily order + // based on city zoo1, zoo2 and zoo3 are all sorted "above" zoo4. however + // the order between zoo1 and zoo2 is completely undefined because they + // have the same address + // + // and honestly, not even sure what this assertion is even trying to test. + // but changed the query to what you'd need to get those results - which I guess + // is the order used by 5.x + checkTestOrderByResults( + session.createQuery( + "select z.name, z.address from Zoo z order by z.address.street, z.address.city", + Object[].class + ).list(), + zoo3, zoo4, null, null, zoosWithSameAddress + ); + checkTestOrderByResults( + session.createQuery( + "select name, address from Zoo order by address.street, address.city", + Object[].class + ).list(), + zoo3, zoo4, null, null, zoosWithSameAddress + ); + + // ordered by name: + // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA + // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA + // unordered: + // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA + // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA + checkTestOrderByResults( + session.createQuery( + "select z.name, z.address from Zoo z order by z.name", + Object[].class + ).list(), + zoo2, zoo4, null, null, zoosWithSameName + ); + checkTestOrderByResults( + session.createQuery( + "select name, address from Zoo order by name", + Object[].class + ).list(), + zoo2, zoo4, null, null, zoosWithSameName + ); + } ); - checkTestOrderByResults( - s.createQuery( - "select z2.name, z2.address from Zoo z2 where z2.name in ( select name from Zoo ) order by z2.name ASC, z2.address ASC", - Object[].class - ).list(), - zoo2, zoo4, zoo3, zoo1, null - ); - - // ordered by address, name: - // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA - // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA - // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA - // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA - - // NOTE (6.0) : the above illustration is based on 5.x code. but the outcome - // is ultimately based on the order in which we render the attributes of - // the Address component. In 6.0 this has been made consistent and easily - // explainable, whereas that was not previously the case. -// checkTestOrderByResults( -// s.createQuery( -// "select z.name, z.address from Zoo z order by z.address, z.name" -// ).list(), -// zoo3, zoo4, zoo2, zoo1, null -// ); - - // NOTE (6.0) - continued : this is functionally equivalent to the 5.x case - checkTestOrderByResults( - s.createQuery( - "select z.name, z.address " + - "from Zoo z " + - "order by z.address.street," + - " z.address.city," + - " z.address.postalCode, " + - " z.address.country," + - " z.name", - Object[].class - ).list(), - zoo3, zoo4, zoo2, zoo1, null - ); - - // NOTE (6.0) - continued 2 : this is the 6.x functionally - // ordered by address, name: - // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA - // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA - // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA - // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA - checkTestOrderByResults( - s.createQuery( - "select z.name, z.address from Zoo z order by z.address, z.name", - Object[].class - ).list(), - zoo3, zoo2, zoo1, zoo4, null - ); - - // NOTE (6.0) - continued 3 : and the functionally equiv "full ordering" - checkTestOrderByResults( - s.createQuery( - "select z.name, z.address from Zoo z order by z.address.city, z.address.country, z.address.stateProvince, z.address.street, z.name", - Object[].class - ).list(), - zoo3, zoo2, zoo1, zoo4, null - ); - - checkTestOrderByResults( - s.createQuery( - "select name, address from Zoo order by address, name", - Object[].class - ).list(), - zoo3, zoo2, zoo1, zoo4, null - ); - - // ordered by address: - // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA - // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA - // unordered: - // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA - // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA - // - // NOTE 6.0 : these results are not well defined. Because we primarily order - // based on city zoo1, zoo2 and zoo3 are all sorted "above" zoo4. however - // the order between zoo1 and zoo2 is completely undefined because they - // have the same address - // - // and honestly, not even sure what this assertion is even trying to test. - // but changed the query to what you'd need to get those results - which I guess - // is the order used by 5.x - checkTestOrderByResults( - s.createQuery( - "select z.name, z.address from Zoo z order by z.address.street, z.address.city", - Object[].class - ).list(), - zoo3, zoo4, null, null, zoosWithSameAddress - ); - checkTestOrderByResults( - s.createQuery( - "select name, address from Zoo order by address.street, address.city", - Object[].class - ).list(), - zoo3, zoo4, null, null, zoosWithSameAddress - ); - - // ordered by name: - // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA - // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA - // unordered: - // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA - // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA - checkTestOrderByResults( - s.createQuery( - "select z.name, z.address from Zoo z order by z.name", - Object[].class - ).list(), - zoo2, zoo4, null, null, zoosWithSameName - ); - checkTestOrderByResults( - s.createQuery( - "select name, address from Zoo order by name", - Object[].class - ).list(), - zoo2, zoo4, null, null, zoosWithSameName - ); - t.commit(); - s.close(); - - cleanupData(); } @Test - public void testOrderByComponentDescNoSelectAliasRef() { - createData(); - - Session s = openSession(); - Transaction t = s.beginTransaction(); - + public void testOrderByComponentDescNoSelectAliasRef(SessionFactoryScope scope) { // ordered by address DESC, name DESC: // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA - checkTestOrderByResults( - s.createQuery( - "select z.name, z.address from Zoo z order by z.address DESC, z.name DESC", - Object[].class - ).list(), - zoo4, zoo1, zoo2, zoo3, null - ); - checkTestOrderByResults( - s.createQuery( - "select name, address from Zoo order by address DESC, name DESC", - Object[].class - ).list(), - zoo4, zoo1, zoo2, zoo3, null + scope.inTransaction( + session -> { + checkTestOrderByResults( + session.createQuery( + "select z.name, z.address from Zoo z order by z.address DESC, z.name DESC", + Object[].class + ).list(), + zoo4, zoo1, zoo2, zoo3, null + ); + checkTestOrderByResults( + session.createQuery( + "select name, address from Zoo order by address DESC, name DESC", + Object[].class + ).list(), + zoo4, zoo1, zoo2, zoo3, null + ); + } ); - t.commit(); - s.close(); - cleanupData(); } @Test - public void testOrderBySelectAliasRef() { - createData(); - - Session s = openSession(); - Transaction t = s.beginTransaction(); - - // ordered by name, address: - // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA - // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA - // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA - // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA - checkTestOrderByResults( - s.createQuery( - "select z2.name as zname, z2.address as zooAddress from Zoo z2 where z2.name in ( select name from Zoo ) order by zname, zooAddress", - Object[].class - ).list(), - zoo2, zoo4, zoo3, zoo1, null - ); - checkTestOrderByResults( - s.createQuery( - "select z.name as name, z.address as address from Zoo z order by name, address", - Object[].class - ).list(), - zoo2, zoo4, zoo3, zoo1, null - ); - checkTestOrderByResults( - s.createQuery( - "select z.name as zooName, z.address as zooAddress from Zoo z order by zooName, zooAddress", - Object[].class - ).list(), - zoo2, zoo4, zoo3, zoo1, null - ); - checkTestOrderByResults( - s.createQuery( - "select z.name, z.address as name from Zoo z order by z.name, name", - Object[].class - ).list(), - zoo2, zoo4, zoo3, zoo1, null - ); - checkTestOrderByResults( - s.createQuery( - "select z.name, z.address as name from Zoo z order by z.name, name", - Object[].class - ).list(), - zoo2, zoo4, zoo3, zoo1, null - ); - // using ASC - checkTestOrderByResults( - s.createQuery( - "select z2.name as zname, z2.address as zooAddress from Zoo z2 where z2.name in ( select name from Zoo ) order by zname ASC, zooAddress ASC", - Object[].class - ).list(), - zoo2, zoo4, zoo3, zoo1, null - ); - checkTestOrderByResults( - s.createQuery( - "select z.name as name, z.address as address from Zoo z order by name ASC, address ASC", - Object[].class - ).list(), - zoo2, zoo4, zoo3, zoo1, null - ); - checkTestOrderByResults( - s.createQuery( - "select z.name as zooName, z.address as zooAddress from Zoo z order by zooName ASC, zooAddress ASC", - Object[].class - ).list(), - zoo2, zoo4, zoo3, zoo1, null - ); - checkTestOrderByResults( - s.createQuery( - "select z.name, z.address as name from Zoo z order by z.name ASC, name ASC", - Object[].class - ).list(), - zoo2, zoo4, zoo3, zoo1, null - ); - checkTestOrderByResults( - s.createQuery( - "select z.name, z.address as name from Zoo z order by z.name ASC, name ASC", - Object[].class - ).list(), - zoo2, zoo4, zoo3, zoo1, null - ); - - // ordered by address, name: - // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA - // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA - // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA - // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA - // - // NOTE (6.0) : another case of different handling for the component attributes - // causing a "failure" - // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA - // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA - // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA - // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA - checkTestOrderByResults( - s.createQuery( - "select z.name as address, z.address as name from Zoo z order by name, address", - Object[].class - ).list(), - zoo3, zoo2, zoo1, zoo4, null - ); - checkTestOrderByResults( - s.createQuery( - "select z.name, z.address as name from Zoo z order by name, z.name", - Object[].class - ).list(), - zoo3, zoo2, zoo1, zoo4, null - ); - // using ASC - checkTestOrderByResults( - s.createQuery( - "select z.name as address, z.address as name from Zoo z order by name ASC, address ASC", - Object[].class - ).list(), - zoo3, zoo2, zoo1, zoo4, null - ); - checkTestOrderByResults( - s.createQuery( - "select z.name, z.address as name from Zoo z order by name ASC, z.name ASC", - Object[].class - ).list(), - zoo3, zoo2, zoo1, zoo4, null - ); - - // ordered by address: - // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA - // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA - // unordered: - // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA - // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA - // - // NOTE (6.0) : another one where the result order would be undefined + public void testOrderBySelectAliasRef(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + + // ordered by name, address: + // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA + // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA + // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA + // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA + checkTestOrderByResults( + session.createQuery( + "select z2.name as zname, z2.address as zooAddress from Zoo z2 where z2.name in ( select name from Zoo ) order by zname, zooAddress", + Object[].class + ).list(), + zoo2, zoo4, zoo3, zoo1, null + ); + checkTestOrderByResults( + session.createQuery( + "select z.name as name, z.address as address from Zoo z order by name, address", + Object[].class + ).list(), + zoo2, zoo4, zoo3, zoo1, null + ); + checkTestOrderByResults( + session.createQuery( + "select z.name as zooName, z.address as zooAddress from Zoo z order by zooName, zooAddress", + Object[].class + ).list(), + zoo2, zoo4, zoo3, zoo1, null + ); + checkTestOrderByResults( + session.createQuery( + "select z.name, z.address as name from Zoo z order by z.name, name", + Object[].class + ).list(), + zoo2, zoo4, zoo3, zoo1, null + ); + checkTestOrderByResults( + session.createQuery( + "select z.name, z.address as name from Zoo z order by z.name, name", + Object[].class + ).list(), + zoo2, zoo4, zoo3, zoo1, null + ); + // using ASC + checkTestOrderByResults( + session.createQuery( + "select z2.name as zname, z2.address as zooAddress from Zoo z2 where z2.name in ( select name from Zoo ) order by zname ASC, zooAddress ASC", + Object[].class + ).list(), + zoo2, zoo4, zoo3, zoo1, null + ); + checkTestOrderByResults( + session.createQuery( + "select z.name as name, z.address as address from Zoo z order by name ASC, address ASC", + Object[].class + ).list(), + zoo2, zoo4, zoo3, zoo1, null + ); + checkTestOrderByResults( + session.createQuery( + "select z.name as zooName, z.address as zooAddress from Zoo z order by zooName ASC, zooAddress ASC", + Object[].class + ).list(), + zoo2, zoo4, zoo3, zoo1, null + ); + checkTestOrderByResults( + session.createQuery( + "select z.name, z.address as name from Zoo z order by z.name ASC, name ASC", + Object[].class + ).list(), + zoo2, zoo4, zoo3, zoo1, null + ); + checkTestOrderByResults( + session.createQuery( + "select z.name, z.address as name from Zoo z order by z.name ASC, name ASC", + Object[].class + ).list(), + zoo2, zoo4, zoo3, zoo1, null + ); + + // ordered by address, name: + // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA + // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA + // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA + // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA + // + // NOTE (6.0) : another case of different handling for the component attributes + // causing a "failure" + // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA + // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA + // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA + // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA + checkTestOrderByResults( + session.createQuery( + "select z.name as address, z.address as name from Zoo z order by name, address", + Object[].class + ).list(), + zoo3, zoo2, zoo1, zoo4, null + ); + checkTestOrderByResults( + session.createQuery( + "select z.name, z.address as name from Zoo z order by name, z.name", + Object[].class + ).list(), + zoo3, zoo2, zoo1, zoo4, null + ); + // using ASC + checkTestOrderByResults( + session.createQuery( + "select z.name as address, z.address as name from Zoo z order by name ASC, address ASC", + Object[].class + ).list(), + zoo3, zoo2, zoo1, zoo4, null + ); + checkTestOrderByResults( + session.createQuery( + "select z.name, z.address as name from Zoo z order by name ASC, z.name ASC", + Object[].class + ).list(), + zoo3, zoo2, zoo1, zoo4, null + ); + + // ordered by address: + // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA + // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA + // unordered: + // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA + // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA + // + // NOTE (6.0) : another one where the result order would be undefined // checkTestOrderByResults( // s.createQuery( // "select z.name as zooName, z.address as zooAddress from Zoo z order by zooAddress" @@ -544,7 +492,7 @@ public void testOrderBySelectAliasRef() { // zoo3, zoo4, null, null, zoosWithSameAddress // ); - // NOTE (6.0) : another undefined case + // NOTE (6.0) : another undefined case // checkTestOrderByResults( // s.createQuery( // "select z.name as zooName, z.address as name from Zoo z order by name" @@ -552,210 +500,181 @@ public void testOrderBySelectAliasRef() { // zoo3, zoo4, null, null, zoosWithSameAddress // ); - // ordered by name: - // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA - // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA - // unordered: - // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA - // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA - checkTestOrderByResults( - s.createQuery( - "select z.name as zooName, z.address as zooAddress from Zoo z order by zooName", - Object[].class - ).list(), - zoo2, zoo4, null, null, zoosWithSameName - ); - - checkTestOrderByResults( - s.createQuery( - "select z.name as address, z.address as name from Zoo z order by address", - Object[].class - ).list(), - zoo2, zoo4, null, null, zoosWithSameName + // ordered by name: + // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA + // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA + // unordered: + // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA + // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA + checkTestOrderByResults( + session.createQuery( + "select z.name as zooName, z.address as zooAddress from Zoo z order by zooName", + Object[].class + ).list(), + zoo2, zoo4, null, null, zoosWithSameName + ); + + checkTestOrderByResults( + session.createQuery( + "select z.name as address, z.address as name from Zoo z order by address", + Object[].class + ).list(), + zoo2, zoo4, null, null, zoosWithSameName + ); + } ); - t.commit(); - s.close(); - - cleanupData(); } @Test - public void testOrderByComponentDescSelectAliasRef() { - createData(); - - Session s = openSession(); - Transaction t = s.beginTransaction(); - - // ordered by address desc, name desc: - // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA - // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA - // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA - // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA - // using DESC - checkTestOrderByResults( - s.createQuery( - "select z.name as zooName, z.address as zooAddress from Zoo z order by zooAddress DESC, zooName DESC", - Object[].class - ).list(), - zoo4, zoo1, zoo2, zoo3, null + public void testOrderByComponentDescSelectAliasRef(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + // ordered by address desc, name desc: + // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA + // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA + // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA + // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA + // using DESC + checkTestOrderByResults( + session.createQuery( + "select z.name as zooName, z.address as zooAddress from Zoo z order by zooAddress DESC, zooName DESC", + Object[].class + ).list(), + zoo4, zoo1, zoo2, zoo3, null + ); + } ); - - t.commit(); - s.close(); - - cleanupData(); } @Test - public void testOrderByEntityWithFetchJoinedCollection() { - createData(); - - Session s = openSession(); - Transaction t = s.beginTransaction(); - - // ordered by address desc, name desc: - // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA - // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA - // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA - // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA - // using DESC - List list = s.createQuery( "from Zoo z join fetch z.mammals", Zoo.class ).list(); - - t.commit(); - s.close(); - - cleanupData(); + public void testOrderByEntityWithFetchJoinedCollection(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + // ordered by address desc, name desc: + // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA + // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA + // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA + // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA + // using DESC + session.createQuery( "from Zoo z join fetch z.mammals", Zoo.class ).list(); + } + ); } @Test - public void testOrderBySelectNewArgAliasRef() { - createData(); - - Session s = openSession(); - Transaction t = s.beginTransaction(); - - // ordered by name, address: - // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA - // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA - // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA - // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA - List list = - s.createQuery( - "select new Zoo( z.name as zname, z.address as zaddress) from Zoo z order by zname, zaddress", - Zoo.class - ).list(); - assertEquals( 4, list.size() ); - assertEquals( zoo2, list.get( 0 ) ); - assertEquals( zoo4, list.get( 1 ) ); - assertEquals( zoo3, list.get( 2 ) ); - assertEquals( zoo1, list.get( 3 ) ); - - // ordered by address, name: - // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA - // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA - // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA - // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA - list = - s.createQuery( - "select new Zoo( z.name as zname, z.address as zaddress) from Zoo z order by zaddress, zname", - Zoo.class - ).list(); - assertEquals( 4, list.size() ); - assertEquals( zoo3, list.get( 0 ) ); - assertEquals( zoo2, list.get( 1 ) ); - assertEquals( zoo1, list.get( 2 ) ); - assertEquals( zoo4, list.get( 3 ) ); - - - t.commit(); - s.close(); - - cleanupData(); + public void testOrderBySelectNewArgAliasRef(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + // ordered by name, address: + // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA + // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA + // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA + // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA + List list = + session.createQuery( + "select new Zoo( z.name as zname, z.address as zaddress) from Zoo z order by zname, zaddress", + Zoo.class + ).list(); + assertThat( list ).hasSize( 4 ); + assertThat( list.get( 0 ) ).isEqualTo( zoo2 ); + assertThat( list.get( 1 ) ).isEqualTo( zoo4 ); + assertThat( list.get( 2 ) ).isEqualTo( zoo3 ); + assertThat( list.get( 3 ) ).isEqualTo( zoo1 ); + + // ordered by address, name: + // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA + // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA + // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA + // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA + list = + session.createQuery( + "select new Zoo( z.name as zname, z.address as zaddress) from Zoo z order by zaddress, zname", + Zoo.class + ).list(); + assertThat( list ).hasSize( 4 ); + assertThat( list.get( 0 ) ).isEqualTo( zoo3 ); + assertThat( list.get( 1 ) ).isEqualTo( zoo2 ); + assertThat( list.get( 2 ) ).isEqualTo( zoo1 ); + assertThat( list.get( 3 ) ).isEqualTo( zoo4 ); + } + ); } - @Test(timeout = 5 * 60 * 1000) - public void testOrderBySelectNewMapArgAliasRef() { - createData(); - - Session s = openSession(); - Transaction t = s.beginTransaction(); - - // ordered by name, address: - // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA - // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA - // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA - // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA - List list = - s.createQuery( - "select new map( z.name as zname, z.address as zaddress ) from Zoo z left join z.mammals m order by zname, zaddress", - Map.class - ).list(); - assertEquals( 4, list.size() ); - assertEquals( zoo2.getName(), list.get( 0 ).get( "zname" ) ); - assertEquals( zoo2.getAddress(), list.get( 0 ).get( "zaddress" ) ); - assertEquals( zoo4.getName(), list.get( 1 ).get( "zname" ) ); - assertEquals( zoo4.getAddress(), list.get( 1 ).get( "zaddress" ) ); - assertEquals( zoo3.getName(), list.get( 2 ).get( "zname" ) ); - assertEquals( zoo3.getAddress(), list.get( 2 ).get( "zaddress" ) ); - assertEquals( zoo1.getName(), list.get( 3 ).get( "zname" ) ); - assertEquals( zoo1.getAddress(), list.get( 3 ).get( "zaddress" ) ); - - // ordered by address, name: - // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA - // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA - // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA - // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA - list = - s.createQuery( - "select new map( z.name as zname, z.address as zaddress ) from Zoo z left join z.mammals m order by zaddress, zname", - Map.class - ).list(); - assertEquals( 4, list.size() ); - - assertEquals( zoo3.getName(), list.get( 0 ).get( "zname" ) ); - assertEquals( zoo3.getAddress(), list.get( 0 ).get( "zaddress" ) ); - - assertEquals( zoo2.getName(), list.get( 1 ).get( "zname" ) ); - assertEquals( zoo2.getAddress(), list.get( 1 ).get( "zaddress" ) ); - - assertEquals( zoo1.getName(), list.get( 2 ).get( "zname" ) ); - assertEquals( zoo1.getAddress(), list.get( 2 ).get( "zaddress" ) ); - - assertEquals( zoo4.getName(), list.get( 3 ).get( "zname" ) ); - assertEquals( zoo4.getAddress(), list.get( 3 ).get( "zaddress" ) ); - t.commit(); - s.close(); - - cleanupData(); + @Test + @Timeout(value = 5, unit = TimeUnit.MINUTES) + public void testOrderBySelectNewMapArgAliasRef(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + // ordered by name, address: + // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA + // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA + // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA + // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA + List list = + session.createQuery( + "select new map( z.name as zname, z.address as zaddress ) from Zoo z left join z.mammals m order by zname, zaddress", + Map.class + ).list(); + assertThat( list ).hasSize( 4 ); + assertThat( list.get( 0 ).get( "zname" ) ).isEqualTo( zoo2.getName() ); + assertThat( list.get( 0 ).get( "zaddress" ) ).isEqualTo( zoo2.getAddress() ); + assertThat( list.get( 1 ).get( "zname" ) ).isEqualTo( zoo4.getName() ); + assertThat( list.get( 1 ).get( "zaddress" ) ).isEqualTo( zoo4.getAddress() ); + assertThat( list.get( 2 ).get( "zname" ) ).isEqualTo( zoo3.getName() ); + assertThat( list.get( 2 ).get( "zaddress" ) ).isEqualTo( zoo3.getAddress() ); + assertThat( list.get( 3 ).get( "zname" ) ).isEqualTo( zoo1.getName() ); + assertThat( list.get( 3 ).get( "zaddress" ) ).isEqualTo( zoo1.getAddress() ); + + // ordered by address, name: + // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA + // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA + // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA + // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA + list = + session.createQuery( + "select new map( z.name as zname, z.address as zaddress ) from Zoo z left join z.mammals m order by zaddress, zname", + Map.class + ).list(); + assertThat( list ).hasSize( 4 ); + + assertThat( list.get( 0 ).get( "zname" ) ).isEqualTo( zoo3.getName() ); + assertThat( list.get( 0 ).get( "zaddress" ) ).isEqualTo( zoo3.getAddress() ); + + assertThat( list.get( 1 ).get( "zname" ) ).isEqualTo( zoo2.getName() ); + assertThat( list.get( 1 ).get( "zaddress" ) ).isEqualTo( zoo2.getAddress() ); + + assertThat( list.get( 2 ).get( "zname" ) ).isEqualTo( zoo1.getName() ); + assertThat( list.get( 2 ).get( "zaddress" ) ).isEqualTo( zoo1.getAddress() ); + + assertThat( list.get( 3 ).get( "zname" ) ).isEqualTo( zoo4.getName() ); + assertThat( list.get( 3 ).get( "zaddress" ) ).isEqualTo( zoo4.getAddress() ); + } + ); } @Test - public void testOrderByAggregatedArgAliasRef() { - createData(); - - Session s = openSession(); - Transaction t = s.beginTransaction(); - - // ordered by name, address: - // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA - // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA - // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA - // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA - List list = - s.createQuery( - "select z.name as zname, count(*) as cnt from Zoo z group by z.name order by cnt desc, zname", - Object[].class - ).list(); - assertEquals( 3, list.size() ); - assertEquals( zoo3.getName(), list.get( 0 )[ 0 ] ); - assertEquals(2L, list.get( 0 )[ 1 ] ); - assertEquals( zoo2.getName(), list.get( 1 )[ 0 ] ); - assertEquals(1L, list.get( 1 )[ 1 ] ); - assertEquals( zoo4.getName(), list.get( 2 )[ 0 ] ); - assertEquals(1L, list.get( 2 )[ 1 ] ); - t.commit(); - s.close(); - cleanupData(); + public void testOrderByAggregatedArgAliasRef(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + // ordered by name, address: + // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA + // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA + // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA + // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA + List list = + session.createQuery( + "select z.name as zname, count(*) as cnt from Zoo z group by z.name order by cnt desc, zname", + Object[].class + ).list(); + assertThat( list ).hasSize( 3 ); + assertThat( list.get( 0 )[0] ).isEqualTo( zoo3.getName() ); + assertThat( list.get( 0 )[1] ).isEqualTo( 2L ); + assertThat( list.get( 1 )[0] ).isEqualTo( zoo2.getName() ); + assertThat( list.get( 1 )[1] ).isEqualTo( 1L ); + assertThat( list.get( 2 )[0] ).isEqualTo( zoo4.getName() ); + assertThat( list.get( 2 )[1] ).isEqualTo( 1L ); + } + ); } private void checkTestOrderByResults( @@ -765,33 +684,34 @@ private void checkTestOrderByResults( Zoo zoo3, Zoo zoo4, Set zoosUnordered) { - assertEquals( 4, results.size() ); - Set zoosUnorderedCopy = ( zoosUnordered == null ? null : new HashSet( zoosUnordered ) ); + assertThat( results ).hasSize( 4 ); + Set zoosUnorderedCopy = (zoosUnordered == null ? null : new HashSet<>( zoosUnordered )); checkTestOrderByResult( results.get( 0 ), zoo1, zoosUnorderedCopy ); checkTestOrderByResult( results.get( 1 ), zoo2, zoosUnorderedCopy ); checkTestOrderByResult( results.get( 2 ), zoo3, zoosUnorderedCopy ); checkTestOrderByResult( results.get( 3 ), zoo4, zoosUnorderedCopy ); if ( zoosUnorderedCopy != null ) { - assertTrue( zoosUnorderedCopy.isEmpty() ); + assertThat( zoosUnorderedCopy ).isEmpty(); } } - private void checkTestOrderByResult(Object result, - Zoo zooExpected, - Set zoosUnordered) { - assertTrue( result instanceof Object[] ); - Object[] resultArray = ( Object[] ) result; - assertEquals( 2, resultArray.length ); - Hibernate.initialize( ( ( Address ) resultArray[ 1 ] ).getStateProvince() ); + private void checkTestOrderByResult( + Object result, + Zoo zooExpected, + Set zoosUnordered) { + assertThat( result ).isInstanceOf( Object[].class ); + Object[] resultArray = (Object[]) result; + assertThat( resultArray ).hasSize( 2 ); + Hibernate.initialize( ((Address) resultArray[1]).getStateProvince() ); if ( zooExpected == null ) { Zoo zooResult = new Zoo(); - zooResult.setName( ( String ) resultArray[ 0 ] ); - zooResult.setAddress( ( Address ) resultArray[ 1 ] ); - assertTrue( zoosUnordered.remove( zooResult ) ); + zooResult.setName( (String) resultArray[0] ); + zooResult.setAddress( (Address) resultArray[1] ); + assertThat( zoosUnordered.remove( zooResult ) ).isTrue(); } else { - assertEquals( zooExpected.getAddress(), ( ( Object[] ) result )[ 1 ] ); - assertEquals( zooExpected.getName(), ( ( Object[] ) result )[ 0 ] ); + assertThat( ((Object[]) result)[1] ).isEqualTo( zooExpected.getAddress() ); + assertThat( ((Object[]) result)[0] ).isEqualTo( zooExpected.getName() ); } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/ScrollableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/ScrollableTest.java index a02a577d307b..ffd34a8c55a5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/ScrollableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/ScrollableTest.java @@ -7,117 +7,98 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; -import java.util.ArrayList; -import java.util.List; - import org.hibernate.ScrollMode; import org.hibernate.ScrollableResults; -import org.hibernate.Session; import org.hibernate.query.Query; - -import org.junit.Test; - +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.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 java.util.ArrayList; +import java.util.List; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Andrea Boriero */ -public class ScrollableTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] {MyEntity.class}; - } - - @Override - protected void prepareTest() throws Exception { - try (Session session = openSession()) { - session.getTransaction().begin(); - try { - session.persist( new MyEntity( 1L, "entity_1" ) ); - session.persist( new MyEntity( 2L, "entity_2" ) ); - session.getTransaction().commit(); - } - catch (Exception e) { - if ( session.getTransaction().isActive() ) { - session.getTransaction().rollback(); - } - throw e; - } +@DomainModel( + annotatedClasses = { + ScrollableTest.MyEntity.class } +) +@SessionFactory +public class ScrollableTest { + + @BeforeEach + public void prepareTest(SessionFactoryScope scope) { + scope.inTransaction( session -> { + session.persist( new MyEntity( 1L, "entity_1" ) ); + session.persist( new MyEntity( 2L, "entity_2" ) ); + } ); } - @Override - protected void cleanupTest() throws Exception { - try (Session session = openSession()) { - session.getTransaction().begin(); - try { - session.createMutationQuery( "delete from MyEntity" ).executeUpdate(); - session.getTransaction().commit(); - } - catch (Exception e) { - if ( session.getTransaction().isActive() ) { - session.getTransaction().rollback(); - } - throw e; - } - } + @AfterEach + public void cleanupTest(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Test @JiraKey(value = "HHH-10860") - public void testScrollableResults() { + public void testScrollableResults(SessionFactoryScope scope) { final List params = new ArrayList<>(); params.add( 1L ); params.add( 2L ); - - try (Session s = openSession()) { - final Query query = s.createQuery( "from MyEntity e where e.id in (:ids)", MyEntity.class ) - .setParameter( "ids", params ) - .setFetchSize( 10 ); - try (ScrollableResults scroll = query.scroll( ScrollMode.FORWARD_ONLY )) { - int i = 0; - while ( scroll.next() ) { - if ( i == 0 ) { - assertThat( scroll.get().getDescription(), is( "entity_1" ) ); - } - else { - assertThat( scroll.get().getDescription(), is( "entity_2" ) ); + scope.inSession( + session -> { + final Query query = session.createQuery( "from MyEntity e where e.id in (:ids)", + MyEntity.class ) + .setParameter( "ids", params ) + .setFetchSize( 10 ); + try (ScrollableResults scroll = query.scroll( ScrollMode.FORWARD_ONLY )) { + int i = 0; + while ( scroll.next() ) { + if ( i == 0 ) { + assertThat( scroll.get().getDescription() ).isEqualTo( "entity_1" ); + } + else { + assertThat( scroll.get().getDescription() ).isEqualTo( "entity_2" ); + } + i++; + } } - i++; } - } - } + ); } @Test @JiraKey(value = "HHH-10860") - public void testScrollableResults2() { + public void testScrollableResults2(SessionFactoryScope scope) { final List params = new ArrayList<>(); params.add( 1L ); params.add( 2L ); - try (Session s = openSession()) { - final Query query = s.createQuery( "from MyEntity e where e.id in (:ids)", MyEntity.class ) + scope.inSession( session -> { + final Query query = session.createQuery( "from MyEntity e where e.id in (:ids)", MyEntity.class ) .setParameter( "ids", params ) .setFetchSize( 10 ); - try (ScrollableResults scroll = query.scroll( )) { + try (ScrollableResults scroll = query.scroll()) { int i = 0; while ( scroll.next() ) { if ( i == 0 ) { - assertThat( scroll.get().getDescription(), is( "entity_1" ) ); + assertThat( scroll.get().getDescription() ).isEqualTo( "entity_1" ); } else { - assertThat( scroll.get().getDescription(), is( "entity_2" ) ); + assertThat( scroll.get().getDescription() ).isEqualTo( "entity_2" ); } i++; } } - } + } ); } @Entity(name = "MyEntity") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/SizeAttributeReferenceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/SizeAttributeReferenceTest.java index 069bc41a473b..8ebfb409fbb1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/SizeAttributeReferenceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/SizeAttributeReferenceTest.java @@ -4,19 +4,19 @@ */ package org.hibernate.orm.test.query.hql; -import java.util.Set; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; - -import org.hibernate.Session; - +import org.hibernate.testing.orm.junit.DomainModel; 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 java.util.Set; /** * Historically HQL allowed syntax like {@code `... where someCollectionPath.size > 1`} where @@ -25,41 +25,45 @@ * * @author Steve Ebersole */ -@JiraKey( value = "HHH-10024" ) -public class SizeAttributeReferenceTest extends BaseNonConfigCoreFunctionalTestCase { - @Test - public void controlGroup() { - Session session = openSession(); - session.getTransaction().begin(); - session.createQuery( "from EntityWithAttributeNamedSize e join e.children c where size(c) > 1", EntityWithAttributeNamedSize.class ).list(); - session.getTransaction().commit(); - session.close(); - } +@JiraKey(value = "HHH-10024") +@DomainModel( + annotatedClasses = { + SizeAttributeReferenceTest.EntityWithAttributeNamedSize.class + } +) +@SessionFactory +public class SizeAttributeReferenceTest { @Test - public void testSizeAttributeReference() { - Session session = openSession(); - session.getTransaction().begin(); - session.createQuery( "from EntityWithAttributeNamedSize e join e.children c where c.size = 'abc'", EntityWithAttributeNamedSize.class ).list(); - session.getTransaction().commit(); - session.close(); + public void controlGroup(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.createQuery( "from EntityWithAttributeNamedSize e join e.children c where size(c) > 1", + EntityWithAttributeNamedSize.class ).list(); + } + ); } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { EntityWithAttributeNamedSize.class }; + @Test + public void testSizeAttributeReference(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.createQuery( "from EntityWithAttributeNamedSize e join e.children c where c.size = 'abc'", + EntityWithAttributeNamedSize.class ).list(); + } + ); } - @Entity( name = "EntityWithAttributeNamedSize" ) - @Table( name = "EntityWithAttributeNamedSize" ) + @Entity(name = "EntityWithAttributeNamedSize") + @Table(name = "EntityWithAttributeNamedSize") public static class EntityWithAttributeNamedSize { @Id public Integer id; @ManyToOne public EntityWithAttributeNamedSize parent; - @OneToMany( mappedBy = "parent" ) + @OneToMany(mappedBy = "parent") public Set children; - @Column(name="`size`") + @Column(name = "`size`") private String size; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/WithClauseJoinRewriteTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/WithClauseJoinRewriteTest.java index a7aadc8c25be..14189a88d178 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/WithClauseJoinRewriteTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/WithClauseJoinRewriteTest.java @@ -4,11 +4,8 @@ */ package org.hibernate.orm.test.query.hql; -import org.hibernate.Session; -import org.hibernate.Transaction; +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.Column; import jakarta.persistence.Entity; @@ -21,6 +18,10 @@ import jakarta.persistence.MappedSuperclass; import jakarta.persistence.Table; import jakarta.persistence.Version; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; + import java.util.HashSet; import java.util.List; import java.util.Set; @@ -30,36 +31,34 @@ * * @author Steve Ebersole */ -public class WithClauseJoinRewriteTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - AbstractObject.class, - AbstractConfigurationObject.class, - ConfigurationObject.class - }; - } +@DomainModel( + annotatedClasses = { + WithClauseJoinRewriteTest.AbstractObject.class, + WithClauseJoinRewriteTest.AbstractConfigurationObject.class, + WithClauseJoinRewriteTest.ConfigurationObject.class + } +) +@SessionFactory +public class WithClauseJoinRewriteTest { @Test @JiraKey(value = "HHH-11230") - public void testInheritanceReAliasing() { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - - // Just assert that the query is successful - List results = s.createQuery( - "SELECT usedBy.id, usedBy.name, COUNT(inverse.id) " + - "FROM " + AbstractConfigurationObject.class.getName() + " config " + - "INNER JOIN config.usedBy usedBy " + - "LEFT JOIN usedBy.uses inverse ON inverse.id = config.id " + - "WHERE config.id = 0 " + - "GROUP BY usedBy.id, usedBy.name", - Object[].class - ).getResultList(); - - tx.commit(); - s.close(); + public void testInheritanceReAliasing(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + + // Just assert that the query is successful + List results = session.createQuery( + "SELECT usedBy.id, usedBy.name, COUNT(inverse.id) " + + "FROM " + AbstractConfigurationObject.class.getName() + " config " + + "INNER JOIN config.usedBy usedBy " + + "LEFT JOIN usedBy.uses inverse ON inverse.id = config.id " + + "WHERE config.id = 0 " + + "GROUP BY usedBy.id, usedBy.name", + Object[].class + ).getResultList(); + } + ); } @Entity diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/mutation/UpdateEntitiesWithPackageNamesStartingWithKeywordsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/mutation/UpdateEntitiesWithPackageNamesStartingWithKeywordsTest.java index 30f78ccf1bef..403eb1110aaf 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/mutation/UpdateEntitiesWithPackageNamesStartingWithKeywordsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/mutation/UpdateEntitiesWithPackageNamesStartingWithKeywordsTest.java @@ -6,121 +6,72 @@ import from.In; import in.from.Any; - -import org.hibernate.Session; import org.hibernate.query.Query; -import org.hibernate.resource.transaction.spi.TransactionStatus; - -import org.junit.Test; - +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.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; /** * @author Andrea Boriero */ @JiraKey(value = "HHH-10953") -public class UpdateEntitiesWithPackageNamesStartingWithKeywordsTest extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] {Any.class, In.class}; +@DomainModel( + annotatedClasses = { + Any.class, In.class + } +) +@SessionFactory +public class UpdateEntitiesWithPackageNamesStartingWithKeywordsTest { + + + @AfterEach + public void tearDown(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Test - public void testUpdateEntityWithPackageNameStartingWithIn() { + public void testUpdateEntityWithPackageNameStartingWithIn(SessionFactoryScope scope) { Any entity = new Any(); entity.setProp( "1" ); - try (Session session = openSession()) { - session.getTransaction().begin(); - try { - session.persist( entity ); - session.getTransaction().commit(); - } - catch (Exception e) { - if ( session.getTransaction().getStatus() == TransactionStatus.ACTIVE ) { - session.getTransaction().rollback(); - } - throw e; - } - } - try (Session session = openSession()) { - session.getTransaction().begin(); - try { - final Query query = session.createQuery( "UPDATE Any set prop = :prop WHERE id = :id " ); - query.setParameter( "prop", "1" ); - query.setParameter( "id", entity.getId() ); - query.executeUpdate(); - session.getTransaction().commit(); - } - catch (Exception e) { - if ( session.getTransaction().getStatus() == TransactionStatus.ACTIVE ) { - session.getTransaction().rollback(); - } - throw e; - } - } - try (Session session = openSession()) { - session.getTransaction().begin(); - try { - session.createQuery( "DELETE FROM Any" ).executeUpdate(); - session.getTransaction().commit(); - } - catch (Exception e) { - if ( session.getTransaction().getStatus() == TransactionStatus.ACTIVE ) { - session.getTransaction().rollback(); + scope.inTransaction( + session -> session.persist( entity ) + ); + + scope.inTransaction( + session -> { + final Query query = session.createQuery( "UPDATE Any set prop = :prop WHERE id = :id " ); + query.setParameter( "prop", "1" ); + query.setParameter( "id", entity.getId() ); + query.executeUpdate(); } - throw e; - } - } + ); + scope.inTransaction( + session -> session.createQuery( "DELETE FROM Any" ).executeUpdate() + ); } @Test - public void testUpdateEntityWithPackageNameStartingWithFrom() { + public void testUpdateEntityWithPackageNameStartingWithFrom(SessionFactoryScope scope) { In entity = new In(); entity.setProp( "1" ); - try (Session session = openSession()) { - - session.getTransaction().begin(); - try { - session.persist( entity ); - session.getTransaction().commit(); - } - catch (Exception e) { - if ( session.getTransaction().getStatus() == TransactionStatus.ACTIVE ) { - session.getTransaction().rollback(); - } - throw e; - } - } - try (Session session = openSession()) { - session.getTransaction().begin(); - try { - final Query query = session.createQuery( "UPDATE In set prop = :prop WHERE id = :id " ); - query.setParameter( "prop", "1" ); - query.setParameter( "id", entity.getId() ); - query.executeUpdate(); - session.getTransaction().commit(); - } - catch (Exception e) { - if ( session.getTransaction().getStatus() == TransactionStatus.ACTIVE ) { - session.getTransaction().rollback(); + scope.inTransaction( + session -> session.persist( entity ) + ); + scope.inTransaction( + session -> { + final Query query = session.createQuery( "UPDATE In set prop = :prop WHERE id = :id " ); + query.setParameter( "prop", "1" ); + query.setParameter( "id", entity.getId() ); + query.executeUpdate(); } - throw e; - } - } - try (Session session = openSession()) { - session.getTransaction().begin(); - try { - session.createQuery( "DELETE FROM In" ).executeUpdate(); - session.getTransaction().commit(); - } - catch (Exception e) { - if ( session.getTransaction().getStatus() == TransactionStatus.ACTIVE ) { - session.getTransaction().rollback(); - } - throw e; - } - } + ); + + scope.inTransaction( + session -> session.createQuery( "DELETE FROM In" ).executeUpdate() + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/sql/SynchronizedSpaceTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/sql/SynchronizedSpaceTests.java index 324c69028692..6344162339e6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/sql/SynchronizedSpaceTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/sql/SynchronizedSpaceTests.java @@ -4,21 +4,6 @@ */ package org.hibernate.orm.test.query.sql; -import java.util.HashSet; -import java.util.Set; -import java.util.function.Consumer; -import java.util.function.Function; - -import org.hibernate.annotations.Cache; -import org.hibernate.annotations.CacheConcurrencyStrategy; -import org.hibernate.annotations.NamedNativeQuery; -import org.hibernate.cache.spi.CacheImplementor; -import org.hibernate.engine.spi.SessionImplementor; -import org.hibernate.query.NativeQuery; - -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; - import jakarta.persistence.Cacheable; import jakarta.persistence.Entity; import jakarta.persistence.EntityResult; @@ -27,43 +12,90 @@ import jakarta.persistence.QueryHint; import jakarta.persistence.SqlResultSetMapping; import jakarta.persistence.Table; +import org.hibernate.annotations.Cache; +import org.hibernate.annotations.CacheConcurrencyStrategy; +import org.hibernate.annotations.NamedNativeQuery; +import org.hibernate.cache.spi.CacheImplementor; +import org.hibernate.cfg.AvailableSettings; +import org.hibernate.engine.spi.SessionImplementor; +import org.hibernate.query.NativeQuery; +import org.hibernate.testing.cache.CachingRegionFactory; +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.SettingProvider; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import java.util.HashSet; +import java.util.Set; +import java.util.function.Consumer; +import java.util.function.Function; + +import static org.assertj.core.api.Assertions.assertThat; import static org.hibernate.jpa.HibernateHints.HINT_NATIVE_SPACES; /** * @author Steve Ebersole */ -public class SynchronizedSpaceTests extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + SynchronizedSpaceTests.CachedEntity.class, + SynchronizedSpaceTests.NonCachedEntity.class + }, + overrideCacheStrategy = false +) +@SessionFactory +@ServiceRegistry( + settingProviders = @SettingProvider( + settingName = AvailableSettings.CACHE_REGION_FACTORY, + provider = SynchronizedSpaceTests.CachingRegionFactoryProvider.class + ) +) +public class SynchronizedSpaceTests { + + public static class CachingRegionFactoryProvider implements SettingProvider.Provider { + + @Override + public String getSetting() { + return CachingRegionFactory.class.getName(); + } + } + @Test - public void testNonSyncedCachedScenario() { + public void testNonSyncedCachedScenario(SessionFactoryScope scope) { // CachedEntity updated by native-query without adding query spaces // - the outcome should be all cached data being invalidated checkUseCase( + scope, "cached_entity", - query -> {}, + query -> { + }, // the 2 CachedEntity entries should not be there false ); // and of course, let's make sure the update happened :) - inTransaction( + scope.inTransaction( session -> { session.createQuery( "from CachedEntity", CachedEntity.class ).list().forEach( - cachedEntity -> assertThat( cachedEntity.name, is( "updated" ) ) + cachedEntity -> assertThat( cachedEntity.name ).isEqualTo( "updated" ) ); } ); } private void checkUseCase( + SessionFactoryScope scope, String table, Consumer updateQueryConfigurer, boolean shouldExistAfter) { checkUseCase( + scope, (session) -> { final Query nativeQuery = session.createNativeQuery( "update " + table + " set name = 'updated'" ); updateQueryConfigurer.accept( nativeQuery ); @@ -75,21 +107,22 @@ private void checkUseCase( } private void checkUseCase( - Function queryProducer, + SessionFactoryScope scope, + Function queryProducer, Consumer executor, boolean shouldExistAfter) { // first, load both `CachedEntity` instances into the L2 cache - loadAll(); + loadAll( scope ); - final CacheImplementor cacheSystem = sessionFactory().getCache(); + final CacheImplementor cacheSystem = scope.getSessionFactory().getCache(); // make sure they are there - assertThat( cacheSystem.containsEntity( CachedEntity.class, 1 ), is( true ) ); - assertThat( cacheSystem.containsEntity( CachedEntity.class, 2 ), is( true ) ); + assertThat( cacheSystem.containsEntity( CachedEntity.class, 1 ) ).isTrue(); + assertThat( cacheSystem.containsEntity( CachedEntity.class, 2 ) ).isTrue(); // create a query to update the specified table - allowing the passed consumer to register a space if needed - inTransaction( + scope.inTransaction( session -> { // notice the type is the JPA Query interface final Query nativeQuery = queryProducer.apply( session ); @@ -98,84 +131,89 @@ private void checkUseCase( ); // see if the entries exist based on the expectation - assertThat( cacheSystem.containsEntity( CachedEntity.class, 1 ), is( shouldExistAfter ) ); - assertThat( cacheSystem.containsEntity( CachedEntity.class, 2 ), is( shouldExistAfter ) ); + assertThat( cacheSystem.containsEntity( CachedEntity.class, 1 ) ).isEqualTo( shouldExistAfter ); + assertThat( cacheSystem.containsEntity( CachedEntity.class, 2 ) ).isEqualTo( shouldExistAfter ); } @Test - public void testSyncedCachedScenario() { + public void testSyncedCachedScenario(SessionFactoryScope scope) { final String tableName = "cached_entity"; checkUseCase( + scope, tableName, - query -> ( (NativeQuery) query ).addSynchronizedQuerySpace( tableName ), + query -> ((NativeQuery) query).addSynchronizedQuerySpace( tableName ), // the 2 CachedEntity entries should not be there false ); // and of course, let's make sure the update happened :) - inTransaction( + scope.inTransaction( session -> { session.createQuery( "from CachedEntity", CachedEntity.class ).list().forEach( - cachedEntity -> assertThat( cachedEntity.name, is( "updated" ) ) + cachedEntity -> assertThat( cachedEntity.name ).isEqualTo( "updated" ) ); } ); } @Test - public void testNonSyncedNonCachedScenario() { + public void testNonSyncedNonCachedScenario(SessionFactoryScope scope) { // NonCachedEntity updated by native-query without adding query spaces // - the outcome should be all cached data being invalidated checkUseCase( + scope, "non_cached_entity", - query -> {}, + query -> { + }, // the 2 CachedEntity entries should not be there false ); // and of course, let's make sure the update happened :) - inTransaction( + scope.inTransaction( session -> { session.createQuery( "from NonCachedEntity", NonCachedEntity.class ).list().forEach( - cachedEntity -> assertThat( cachedEntity.name, is( "updated" ) ) + cachedEntity -> assertThat( cachedEntity.name ).isEqualTo( "updated" ) ); } ); } @Test - public void testSyncedNonCachedScenario() { + public void testSyncedNonCachedScenario(SessionFactoryScope scope) { // NonCachedEntity updated by native-query with query spaces // - the caches for CachedEntity are not invalidated - they are not affected by the specified query-space final String tableName = "non_cached_entity"; checkUseCase( + scope, tableName, - query -> ( (NativeQuery) query ).addSynchronizedQuerySpace( tableName ), + query -> ((NativeQuery) query).addSynchronizedQuerySpace( tableName ), // the 2 CachedEntity entries should still be there true ); // and of course, let's make sure the update happened :) - inTransaction( + scope.inTransaction( session -> { session.createQuery( "from NonCachedEntity", NonCachedEntity.class ).list().forEach( - cachedEntity -> assertThat( cachedEntity.name, is( "updated" ) ) + cachedEntity -> assertThat( cachedEntity.name ).isEqualTo( "updated" ) ); } ); } @Test - public void testSyncedNonCachedScenarioUsingHint() { + public void testSyncedNonCachedScenarioUsingHint(SessionFactoryScope scope) { // same as `#testSyncedNonCachedScenario`, but here using the hint final String tableName = "non_cached_entity"; checkUseCase( + scope, tableName, query -> query.setHint( HINT_NATIVE_SPACES, tableName ), // the 2 CachedEntity entries should still be there @@ -183,17 +221,17 @@ public void testSyncedNonCachedScenarioUsingHint() { ); // and of course, let's make sure the update happened :) - inTransaction( + scope.inTransaction( session -> { session.createQuery( "from NonCachedEntity", NonCachedEntity.class ).list().forEach( - cachedEntity -> assertThat( cachedEntity.name, is( "updated" ) ) + cachedEntity -> assertThat( cachedEntity.name ).isEqualTo( "updated" ) ); } ); } @Test - public void testSyncedNonCachedScenarioUsingHintWithCollection() { + public void testSyncedNonCachedScenarioUsingHintWithCollection(SessionFactoryScope scope) { // same as `#testSyncedNonCachedScenario`, but here using the hint final String tableName = "non_cached_entity"; @@ -201,6 +239,7 @@ public void testSyncedNonCachedScenarioUsingHintWithCollection() { spaces.add( tableName ); checkUseCase( + scope, tableName, query -> query.setHint( HINT_NATIVE_SPACES, spaces ), // the 2 CachedEntity entries should still be there @@ -208,23 +247,24 @@ public void testSyncedNonCachedScenarioUsingHintWithCollection() { ); // and of course, let's make sure the update happened :) - inTransaction( + scope.inTransaction( session -> { session.createQuery( "from NonCachedEntity", NonCachedEntity.class ).list().forEach( - cachedEntity -> assertThat( cachedEntity.name, is( "updated" ) ) + cachedEntity -> assertThat( cachedEntity.name ).isEqualTo( "updated" ) ); } ); } @Test - public void testSyncedNonCachedScenarioUsingHintWithArray() { + public void testSyncedNonCachedScenarioUsingHintWithArray(SessionFactoryScope scope) { // same as `#testSyncedNonCachedScenario`, but here using the hint final String tableName = "non_cached_entity"; - final String[] spaces = { tableName }; + final String[] spaces = {tableName}; checkUseCase( + scope, tableName, query -> query.setHint( HINT_NATIVE_SPACES, spaces ), // the 2 CachedEntity entries should still be there @@ -232,18 +272,19 @@ public void testSyncedNonCachedScenarioUsingHintWithArray() { ); // and of course, let's make sure the update happened :) - inTransaction( + scope.inTransaction( session -> { session.createQuery( "from NonCachedEntity", NonCachedEntity.class ).list().forEach( - cachedEntity -> assertThat( cachedEntity.name, is( "updated" ) ) + cachedEntity -> assertThat( cachedEntity.name ).isEqualTo( "updated" ) ); } ); } @Test - public void testSyncedNonCachedScenarioUsingAnnotationWithReturnClass() { + public void testSyncedNonCachedScenarioUsingAnnotationWithReturnClass(SessionFactoryScope scope) { checkUseCase( + scope, (session) -> session.createNamedQuery( "NonCachedEntity_return_class" ), Query::getResultList, true @@ -251,8 +292,9 @@ public void testSyncedNonCachedScenarioUsingAnnotationWithReturnClass() { } @Test - public void testSyncedNonCachedScenarioUsingAnnotationWithResultSetMapping() { + public void testSyncedNonCachedScenarioUsingAnnotationWithResultSetMapping(SessionFactoryScope scope) { checkUseCase( + scope, (session) -> session.createNamedQuery( "NonCachedEntity_resultset_mapping" ), Query::getResultList, true @@ -260,8 +302,9 @@ public void testSyncedNonCachedScenarioUsingAnnotationWithResultSetMapping() { } @Test - public void testSyncedNonCachedScenarioUsingAnnotationWithSpaces() { + public void testSyncedNonCachedScenarioUsingAnnotationWithSpaces(SessionFactoryScope scope) { checkUseCase( + scope, (session) -> session.createNamedQuery( "NonCachedEntity_spaces" ), Query::getResultList, true @@ -269,8 +312,9 @@ public void testSyncedNonCachedScenarioUsingAnnotationWithSpaces() { } @Test - public void testSyncedNonCachedScenarioUsingJpaAnnotationWithNoResultMapping() { + public void testSyncedNonCachedScenarioUsingJpaAnnotationWithNoResultMapping(SessionFactoryScope scope) { checkUseCase( + scope, (session) -> session.createNamedQuery( "NonCachedEntity_raw_jpa" ), Query::getResultList, true @@ -278,16 +322,17 @@ public void testSyncedNonCachedScenarioUsingJpaAnnotationWithNoResultMapping() { } @Test - public void testSyncedNonCachedScenarioUsingJpaAnnotationWithHint() { + public void testSyncedNonCachedScenarioUsingJpaAnnotationWithHint(SessionFactoryScope scope) { checkUseCase( + scope, (session) -> session.createNamedQuery( "NonCachedEntity_hint_jpa" ), Query::getResultList, true ); } - private void loadAll() { - inTransaction( + private void loadAll(SessionFactoryScope scope) { + scope.inTransaction( session -> { session.createQuery( "from CachedEntity" ).list(); @@ -298,8 +343,9 @@ private void loadAll() { ); } - public void prepareTest() { - inTransaction( + @BeforeEach + public void prepareTest(SessionFactoryScope scope) { + scope.inTransaction( session -> { session.persist( new CachedEntity( 1, "first cached" ) ); session.persist( new CachedEntity( 2, "second cached" ) ); @@ -309,34 +355,23 @@ public void prepareTest() { } ); - cleanupCache(); - } - - public void cleanupTest() { - cleanupCache(); - - inTransaction( - session -> { - session.createQuery( "delete CachedEntity" ).executeUpdate(); - session.createQuery( "delete NonCachedEntity" ).executeUpdate(); - } - ); + cleanupCache( scope ); } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { CachedEntity.class, NonCachedEntity.class }; + @AfterEach + public void cleanupTest(SessionFactoryScope scope) { + cleanupCache( scope ); + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } - @Override - protected boolean overrideCacheStrategy() { - return false; + private void cleanupCache(SessionFactoryScope scope) { + scope.getSessionFactory().getCache().evictAllRegions(); } - @Entity( name = "CachedEntity" ) - @Table( name = "cached_entity" ) - @Cacheable( true ) - @Cache( usage = CacheConcurrencyStrategy.READ_WRITE ) + @Entity(name = "CachedEntity") + @Table(name = "cached_entity") + @Cacheable + @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public static class CachedEntity { @Id private Integer id; @@ -351,9 +386,9 @@ public CachedEntity(Integer id, String name) { } } - @Entity( name = "NonCachedEntity" ) - @Table( name = "non_cached_entity" ) - @Cacheable( false ) + @Entity(name = "NonCachedEntity") + @Table(name = "non_cached_entity") + @Cacheable(false) @NamedNativeQuery( name = "NonCachedEntity_return_class", query = "select * from non_cached_entity", @@ -366,7 +401,7 @@ public CachedEntity(Integer id, String name) { ) @SqlResultSetMapping( name = "NonCachedEntity_resultset_mapping", - entities = @EntityResult( entityClass = NonCachedEntity.class ) + entities = @EntityResult(entityClass = NonCachedEntity.class) ) @NamedNativeQuery( name = "NonCachedEntity_spaces", @@ -381,7 +416,7 @@ public CachedEntity(Integer id, String name) { name = "NonCachedEntity_hint_jpa", query = "select * from non_cached_entity", hints = { - @QueryHint( name = HINT_NATIVE_SPACES, value = "non_cached_entity" ) + @QueryHint(name = HINT_NATIVE_SPACES, value = "non_cached_entity") } ) public static class NonCachedEntity { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/ConcurrentConcreteSqmSelectQueryPlainTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/ConcurrentConcreteSqmSelectQueryPlainTest.java index e877f738de57..03118f16a2fc 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/ConcurrentConcreteSqmSelectQueryPlainTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/ConcurrentConcreteSqmSelectQueryPlainTest.java @@ -4,31 +4,35 @@ */ package org.hibernate.orm.test.query.sqm; -import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; import jakarta.persistence.Entity; import jakarta.persistence.Id; - import org.hibernate.Session; -import org.hibernate.boot.registry.BootstrapServiceRegistry; import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; import org.hibernate.dialect.MySQLDialect; import org.hibernate.engine.spi.LoadQueryInfluencers; import org.hibernate.query.Query; import org.hibernate.query.spi.QueryOptions; import org.hibernate.query.spi.QueryParameterBindings; +import org.hibernate.query.sqm.internal.ConcreteSqmSelectQueryPlan; import org.hibernate.query.sqm.internal.DomainParameterXref; import org.hibernate.query.sqm.sql.SqmTranslator; import org.hibernate.query.sqm.sql.StandardSqmTranslatorFactory; import org.hibernate.query.sqm.tree.select.SqmSelectStatement; import org.hibernate.sql.ast.spi.SqlAstCreationContext; import org.hibernate.sql.ast.tree.select.SelectStatement; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.orm.junit.RequiresDialect; -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.SettingProvider; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; @@ -41,22 +45,37 @@ * @see https://hibernate.atlassian.net/browse/HHH-17742 */ @RequiresDialect(MySQLDialect.class) -public class ConcurrentConcreteSqmSelectQueryPlainTest extends BaseCoreFunctionalTestCase { +@JiraKey("HHH-17742") +@DomainModel( + annotatedClasses = { + ConcurrentConcreteSqmSelectQueryPlainTest.SimpleEntity.class + } +) +@SessionFactory +@ServiceRegistry( + settingProviders = @SettingProvider( + settingName = AvailableSettings.SEMANTIC_QUERY_TRANSLATOR, + provider = ConcurrentConcreteSqmSelectQueryPlainTest.SemantiQueryTranslatorProvider.class + ) +) +public class ConcurrentConcreteSqmSelectQueryPlainTest { + + public static class SemantiQueryTranslatorProvider implements SettingProvider.Provider { + @Override + public String getSetting() { + return DelayingStandardSqmTranslatorFactory.class.getName(); + } + } public static final String QUERY_STRING = "select e from simple e"; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { SimpleEntity.class }; - } - /** * First query will generated a "limit ?,?" SQL statement, the following ones only need "limit ?". * Due to the race condition, the following ones reuse the cached "limit ?,?" statement, resulting in "limit null,?" being generated. */ @Test - public void run() throws InterruptedException { - inTransaction( session -> { + public void run(SessionFactoryScope scope) throws InterruptedException { + scope.inTransaction( session -> { for ( int i = 0; i < 2; i++ ) { SimpleEntity entity = new SimpleEntity(); entity.setId( i ); @@ -69,7 +88,7 @@ public void run() throws InterruptedException { for ( int i = 0; i < results.length; i++ ) { int index = i; - results[i] = CompletableFuture.supplyAsync( () -> executeQuery( index ), executorService ); + results[i] = CompletableFuture.supplyAsync( () -> executeQuery( scope, index ), executorService ); } for ( int i = 0; i < results.length; i++ ) { assertThat( results[i].join() ).hasSize( 1 ); @@ -78,10 +97,10 @@ public void run() throws InterruptedException { executorService.shutdown(); } - private List executeQuery(int index) { - try (Session session = sessionFactory().openSession()) { - return executeQuery( session, index ); - } + private List executeQuery(SessionFactoryScope scope, int index) { + return scope.fromSession( + session -> executeQuery( session, index ) + ); } private List executeQuery(Session session, int index) { @@ -90,9 +109,11 @@ private List executeQuery(Session session, int index) { if ( index == 0 ) { query.setFirstResult( 1 ); - } else { + } + else { try { - Thread.sleep( 500L ); // sleep to "ensure" all queries use the same SelectQueryPlan instance (QuerySqmImpl#resolveSelectQueryPlan) + Thread.sleep( + 500L ); // sleep to "ensure" all queries use the same SelectQueryPlan instance (QuerySqmImpl#resolveSelectQueryPlan) } catch (InterruptedException ex) { fail( "sleep interrupted: query " + index, ex ); @@ -102,13 +123,6 @@ private List executeQuery(Session session, int index) { return query.list(); } - @Override - protected Configuration constructAndConfigureConfiguration(BootstrapServiceRegistry bootstrapServiceRegistry) { - Configuration cfg = super.constructAndConfigureConfiguration( bootstrapServiceRegistry ); - cfg.setProperty( AvailableSettings.SEMANTIC_QUERY_TRANSLATOR, DelayingStandardSqmTranslatorFactory.class.getName() ); - - return cfg; - } @Entity(name = "simple") public static class SimpleEntity { @@ -129,8 +143,8 @@ public static class DelayingStandardSqmTranslatorFactory extends StandardSqmTran @Override public SqmTranslator createSelectTranslator(SqmSelectStatement sqmSelectStatement, QueryOptions queryOptions, - DomainParameterXref domainParameterXref, QueryParameterBindings domainParameterBindings, LoadQueryInfluencers loadQueryInfluencers, - SqlAstCreationContext creationContext, boolean deduplicateSelectionItems) { + DomainParameterXref domainParameterXref, QueryParameterBindings domainParameterBindings, LoadQueryInfluencers loadQueryInfluencers, + SqlAstCreationContext creationContext, boolean deduplicateSelectionItems) { try { Thread.sleep( 2000L ); // delay to trigger double-lock checking by concurrent queries @@ -139,7 +153,8 @@ public SqmTranslator createSelectTranslator(SqmSelectStatement< fail( "sleep interrupted: createSelectTranslator", ex ); } - return super.createSelectTranslator( sqmSelectStatement, queryOptions, domainParameterXref, domainParameterBindings, loadQueryInfluencers, creationContext, + return super.createSelectTranslator( sqmSelectStatement, queryOptions, domainParameterXref, + domainParameterBindings, loadQueryInfluencers, creationContext, deduplicateSelectionItems ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/ConcurrentQueriesByIdsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/ConcurrentQueriesByIdsTest.java index 72dae79b8313..ffbfd2f60663 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/ConcurrentQueriesByIdsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/ConcurrentQueriesByIdsTest.java @@ -4,34 +4,36 @@ */ package org.hibernate.orm.test.query.sqm; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; import jakarta.persistence.Basic; import jakarta.persistence.Entity; import jakarta.persistence.Id; - import org.hibernate.Session; +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.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import static org.assertj.core.api.Assertions.assertThat; -public class ConcurrentQueriesByIdsTest extends BaseCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + ConcurrentQueriesByIdsTest.SimpleEntity.class + } +) +@SessionFactory +public class ConcurrentQueriesByIdsTest { public static final String QUERY_STRING = "select e from simple e where e.id in (:ids)"; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { SimpleEntity.class }; - } - @Test - public void run() throws InterruptedException { - inTransaction( session -> { + public void run(SessionFactoryScope scope) throws InterruptedException { + scope.inTransaction( session -> { for ( int i = 0; i < 100; i++ ) { SimpleEntity entity = new SimpleEntity(); entity.setId( i ); @@ -45,7 +47,7 @@ public void run() throws InterruptedException { for ( int i = 0; i < 10; i++ ) { int index = i; - results[i] = CompletableFuture.supplyAsync( () -> executeQuery( index ), executorService ); + results[i] = CompletableFuture.supplyAsync( () -> executeQuery( scope, index ), executorService ); } for ( int i = 0; i < 10; i++ ) { assertThat( results[i].join() ).hasSize( 10 ); @@ -54,10 +56,10 @@ public void run() throws InterruptedException { executorService.shutdown(); } - private List executeQuery(int index) { - try (Session session = sessionFactory().openSession()) { - return executeQuery( session, index ); - } + private List executeQuery(SessionFactoryScope scope, int index) { + return scope.fromSession( + session -> executeQuery( session, index ) + ); } private List executeQuery(Session session, int index) { @@ -67,7 +69,7 @@ private List executeQuery(Session session, int index) { .setParameter( "ids", Arrays.asList( base + 0, base + 1, base + 2, base + 3, base + 4, base + 5, - base + 6, base + 7, base + 8, base + 9 + base + 6, base + 7, base + 8, base + 9 ) ) .list(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/SortSpecificationReversalTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/SortSpecificationReversalTests.java index af677c953317..254e371327da 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/SortSpecificationReversalTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/SortSpecificationReversalTests.java @@ -7,15 +7,13 @@ import org.hibernate.query.criteria.JpaOrder; import org.hibernate.query.sqm.tree.expression.SqmExpression; import org.hibernate.query.sqm.tree.select.SqmSortSpecification; - import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static jakarta.persistence.criteria.Nulls.FIRST; +import static org.assertj.core.api.Assertions.assertThat; import static org.hibernate.query.SortDirection.ASCENDING; import static org.hibernate.query.SortDirection.DESCENDING; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; import static org.mockito.Mockito.mock; /** @@ -30,15 +28,17 @@ public void testDefaultSqmSortSpecificationReverse() { SqmSortSpecification order = new SqmSortSpecification( sortExpression, ASCENDING, FIRST ); - assertEquals( sortExpression, order.getSortExpression() ); - assertEquals( ASCENDING, order.getSortDirection() ); - assertEquals( FIRST, order.getNullPrecedence() ); + assertThat( order.getSortExpression() ).isEqualTo( sortExpression ); + assertThat( order.getSortDirection() ).isEqualTo( ASCENDING ); + assertThat( order.getNullPrecedence() ).isEqualTo( FIRST ); JpaOrder reversed = order.reverse(); - assertEquals( DESCENDING, reversed.getSortDirection() ); - assertEquals( FIRST, reversed.getNullPrecedence() ); + assertThat( reversed.getSortDirection() ).isEqualTo( DESCENDING ); + assertThat( reversed.getNullPrecedence() ).isEqualTo( FIRST ); - assertNotSame( "Order.reverse() should create new instance", order, reversed ); + assertThat( reversed ) + .describedAs( "Order.reverse() should create new instance" ) + .isNotSameAs( order ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/quote/Phone.java b/hibernate-core/src/test/java/org/hibernate/orm/test/quote/Phone.java index ef78452c398d..0867ba87dedb 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/quote/Phone.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/quote/Phone.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.quote; + import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/quote/QuoteTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/quote/QuoteTest.java index 6768c738539b..acc2122456f1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/quote/QuoteTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/quote/QuoteTest.java @@ -4,8 +4,6 @@ */ package org.hibernate.orm.test.quote; -import java.util.HashSet; -import java.util.Set; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; @@ -17,126 +15,137 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; - -import org.hibernate.Session; - +import org.hibernate.testing.orm.junit.DomainModel; 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.AfterEach; +import org.junit.jupiter.api.Test; + +import java.util.HashSet; +import java.util.Set; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Emmanuel Bernard * @author Brett Meyer */ -public class QuoteTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + User.class, + Role.class, + Phone.class, + House.class, + QuoteTest.Container.class, + QuoteTest.SimpleItem.class + } +) +@SessionFactory +public class QuoteTest { + + @AfterEach + public void cleanup(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); + } @Test - public void testQuoteManytoMany() { + public void testQuoteManytoMany(SessionFactoryScope scope) { String role = User.class.getName() + ".roles"; - assertEquals( "User_Role", metadata().getCollectionBinding( role ).getCollectionTable().getName() ); - Session s = openSession(); - s.beginTransaction(); - User u = new User(); - s.persist( u ); - Role r = new Role(); - s.persist( r ); - u.getRoles().add( r ); - s.flush(); - s.clear(); - u = s.get( User.class, u.getId() ); - assertEquals( 1, u.getRoles().size() ); - s.getTransaction().rollback(); - s.close(); + assertThat( + scope.getMetadataImplementor().getCollectionBinding( role ).getCollectionTable().getName() ).isEqualTo( + "User_Role" ); + + scope.inTransaction( + session -> { + User u = new User(); + session.persist( u ); + Role r = new Role(); + session.persist( r ); + u.getRoles().add( r ); + session.flush(); + session.clear(); + u = session.get( User.class, u.getId() ); + assertThat( u.getRoles() ).hasSize( 1 ); + } + ); } @Test @JiraKey(value = "HHH-8464") - public void testDoubleQuoteJoinColumn() { - Session s = openSession(); - s.getTransaction().begin(); - User user = new User(); - House house = new House(); - user.setHouse( house ); - s.persist( house ); - s.persist( user ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.getTransaction().begin(); - user = s.get( User.class, user.getId() ); - assertNotNull( user ); - assertNotNull( user.getHouse() ); - // seems trivial, but if quoting normalization worked on the join column, these should all be the same - assertEquals( user.getHouse().getId(), user.getHouse1() ); - assertEquals( user.getHouse().getId(), user.getHouse2() ); - s.getTransaction().commit(); - s.close(); + public void testDoubleQuoteJoinColumn(SessionFactoryScope scope) { + User u = new User(); + scope.inTransaction( + session -> { + + House house = new House(); + u.setHouse( house ); + session.persist( house ); + session.persist( u ); + } + ); + + scope.inTransaction( + session -> { + User user = session.get( User.class, u.getId() ); + assertThat( user ).isNotNull(); + assertThat( user.getHouse() ).isNotNull(); + // seems trivial, but if quoting normalization worked on the join column, these should all be the same + assertThat( user.getHouse1() ).isEqualTo( user.getHouse().getId() ); + assertThat( user.getHouse2() ).isEqualTo( user.getHouse().getId() ); + } + ); } @Test @JiraKey(value = "HHH-2988") - public void testUnionSubclassEntityQuoting() { - Session s = openSession(); - s.beginTransaction(); + public void testUnionSubclassEntityQuoting(SessionFactoryScope scope) { Container container1 = new Container(); - Container container2 = new Container(); - SimpleItem simpleItem = new SimpleItem(); - - container1.items.add( container2 ); - container1.items.add( simpleItem ); - container2.parent = container1; - simpleItem.parent = container1; - - s.persist( simpleItem ); - s.persist( container2 ); - s.persist( container1 ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - Container result = s.get( Container.class, container1.id ); - assertNotNull( result ); - assertNotNull( result.items ); - assertEquals( 2, result.items.size() ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - container1 = s.get( Container.class, container1.id ); - for ( Item item : container1.items ) { - item.parent = null; - } - container1.items.clear(); - s.flush(); - s.createQuery( "delete Item" ).executeUpdate(); - s.getTransaction().commit(); - s.close(); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - User.class, - Role.class, - Phone.class, - House.class, - Container.class, - SimpleItem.class - }; + scope.inTransaction( + session -> { + Container container2 = new Container(); + SimpleItem simpleItem = new SimpleItem(); + + container1.items.add( container2 ); + container1.items.add( simpleItem ); + container2.parent = container1; + simpleItem.parent = container1; + + session.persist( simpleItem ); + session.persist( container2 ); + session.persist( container1 ); + } + ); + + scope.inTransaction( + session -> { + Container result = session.get( Container.class, container1.id ); + assertThat( result ).isNotNull(); + assertThat( result.items ).isNotNull(); + assertThat( result.items ).hasSize( 2 ); + } + ); + + scope.inTransaction( + session -> { + Container result = session.get( Container.class, container1.id ); + for ( Item item : result.items ) { + item.parent = null; + } + result.items.clear(); + session.flush(); + session.createMutationQuery( "delete Item" ).executeUpdate(); + } + ); } - @Entity( name = "Item" ) + @Entity(name = "Item") @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) - private static abstract class Item { + static abstract class Item { - @Id @GeneratedValue + @Id + @GeneratedValue @Column(name = "`ID`") protected long id; @@ -150,14 +159,14 @@ private static abstract class Item { @Entity @Table(name = "`CoNTaiNeR`") - private static class Container extends Item { + static class Container extends Item { @OneToMany(mappedBy = "parent", targetEntity = Item.class) - private Set items = new HashSet( 0 ); + private Set items = new HashSet<>( 0 ); } @Entity @Table(name = "`SimpleItem`") - private static class SimpleItem extends Item { + static class SimpleItem extends Item { } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/quote/Role.java b/hibernate-core/src/test/java/org/hibernate/orm/test/quote/Role.java index fda1308340ff..1cf999e0d891 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/quote/Role.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/quote/Role.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.quote; + import java.io.Serializable; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/quote/User.java b/hibernate-core/src/test/java/org/hibernate/orm/test/quote/User.java index 711c9d1b1266..bb4d2865d877 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/quote/User.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/quote/User.java @@ -32,7 +32,7 @@ public class User implements Serializable { private long id; @ManyToMany - private Set roles = new HashSet(); + private Set roles = new HashSet<>(); // These exist solely for HHH-8464 to ensure that the various forms of quoting are normalized internally // (using backticks), including the join column. Without normalization, the mapping will throw a diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/serialization/GetterSetterSerializationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/serialization/GetterSetterSerializationTest.java index c80f2c335634..6f5fc0c019a4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/serialization/GetterSetterSerializationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/serialization/GetterSetterSerializationTest.java @@ -4,13 +4,6 @@ */ package org.hibernate.orm.test.serialization; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; - -import org.junit.Test; - import org.hibernate.internal.util.ReflectHelper; import org.hibernate.orm.test.serialization.entity.AnEntity; import org.hibernate.orm.test.serialization.entity.PK; @@ -20,10 +13,15 @@ import org.hibernate.property.access.spi.Setter; import org.hibernate.property.access.spi.SetterFieldImpl; import org.hibernate.property.access.spi.SetterMethodImpl; - import org.hibernate.testing.orm.junit.JiraKey; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertSame; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +import static org.assertj.core.api.Assertions.assertThat; /** * Tests that the can access inaccessible private fields and @@ -34,7 +32,7 @@ public class GetterSetterSerializationTest { @Test - @JiraKey( value = "HHH-11202") + @JiraKey(value = "HHH-11202") public void testPrivateFieldGetter() throws Exception { final AnEntity entity = new AnEntity( new PK( 1L ) ); @@ -42,21 +40,26 @@ public void testPrivateFieldGetter() throws Exception { final Getter getter = new GetterFieldImpl( AnEntity.class, propertyName, - ReflectHelper.findField( AnEntity.class, propertyName) + ReflectHelper.findField( AnEntity.class, propertyName ) ); - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - final ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject( getter ); - final ObjectInputStream ois = new ObjectInputStream( new ByteArrayInputStream( baos.toByteArray() ) ); + try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + try (final ObjectOutputStream oos = new ObjectOutputStream( baos )) { + oos.writeObject( getter ); - final Getter getterClone = (Getter) ois.readObject(); + try (final ObjectInputStream ois = new ObjectInputStream( + new ByteArrayInputStream( baos.toByteArray() ) )) { - assertSame( getter.get( entity ), getterClone.get( entity ) ); + final Getter getterClone = (Getter) ois.readObject(); + + assertThat( getterClone.get( entity ) ).isSameAs( getter.get( entity ) ); + } + } + } } @Test - @JiraKey( value = "HHH-11202") + @JiraKey(value = "HHH-11202") public void testPrivateFieldSetter() throws Exception { AnEntity entity = new AnEntity( new PK( 1L ) ); @@ -64,29 +67,33 @@ public void testPrivateFieldSetter() throws Exception { final Getter getter = new GetterFieldImpl( AnEntity.class, propertyName, - ReflectHelper.findField( AnEntity.class, propertyName) + ReflectHelper.findField( AnEntity.class, propertyName ) ); final Setter setter = new SetterFieldImpl( AnEntity.class, propertyName, - ReflectHelper.findField( AnEntity.class, propertyName) + ReflectHelper.findField( AnEntity.class, propertyName ) ); - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - final ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject( setter ); + try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + try (final ObjectOutputStream oos = new ObjectOutputStream( baos )) { + oos.writeObject( setter ); - final ObjectInputStream ois = new ObjectInputStream( new ByteArrayInputStream( baos.toByteArray() ) ); + try (final ObjectInputStream ois = new ObjectInputStream( + new ByteArrayInputStream( baos.toByteArray() ) )) { - final Setter setterClone = (Setter) ois.readObject(); - final PK pkNew = new PK( 2L ); - setterClone.set( entity, pkNew ); + final Setter setterClone = (Setter) ois.readObject(); + final PK pkNew = new PK( 2L ); + setterClone.set( entity, pkNew ); - assertSame( pkNew, getter.get( entity ) ); + assertThat( pkNew ).isSameAs( getter.get( entity ) ); + } + } + } } @Test - @JiraKey( value = "HHH-11202") + @JiraKey(value = "HHH-11202") public void testProtectedMethodGetter() throws Exception { final AnEntity entity = new AnEntity( new PK( 1L ) ); @@ -95,19 +102,24 @@ public void testProtectedMethodGetter() throws Exception { "pk", ReflectHelper.findGetterMethod( AnEntity.class, "pk" ) ); - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - final ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject( getter ); - final ObjectInputStream ois = new ObjectInputStream( new ByteArrayInputStream( baos.toByteArray() ) ); + try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + try (final ObjectOutputStream oos = new ObjectOutputStream( baos )) { + oos.writeObject( getter ); + + try (final ObjectInputStream ois = new ObjectInputStream( + new ByteArrayInputStream( baos.toByteArray() ) )) { - final Getter getterClone = (Getter) ois.readObject(); + final Getter getterClone = (Getter) ois.readObject(); - assertSame( getter.get( entity ), getterClone.get( entity ) ); + assertThat( getterClone.get( entity ) ).isSameAs( getter.get( entity ) ); + } + } + } } @Test - @JiraKey( value = "HHH-11202") + @JiraKey(value = "HHH-11202") public void testProtectedMethodSetter() throws Exception { final AnEntity entity = new AnEntity( new PK( 1L ) ); @@ -122,16 +134,19 @@ public void testProtectedMethodSetter() throws Exception { ReflectHelper.findSetterMethod( AnEntity.class, "pk", PK.class ) ); - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - final ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject( setter ); - - final ObjectInputStream ois = new ObjectInputStream( new ByteArrayInputStream( baos.toByteArray() ) ); + try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + try (final ObjectOutputStream oos = new ObjectOutputStream( baos )) { + oos.writeObject( setter ); - final Setter setterClone = (Setter) ois.readObject(); - final PK pkNew = new PK( 2L ); - setterClone.set( entity, pkNew ); + try (final ObjectInputStream ois = new ObjectInputStream( + new ByteArrayInputStream( baos.toByteArray() ) )) { + final Setter setterClone = (Setter) ois.readObject(); + final PK pkNew = new PK( 2L ); + setterClone.set( entity, pkNew ); - assertSame( pkNew, getter.get( entity ) ); + assertThat( pkNew ).isSameAs( getter.get( entity ) ); + } + } + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/serialization/ProxySerializationNoSessionFactoryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/serialization/ProxySerializationNoSessionFactoryTest.java index 3cdcf9260ac2..c5f85383eefa 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/serialization/ProxySerializationNoSessionFactoryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/serialization/ProxySerializationNoSessionFactoryTest.java @@ -4,37 +4,34 @@ */ package org.hibernate.orm.test.serialization; -import java.io.Serializable; - +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; import org.hibernate.Hibernate; -import org.hibernate.SessionFactory; import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Configuration; +import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.internal.SessionFactoryRegistry; import org.hibernate.internal.util.SerializationHelper; import org.hibernate.proxy.HibernateProxy; - -import org.hibernate.testing.junit4.BaseUnitTestCase; +import org.hibernate.testing.orm.junit.BaseUnitTest; import org.hibernate.testing.util.ServiceRegistryUtil; import org.hibernate.tool.schema.Action; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import jakarta.persistence.Entity; -import jakarta.persistence.FetchType; -import jakarta.persistence.Id; -import jakarta.persistence.JoinColumn; -import jakarta.persistence.ManyToOne; +import java.io.Serializable; -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; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hibernate.testing.orm.transaction.TransactionUtil.fromTransaction; +import static org.hibernate.testing.orm.transaction.TransactionUtil.inTransaction; /** * @author Marco Belladelli */ -public class ProxySerializationNoSessionFactoryTest extends BaseUnitTestCase { +@BaseUnitTest +public class ProxySerializationNoSessionFactoryTest { @Test public void testUninitializedProxy() { executeTest( false ); @@ -46,51 +43,53 @@ public void testInitializedProxy() { } private void executeTest(boolean initializeProxy) { + SessionFactoryRegistry.INSTANCE.clearRegistrations(); final Configuration cfg = new Configuration() .setProperty( AvailableSettings.HBM2DDL_AUTO, Action.ACTION_CREATE_THEN_DROP ) .addAnnotatedClass( SimpleEntity.class ) .addAnnotatedClass( ChildEntity.class ); ServiceRegistryUtil.applySettings( cfg.getStandardServiceRegistryBuilder() ); final SimpleEntity parent; - try (final SessionFactory factory = cfg.buildSessionFactory()) { - doInHibernate( () -> factory, session -> { - final SimpleEntity entity = new SimpleEntity(); - entity.setId( 1L ); - entity.setName( "TheParent" ); - session.persist( entity ); - - final ChildEntity child = new ChildEntity(); - child.setId( 1L ); - child.setParent( entity ); - session.persist( child ); - } ); - - parent = doInHibernate( () -> factory, session -> { - final ChildEntity childEntity = session.find( ChildEntity.class, 1L ); - final SimpleEntity entity = childEntity.getParent(); - if ( initializeProxy ) { - assertEquals( "TheParent",entity.getName() ); - } - return entity; - } ); + try (final SessionFactoryImplementor factory = (SessionFactoryImplementor) cfg.buildSessionFactory()) { + inTransaction( factory, session -> { + final SimpleEntity entity = new SimpleEntity(); + entity.setId( 1L ); + entity.setName( "TheParent" ); + session.persist( entity ); + + final ChildEntity child = new ChildEntity(); + child.setId( 1L ); + child.setParent( entity ); + session.persist( child ); + } + ); + parent = fromTransaction( factory, session -> { + final ChildEntity childEntity = session.find( ChildEntity.class, 1L ); + final SimpleEntity entity = childEntity.getParent(); + if ( initializeProxy ) { + assertThat( entity.getName() ).isEqualTo( "TheParent" ); + } + return entity; + } + ); } // The session factory is not available anymore - assertFalse( SessionFactoryRegistry.INSTANCE.hasRegistrations() ); + assertThat( SessionFactoryRegistry.INSTANCE.hasRegistrations() ).isFalse(); - assertTrue( parent instanceof HibernateProxy ); - assertEquals( initializeProxy, Hibernate.isInitialized( parent ) ); + assertThat( parent instanceof HibernateProxy ).isTrue(); + assertThat( Hibernate.isInitialized( parent ) ).isEqualTo( initializeProxy ); // Serialization and deserialization should still work final SimpleEntity clone = (SimpleEntity) SerializationHelper.clone( parent ); - assertNotNull( clone ); - assertEquals( parent.getId(), clone.getId() ); + assertThat( clone ).isNotNull(); + assertThat( clone.getId() ).isEqualTo( parent.getId() ); if ( initializeProxy ) { - assertEquals( parent.getName(), clone.getName() ); + assertThat( clone.getName() ).isEqualTo( parent.getName() ); } } - @Entity( name = "SimpleEntity" ) + @Entity(name = "SimpleEntity") static class SimpleEntity implements Serializable { @Id private Long id; @@ -114,12 +113,12 @@ public void setName(final String name) { } } - @Entity( name = "ChildEntity" ) + @Entity(name = "ChildEntity") static class ChildEntity { @Id private Long id; - @ManyToOne( fetch = FetchType.LAZY ) + @ManyToOne(fetch = FetchType.LAZY) @JoinColumn private SimpleEntity parent; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/serialization/SessionFactorySerializationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/serialization/SessionFactorySerializationTest.java index ddcbc04c8fe9..8e6eb1c0cb10 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/serialization/SessionFactorySerializationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/serialization/SessionFactorySerializationTest.java @@ -4,33 +4,36 @@ */ package org.hibernate.orm.test.serialization; - - -import org.junit.Test; - import org.hibernate.SessionFactory; import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Configuration; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.internal.SessionFactoryRegistry; import org.hibernate.internal.util.SerializationHelper; -import org.hibernate.testing.junit4.BaseUnitTestCase; +import org.hibernate.testing.orm.junit.BaseUnitTest; import org.hibernate.testing.util.ServiceRegistryUtil; - import org.hibernate.type.SerializationException; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.fail; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; /** * @author Steve Ebersole */ -public class SessionFactorySerializationTest extends BaseUnitTestCase { +@BaseUnitTest +public class SessionFactorySerializationTest { public static final String NAME = "mySF"; + @BeforeAll + public void clearRegistry() { + SessionFactoryRegistry.INSTANCE.clearRegistrations(); + } + @Test - public void testNamedSessionFactorySerialization() throws Exception { + public void testNamedSessionFactorySerialization() { Configuration cfg = new Configuration() .setProperty( AvailableSettings.SESSION_FACTORY_NAME, NAME ) .setProperty( AvailableSettings.SESSION_FACTORY_NAME_IS_JNDI, false ); // default is true @@ -39,7 +42,7 @@ public void testNamedSessionFactorySerialization() throws Exception { // we need to do some tricking here so that Hibernate thinks the deserialization happens in a // different VM - String uuid = ( (SessionFactoryImplementor) factory ).getUuid(); + String uuid = ((SessionFactoryImplementor) factory).getUuid(); // deregister under this uuid... SessionFactoryRegistry.INSTANCE.removeSessionFactory( uuid, NAME, null, null ); // and then register under a different uuid... @@ -52,16 +55,16 @@ public void testNamedSessionFactorySerialization() throws Exception { ); SessionFactory factory2 = (SessionFactory) SerializationHelper.clone( factory ); - assertSame( factory, factory2 ); + assertThat( factory2 ).isSameAs( factory ); SessionFactoryRegistry.INSTANCE.removeSessionFactory( "some-other-uuid", NAME, null, null ); } - assertFalse( SessionFactoryRegistry.INSTANCE.hasRegistrations() ); + assertThat( SessionFactoryRegistry.INSTANCE.hasRegistrations() ).isFalse(); } @Test - public void testUnNamedSessionFactorySerialization() throws Exception { + public void testUnNamedSessionFactorySerialization() { // IMPL NOTE : this test is a control to testNamedSessionFactorySerialization // here, the test should fail based just on attempted uuid resolution Configuration cfg = new Configuration() @@ -71,7 +74,7 @@ public void testUnNamedSessionFactorySerialization() throws Exception { // we need to do some tricking here so that Hibernate thinks the deserialization happens in a // different VM - String uuid = ( (SessionFactoryImplementor) factory ).getUuid(); + String uuid = ((SessionFactoryImplementor) factory).getUuid(); // deregister under this uuid... SessionFactoryRegistry.INSTANCE.removeSessionFactory( uuid, null, null, null ); // and then register under a different uuid... @@ -93,6 +96,6 @@ public void testUnNamedSessionFactorySerialization() throws Exception { SessionFactoryRegistry.INSTANCE.removeSessionFactory( "some-other-uuid", null, null, null ); } - assertFalse( SessionFactoryRegistry.INSTANCE.hasRegistrations() ); + assertThat( SessionFactoryRegistry.INSTANCE.hasRegistrations() ).isFalse(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/serialization/TypedValueSerializationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/serialization/TypedValueSerializationTest.java index 02a74f42202d..097bae63629c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/serialization/TypedValueSerializationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/serialization/TypedValueSerializationTest.java @@ -4,18 +4,18 @@ */ package org.hibernate.orm.test.serialization; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; +import org.hibernate.engine.spi.TypedValue; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.type.Type; +import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; -import org.hibernate.engine.spi.TypedValue; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.type.Type; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; /** * @author Brett Meyer @@ -25,20 +25,24 @@ public class TypedValueSerializationTest { @Test @JiraKey(value = "HHH-9024") public void testTypedValueSerialization() throws Exception { - final Type mockType = mock(Type.class); + final Type mockType = mock( Type.class ); final String value = "foo"; - final TypedValue typedValue = new TypedValue(mockType, value); - - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - final ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(typedValue); - - final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); - final TypedValue typedValueClone = (TypedValue) ois.readObject(); - - assertEquals(typedValue.hashCode(), typedValueClone.hashCode()); - assertEquals(typedValue.toString(), typedValueClone.toString()); - assertEquals(typedValue.getValue(), typedValueClone.getValue()); + final TypedValue typedValue = new TypedValue( mockType, value ); + + try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + try (final ObjectOutputStream oos = new ObjectOutputStream( baos )) { + oos.writeObject( typedValue ); + + try (final ObjectInputStream ois = new ObjectInputStream( + new ByteArrayInputStream( baos.toByteArray() ) )) { + final TypedValue typedValueClone = (TypedValue) ois.readObject(); + + assertEquals( typedValue.hashCode(), typedValueClone.hashCode() ); + assertEquals( typedValue.toString(), typedValueClone.toString() ); + assertEquals( typedValue.getValue(), typedValueClone.getValue() ); + } + } + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/service/ClassLoaderServiceImplTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/service/ClassLoaderServiceImplTest.java index 3ffc355a62c6..242b1742c4b4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/service/ClassLoaderServiceImplTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/service/ClassLoaderServiceImplTest.java @@ -22,10 +22,10 @@ import org.hibernate.service.ServiceRegistry; import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * @author Artem V. Navrotskiy @@ -46,13 +46,14 @@ public void testSystemClassLoaderNotOverriding() throws IOException, ClassNotFou TestClassLoader anotherLoader = new TestClassLoader(); anotherLoader.overrideClass(testClass); Class anotherClass = anotherLoader.loadClass(testClass.getName()); - Assert.assertNotSame( testClass, anotherClass ); + assertThat( anotherClass ).isNotSameAs(testClass); // Check ClassLoaderServiceImpl().classForName() returns correct class (not from current ClassLoader). ClassLoaderServiceImpl loaderService = new ClassLoaderServiceImpl(anotherLoader); Class objectClass = loaderService.classForName(testClass.getName()); - Assert.assertSame("Should not return class loaded from the parent classloader of ClassLoaderServiceImpl", - objectClass, anotherClass); + assertThat( anotherClass) + .describedAs( "Should not return class loaded from the parent classloader of ClassLoaderServiceImpl" ) + .isSameAs( objectClass ); } /** @@ -78,14 +79,10 @@ public void testStoppableClassLoaderService() { StandardServiceRegistryBuilder.destroy( serviceRegistry ); - try { - getTypeContributorServices( serviceRegistry ); - Assert.fail("Should have thrown an HibernateException -- the ClassLoaderService instance was closed."); - } - catch (HibernateException e) { - Assert.assertEquals( "The ClassLoaderService cannot be reused (this instance was stopped already)", - e.getMessage() ); - } + HibernateException hibernateException = assertThrows( HibernateException.class, + () -> getTypeContributorServices( serviceRegistry ) ); + assertThat( hibernateException.getMessage() ) + .isEqualTo( "The ClassLoaderService cannot be reused (this instance was stopped already)" ); } private TypeContributor getTypeContributorServices(ServiceRegistry serviceRegistry) { @@ -106,7 +103,7 @@ protected Enumeration findResources(String name) throws IOException { if (name.equals( "META-INF/services/org.hibernate.boot.model.TypeContributor" )) { final URL serviceUrl = ConfigHelper.findAsResource( "org/hibernate/orm/test/service/org.hibernate.boot.model.TypeContributor" ); - return new Enumeration() { + return new Enumeration<>() { boolean hasMore = true; @Override @@ -122,7 +119,7 @@ public URL nextElement() { }; } else { - return java.util.Collections.enumeration( java.util.Collections.emptyList() ); + return java.util.Collections.enumeration( java.util.Collections.emptyList() ); } } @@ -134,13 +131,11 @@ public URL nextElement() { */ public void overrideClass(final Class originalClass) throws IOException { String originalPath = "/" + originalClass.getName().replaceAll("\\.", "/") + ".class"; - InputStream inputStream = originalClass.getResourceAsStream(originalPath); - Assert.assertNotNull(inputStream); - try { + try (InputStream inputStream = originalClass.getResourceAsStream( originalPath )) { + assertThat( inputStream ).isNotNull(); + byte[] data = toByteArray( inputStream ); - defineClass(originalClass.getName(), data, 0, data.length); - } finally { - inputStream.close(); + defineClass( originalClass.getName(), data, 0, data.length ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/service/ServiceBootstrappingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/service/ServiceBootstrappingTest.java index 693140742dc0..c0486c2569f0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/service/ServiceBootstrappingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/service/ServiceBootstrappingTest.java @@ -4,58 +4,58 @@ */ package org.hibernate.orm.test.service; -import java.lang.reflect.Field; -import java.util.Properties; - import org.hibernate.boot.registry.internal.StandardServiceRegistryImpl; import org.hibernate.cfg.Environment; import org.hibernate.dialect.H2Dialect; import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProvider; import org.hibernate.engine.jdbc.connections.internal.UserSuppliedConnectionProviderImpl; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; +import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess; import org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.ConnectionProviderJdbcConnectionAccess; import org.hibernate.engine.jdbc.spi.JdbcServices; - -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.junit4.BaseUnitTestCase; +import org.hibernate.testing.orm.junit.BaseUnitTest; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Assume; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Field; +import java.util.Properties; -import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Steve Ebersole */ -@RequiresDialect( H2Dialect.class ) -public class ServiceBootstrappingTest extends BaseUnitTestCase { +@RequiresDialect(H2Dialect.class) +@BaseUnitTest +public class ServiceBootstrappingTest { @Test - public void testBasicBuild() throws Exception{ - Field globalProperties = Environment.class.getDeclaredField("GLOBAL_PROPERTIES"); - globalProperties.setAccessible(true); - Properties props = (Properties) globalProperties.get(null); - Object showSql = props.remove(Environment.SHOW_SQL); + public void testBasicBuild() throws Exception { + Field globalProperties = Environment.class.getDeclaredField( "GLOBAL_PROPERTIES" ); + globalProperties.setAccessible( true ); + Properties props = (Properties) globalProperties.get( null ); + Object showSql = props.remove( Environment.SHOW_SQL ); // this test requires that SHOW_SQL property isn't passed from the outside (eg. via Gradle) - final String showSqlPropertyFromOutside = System.getProperty(Environment.SHOW_SQL); - Assume.assumeFalse("true".equals(showSqlPropertyFromOutside)); + final String showSqlPropertyFromOutside = System.getProperty( Environment.SHOW_SQL ); + assertThat( showSqlPropertyFromOutside ).isNotEqualTo( "true" ); final StandardServiceRegistryImpl serviceRegistry = ServiceRegistryUtil.serviceRegistry(); try { final JdbcServices jdbcServices = serviceRegistry.getService( JdbcServices.class ); - final ConnectionProviderJdbcConnectionAccess connectionAccess = assertTyping( - ConnectionProviderJdbcConnectionAccess.class, - jdbcServices.getBootstrapJdbcConnectionAccess() - ); - assertTrue( connectionAccess.getConnectionProvider().isUnwrappableAs( DriverManagerConnectionProvider.class ) ); - assertFalse( jdbcServices.getSqlStatementLogger().isLogToStdout() ); + final JdbcConnectionAccess connectionAccess = jdbcServices.getBootstrapJdbcConnectionAccess(); + assertThat( connectionAccess ).isInstanceOf( ConnectionProviderJdbcConnectionAccess.class ); + + ConnectionProviderJdbcConnectionAccess connectionProviderJdbcConnectionAccess = (ConnectionProviderJdbcConnectionAccess) connectionAccess; + + assertThat( connectionProviderJdbcConnectionAccess.getConnectionProvider() + .isUnwrappableAs( DriverManagerConnectionProvider.class ) ).isTrue(); + assertThat( jdbcServices.getSqlStatementLogger().isLogToStdout() ).isFalse(); } finally { if ( showSql != null ) { - props.put(Environment.SHOW_SQL, showSql); + props.put( Environment.SHOW_SQL, showSql ); } serviceRegistry.destroy(); } @@ -64,18 +64,20 @@ public void testBasicBuild() throws Exception{ @Test public void testBuildWithLogging() { StandardServiceRegistryImpl serviceRegistry = (StandardServiceRegistryImpl) ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( Environment.SHOW_SQL, "true" ) - .build(); + .applySetting( Environment.SHOW_SQL, "true" ) + .build(); try { JdbcServices jdbcServices = serviceRegistry.getService( JdbcServices.class ); + final JdbcConnectionAccess connectionAccess = jdbcServices.getBootstrapJdbcConnectionAccess(); + assertThat( connectionAccess ).isInstanceOf( ConnectionProviderJdbcConnectionAccess.class ); + + ConnectionProviderJdbcConnectionAccess connectionProviderJdbcConnectionAccess = (ConnectionProviderJdbcConnectionAccess) connectionAccess; - final ConnectionProviderJdbcConnectionAccess connectionAccess = assertTyping( - ConnectionProviderJdbcConnectionAccess.class, - jdbcServices.getBootstrapJdbcConnectionAccess() - ); - assertTrue( connectionAccess.getConnectionProvider().isUnwrappableAs( DriverManagerConnectionProvider.class ) ); - assertTrue( jdbcServices.getSqlStatementLogger().isLogToStdout() ); + assertThat( connectionProviderJdbcConnectionAccess.getConnectionProvider() + .isUnwrappableAs( DriverManagerConnectionProvider.class ) ) + .isTrue(); + assertThat( jdbcServices.getSqlStatementLogger().isLogToStdout() ).isTrue(); } finally { serviceRegistry.destroy(); @@ -88,12 +90,14 @@ public void testBuildWithServiceOverride() { try { JdbcServices jdbcServices = serviceRegistry.getService( JdbcServices.class ); + final JdbcConnectionAccess connectionAccess = jdbcServices.getBootstrapJdbcConnectionAccess(); + assertThat( connectionAccess ).isInstanceOf( ConnectionProviderJdbcConnectionAccess.class ); - ConnectionProviderJdbcConnectionAccess connectionAccess = assertTyping( - ConnectionProviderJdbcConnectionAccess.class, - jdbcServices.getBootstrapJdbcConnectionAccess() - ); - assertTrue( connectionAccess.getConnectionProvider().isUnwrappableAs( DriverManagerConnectionProvider.class ) ); + ConnectionProviderJdbcConnectionAccess connectionProviderJdbcConnectionAccess = (ConnectionProviderJdbcConnectionAccess) connectionAccess; + + assertThat( connectionProviderJdbcConnectionAccess.getConnectionProvider() + .isUnwrappableAs( DriverManagerConnectionProvider.class ) ) + .isTrue(); } finally { serviceRegistry.destroy(); @@ -105,11 +109,14 @@ public void testBuildWithServiceOverride() { .build(); JdbcServices jdbcServices = serviceRegistry.getService( JdbcServices.class ); - ConnectionProviderJdbcConnectionAccess connectionAccess = assertTyping( - ConnectionProviderJdbcConnectionAccess.class, - jdbcServices.getBootstrapJdbcConnectionAccess() - ); - assertTrue( connectionAccess.getConnectionProvider().isUnwrappableAs( UserSuppliedConnectionProviderImpl.class ) ); + final JdbcConnectionAccess connectionAccess = jdbcServices.getBootstrapJdbcConnectionAccess(); + assertThat( connectionAccess ).isInstanceOf( ConnectionProviderJdbcConnectionAccess.class ); + + ConnectionProviderJdbcConnectionAccess connectionProviderJdbcConnectionAccess = (ConnectionProviderJdbcConnectionAccess) connectionAccess; + + assertThat( connectionProviderJdbcConnectionAccess.getConnectionProvider() + .isUnwrappableAs( UserSuppliedConnectionProviderImpl.class ) ) + .isTrue(); } finally { serviceRegistry.destroy(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/service/ServiceContributorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/service/ServiceContributorTest.java index 93794e68c6e4..7117842cee66 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/service/ServiceContributorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/service/ServiceContributorTest.java @@ -4,27 +4,26 @@ */ package org.hibernate.orm.test.service; -import java.util.Map; - import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cache.internal.RegionFactoryInitiator; import org.hibernate.cache.spi.RegionFactory; import org.hibernate.cfg.AvailableSettings; import org.hibernate.service.spi.ServiceRegistryImplementor; - import org.hibernate.testing.cache.CachingRegionFactory; -import org.hibernate.testing.junit4.BaseUnitTestCase; +import org.hibernate.testing.orm.junit.BaseUnitTest; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; /** * @author Steve Ebersole */ -public class ServiceContributorTest extends BaseUnitTestCase { +@BaseUnitTest +public class ServiceContributorTest { + @Test public void overrideCachingInitiator() { var ssrb = ServiceRegistryUtil.serviceRegistryBuilder(); @@ -36,13 +35,14 @@ public void overrideCachingInitiator() { final var registry = (ServiceRegistryImplementor) ssrb.build(); try { final RegionFactory regionFactory = registry.getService( RegionFactory.class ); - assertTrue( initiator.called ); - assertTyping( MyRegionFactory.class, regionFactory ); + assertThat( initiator.called ).isTrue(); + assertThat( regionFactory ).isInstanceOf( MyRegionFactory.class ); } finally { StandardServiceRegistryBuilder.destroy( registry ); } } + @Test public void overrideCachingInitiatorExplicitSet() { var ssrb = ServiceRegistryUtil.serviceRegistryBuilder(); @@ -54,7 +54,7 @@ public void overrideCachingInitiatorExplicitSet() { final var registry = (ServiceRegistryImplementor) ssrb.build(); try { registry.getService( RegionFactory.class ); - assertFalse( initiator.called ); + assertThat( initiator.called ).isFalse(); } finally { StandardServiceRegistryBuilder.destroy( registry ); @@ -66,7 +66,7 @@ static class MyRegionFactoryInitiator extends RegionFactoryInitiator { @Override protected RegionFactory getFallback( - Map configurationValues, + Map configurationValues, ServiceRegistryImplementor registry) { called = true; return new MyRegionFactory(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/service/ServiceRegistryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/service/ServiceRegistryTest.java index e1049cb8aabd..6044809e8ec7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/service/ServiceRegistryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/service/ServiceRegistryTest.java @@ -4,14 +4,6 @@ */ package org.hibernate.orm.test.service; -import java.util.Map; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.FutureTask; - import org.hibernate.boot.registry.StandardServiceInitiator; import org.hibernate.service.NullServiceException; import org.hibernate.service.Service; @@ -20,30 +12,33 @@ import org.hibernate.service.spi.ServiceRegistryAwareService; import org.hibernate.service.spi.ServiceRegistryImplementor; import org.hibernate.service.spi.Startable; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.util.ServiceRegistryUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.hamcrest.core.IsInstanceOf.instanceOf; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.FutureTask; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; public class ServiceRegistryTest { private ServiceRegistry registry; private final static int NUMBER_OF_THREADS = 100; - @Before + @BeforeEach public void init() { registry = buildRegistry(); } - @After + @AfterEach public void destroy() { registry.close(); } @@ -61,40 +56,37 @@ public void testOnlyOneInstanceOfTheServiceShouldBeCreated() throws InterruptedE previousResult = result; } else { - assertTrue( "There are more than one instance of the service", result == previousResult ); + assertThat( previousResult ) + .describedAs( "There are more than one instance of the service" ) + .isEqualTo( result ); } - } } @Test @JiraKey(value = "HHH-11395") public void testGetService() { - assertThat( - registry.getService( SlowInitializationService.class ), - instanceOf( SlowInitializationService.class ) - ); + assertThat( registry.getService( SlowInitializationService.class ) ) + .isInstanceOf( SlowInitializationService.class ); } @Test @JiraKey(value = "HHH-11395") public void testGetServiceReturnsNullWhenTheServiceInitiatorInitiateServiceReturnsNull() { - assertNull( registry.getService( FakeService.class ) ); + assertThat( registry.getService( FakeService.class ) ).isNull(); } @Test @JiraKey(value = "HHH-11395") public void testRequireService() { - assertThat( - registry.requireService( SlowInitializationService.class ), - instanceOf( SlowInitializationService.class ) - ); + assertThat( registry.requireService( SlowInitializationService.class ) ) + .isInstanceOf( SlowInitializationService.class ); } - @Test(expected = NullServiceException.class) + @Test @JiraKey(value = "HHH-11395") public void testRequireServiceThrowsAnExceptionWhenTheServiceInitiatorInitiateServiceReturnsNull() { - assertNull( registry.requireService( FakeService.class ) ); + assertThrows( NullServiceException.class, () -> registry.requireService( FakeService.class ) ); } private ServiceRegistry buildRegistry() { @@ -103,8 +95,7 @@ private ServiceRegistry buildRegistry() { .build(); } - private FutureTask[] execute() - throws InterruptedException, ExecutionException { + private FutureTask[] execute() { FutureTask[] results = new FutureTask[NUMBER_OF_THREADS]; ExecutorService executor = Executors.newFixedThreadPool( NUMBER_OF_THREADS ); for ( int i = 0; i < NUMBER_OF_THREADS; i++ ) { @@ -114,7 +105,7 @@ private FutureTask[] execute() return results; } - public class ServiceCallable implements Callable { + public static class ServiceCallable implements Callable { private final ServiceRegistry registry; public ServiceCallable(ServiceRegistry registry) { @@ -124,14 +115,21 @@ public ServiceCallable(ServiceRegistry registry) { @Override public SlowInitializationService call() throws Exception { final SlowInitializationService service = registry.getService( SlowInitializationService.class ); - assertTrue( "The service is not initialized", service.isInitialized() ); - assertTrue( "The service is not configured", service.isConfigured() ); - assertTrue( "The service is not started", service.isStarted() ); + assertThat( service.isInitialized() ) + .describedAs( "The service is not initialized" ) + .isTrue(); + assertThat( service.isConfigured() ) + .describedAs( "The service is not configured" ) + .isTrue(); + assertThat( service.isStarted() ) + .describedAs( "The service is not started" ) + .isTrue(); return service; } } - public class SlowInitializationService implements ServiceRegistryAwareService, Configurable, Startable, Service { + public static class SlowInitializationService + implements ServiceRegistryAwareService, Configurable, Startable, Service { private final static int TIME_TO_SLEEP = 100; private boolean initialized; private boolean configured; @@ -191,7 +189,7 @@ public boolean isStarted() { } } - public class SlowServiceInitiator implements StandardServiceInitiator { + public static class SlowServiceInitiator implements StandardServiceInitiator { @Override public Class getServiceInitiated() { @@ -204,7 +202,7 @@ public SlowInitializationService initiateService(Map configurati } } - public class NullServiceInitiator implements StandardServiceInitiator { + public static class NullServiceInitiator implements StandardServiceInitiator { @Override public Class getServiceInitiated() { @@ -217,7 +215,7 @@ public FakeService initiateService(Map configurationValues, Serv } } - public class FakeService implements ServiceRegistryAwareService, Configurable, Startable, Service { + public static class FakeService implements ServiceRegistryAwareService, Configurable, Startable, Service { @Override public void start() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/service/internal/JndiServiceImplTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/service/internal/JndiServiceImplTest.java index 7e1cc09a532c..105c84c41264 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/service/internal/JndiServiceImplTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/service/internal/JndiServiceImplTest.java @@ -4,13 +4,12 @@ */ package org.hibernate.orm.test.service.internal; -import java.util.HashMap; - import org.hibernate.engine.jndi.JndiException; import org.hibernate.engine.jndi.internal.JndiServiceInitiator; import org.hibernate.engine.jndi.spi.JndiService; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import java.util.HashMap; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -21,13 +20,13 @@ */ public class JndiServiceImplTest { - private final JndiService jndiService = JndiServiceInitiator.INSTANCE.initiateService( new HashMap(), null ); + private final JndiService jndiService = JndiServiceInitiator.INSTANCE.initiateService( new HashMap<>(), null ); @Test public void rejectNonLocalProtocols() { final JndiException ldapException = assertThrows( JndiException.class, - () -> jndiService.locate( - "ldap://yourserver/something" ) + () -> jndiService.locate( + "ldap://yourserver/something" ) ); assertEquals( "JNDI lookups for scheme 'ldap' are not allowed", ldapException.getMessage() ); } @@ -37,8 +36,8 @@ public void javaLookupIsAttempted() { //The "java" scheme is allowed to be used; it will also fail as we didn't setup a full JNDI context //in this test, but we can verify it's been attempted by checking the error message. final JndiException javaLookupException = assertThrows( JndiException.class, - () -> jndiService.locate( - "java:comp/env/jdbc/MyDatasource" ) + () -> jndiService.locate( + "java:comp/env/jdbc/MyDatasource" ) ); assertEquals( "Error parsing JNDI name [java:comp/env/jdbc/MyDatasource]", javaLookupException.getMessage() ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/service/internal/ServiceRegistryClosingCascadeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/service/internal/ServiceRegistryClosingCascadeTest.java index 99baef4fdccf..571eef33e9e9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/service/internal/ServiceRegistryClosingCascadeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/service/internal/ServiceRegistryClosingCascadeTest.java @@ -10,27 +10,26 @@ import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.internal.BootstrapServiceRegistryImpl; import org.hibernate.cfg.Configuration; - -import org.hibernate.testing.junit4.BaseUnitTestCase; +import org.hibernate.testing.orm.junit.BaseUnitTest; 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.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Steve Ebersole */ -public class ServiceRegistryClosingCascadeTest extends BaseUnitTestCase { +@BaseUnitTest +public class ServiceRegistryClosingCascadeTest { @Test public void testSessionFactoryClosing() { BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder().build(); StandardServiceRegistry sr = ServiceRegistryUtil.serviceRegistryBuilder( bsr ).build(); - assertTrue( ( (BootstrapServiceRegistryImpl) bsr ).isActive() ); + assertThat( ((BootstrapServiceRegistryImpl) bsr).isActive() ).isTrue(); Configuration config = new Configuration(); try (SessionFactory sf = config.buildSessionFactory( sr )) { } - assertFalse( ( (BootstrapServiceRegistryImpl) bsr ).isActive() ); + assertThat( ((BootstrapServiceRegistryImpl) bsr).isActive() ).isFalse(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sorted/map/SortComparatorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sorted/map/SortComparatorTest.java index 25d68aa6e2f3..f8c510994812 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sorted/map/SortComparatorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sorted/map/SortComparatorTest.java @@ -4,10 +4,6 @@ */ package org.hibernate.orm.test.sorted.map; -import java.util.Iterator; -import java.util.Map; -import java.util.SortedMap; -import java.util.TreeMap; import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; @@ -16,68 +12,71 @@ import jakarta.persistence.MapKey; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; - -import org.hibernate.Session; import org.hibernate.annotations.SortComparator; import org.hibernate.orm.test.sorted.StringCaseInsensitiveComparator; +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.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import java.util.Iterator; +import java.util.Map; +import java.util.SortedMap; +import java.util.TreeMap; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; -@SuppressWarnings( "unused" ) -public class SortComparatorTest extends BaseNonConfigCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Owner.class, Cat.class }; - } +@DomainModel( + annotatedClasses = { + SortComparatorTest.Owner.class, + SortComparatorTest.Cat.class + } +) +@SessionFactory +public class SortComparatorTest { @Test - public void testSortComparator() { - Session s = openSession(); - s.beginTransaction(); - - Owner owner = new Owner(); - Cat cat1 = new Cat(); - Cat cat2 = new Cat(); - cat1.owner = owner; - cat1.name = "B"; - cat1.nickname = "B"; - cat2.owner = owner; - cat2.name = "a"; - cat2.nickname = "a"; - owner.cats.put( cat1.nickname, cat1 ); - owner.cats.put( cat2.nickname, cat2 ); - s.persist( owner ); - - s.getTransaction().commit(); - s.clear(); - - s.beginTransaction(); - - owner = s.get( Owner.class, owner.id ); - assertNotNull( owner.cats ); - assertEquals( 2, owner.cats.size() ); - - Iterator> entryIterator = owner.cats.entrySet().iterator(); - Map.Entry firstEntry = entryIterator.next(); - Map.Entry secondEntry = entryIterator.next(); - - assertEquals( "a", firstEntry.getKey() ); - assertEquals( "a", firstEntry.getValue().nickname ); - assertEquals( "B", secondEntry.getKey() ); - assertEquals( "B", secondEntry.getValue().nickname ); - - s.getTransaction().commit(); - s.close(); + public void testSortComparator(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Owner owner = new Owner(); + Cat cat1 = new Cat(); + Cat cat2 = new Cat(); + cat1.owner = owner; + cat1.name = "B"; + cat1.nickname = "B"; + cat2.owner = owner; + cat2.name = "a"; + cat2.nickname = "a"; + owner.cats.put( cat1.nickname, cat1 ); + owner.cats.put( cat2.nickname, cat2 ); + session.persist( owner ); + + session.getTransaction().commit(); + session.clear(); + + session.beginTransaction(); + + owner = session.get( Owner.class, owner.id ); + assertThat( owner.cats ).isNotNull(); + assertThat( owner.cats.size()).isEqualTo(2); + + Iterator> entryIterator = owner.cats.entrySet().iterator(); + Map.Entry firstEntry = entryIterator.next(); + Map.Entry secondEntry = entryIterator.next(); + + assertThat( firstEntry.getKey()).isEqualTo("a"); + assertThat( firstEntry.getValue().nickname).isEqualTo("a"); + assertThat( secondEntry.getKey()).isEqualTo("B"); + assertThat( secondEntry.getValue().nickname).isEqualTo("B"); + } + ); } @Entity(name = "Owner") @Table(name = "Owner") - private static class Owner { + static class Owner { @Id @GeneratedValue @@ -91,7 +90,7 @@ private static class Owner { @Entity(name = "Cat") @Table(name = "Cat") - private static class Cat implements Comparable { + static class Cat implements Comparable { @Id @GeneratedValue diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sorted/map/SortNaturalTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sorted/map/SortNaturalTest.java index 27acca792f7c..cfe88284dd17 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sorted/map/SortNaturalTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sorted/map/SortNaturalTest.java @@ -4,10 +4,6 @@ */ package org.hibernate.orm.test.sorted.map; -import java.util.Iterator; -import java.util.Map; -import java.util.SortedMap; -import java.util.TreeMap; import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; @@ -16,65 +12,68 @@ import jakarta.persistence.MapKey; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; - -import org.hibernate.Session; import org.hibernate.annotations.SortNatural; +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.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import java.util.Iterator; +import java.util.Map; +import java.util.SortedMap; +import java.util.TreeMap; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings( "unused" ) -public class SortNaturalTest extends BaseNonConfigCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Owner.class, Cat.class }; - } +@DomainModel( + annotatedClasses = { + SortNaturalTest.Owner.class, + SortNaturalTest.Cat.class + } +) +@SessionFactory +public class SortNaturalTest { @Test - public void testSortNatural() { - Session s = openSession(); - s.beginTransaction(); - - Owner owner = new Owner(); - Cat cat1 = new Cat(); - Cat cat2 = new Cat(); - cat1.owner = owner; - cat1.name = "B"; - cat2.owner = owner; - cat2.name = "A"; - owner.cats.put( cat1.name, cat1 ); - owner.cats.put( cat2.name, cat2 ); - s.persist( owner ); - - s.getTransaction().commit(); - s.clear(); - - s.beginTransaction(); - - owner = s.get( Owner.class, owner.id ); - assertNotNull(owner.cats); - assertEquals( 2, owner.cats.size() ); - - Iterator> entryIterator = owner.cats.entrySet().iterator(); - Map.Entry firstEntry = entryIterator.next(); - Map.Entry secondEntry = entryIterator.next(); - - assertEquals( "A", firstEntry.getKey() ); - assertEquals( "A", firstEntry.getValue().name ); - assertEquals( "B", secondEntry.getKey() ); - assertEquals( "B", secondEntry.getValue().name ); - - s.getTransaction().commit(); - s.close(); + public void testSortNatural(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Owner owner = new Owner(); + Cat cat1 = new Cat(); + Cat cat2 = new Cat(); + cat1.owner = owner; + cat1.name = "B"; + cat2.owner = owner; + cat2.name = "A"; + owner.cats.put( cat1.name, cat1 ); + owner.cats.put( cat2.name, cat2 ); + session.persist( owner ); + + session.getTransaction().commit(); + session.clear(); + + session.beginTransaction(); + + owner = session.get( Owner.class, owner.id ); + assertThat( owner.cats ).isNotNull(); + assertThat( owner.cats.size()).isEqualTo(2); + + Iterator> entryIterator = owner.cats.entrySet().iterator(); + Map.Entry firstEntry = entryIterator.next(); + Map.Entry secondEntry = entryIterator.next(); + + assertThat( firstEntry.getKey()).isEqualTo("A"); + assertThat( firstEntry.getValue().name).isEqualTo("A"); + assertThat( secondEntry.getKey()).isEqualTo("B"); + assertThat( secondEntry.getValue().name).isEqualTo("B"); + } + ); } @Entity(name = "Owner") @Table(name = "Owner") - private static class Owner { + static class Owner { @Id @GeneratedValue @@ -88,7 +87,7 @@ private static class Owner { @Entity(name = "Cat") @Table(name = "Cat") - private static class Cat implements Comparable { + static class Cat implements Comparable { @Id @GeneratedValue diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sorted/set/SortComparatorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sorted/set/SortComparatorTest.java index 2a39e48e46ee..ba66ca9f9d30 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sorted/set/SortComparatorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sorted/set/SortComparatorTest.java @@ -4,9 +4,6 @@ */ package org.hibernate.orm.test.sorted.set; -import java.util.Comparator; -import java.util.SortedSet; -import java.util.TreeSet; import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; @@ -14,74 +11,75 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; - -import org.hibernate.Session; import org.hibernate.annotations.SortComparator; +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.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import java.util.Comparator; +import java.util.SortedSet; +import java.util.TreeSet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; -@SuppressWarnings( "unused" ) -public class SortComparatorTest extends BaseNonConfigCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Owner.class, Cat.class }; - } +@DomainModel( + annotatedClasses = { + SortComparatorTest.Owner.class, SortComparatorTest.Cat.class + } +) +@SessionFactory +public class SortComparatorTest { @Test - public void testSortComparator() { - Session s = openSession(); - s.beginTransaction(); - - Owner owner = new Owner(); - Cat cat1 = new Cat(); - Cat cat2 = new Cat(); - cat1.owner = owner; - cat1.name = "B"; - cat1.nickname = "B"; - cat2.owner = owner; - cat2.name = "a"; - cat2.nickname = "a"; - owner.cats.add( cat1 ); - owner.cats.add( cat2 ); - s.persist( owner ); - - s.getTransaction().commit(); - s.clear(); - - s.beginTransaction(); - - owner = s.get( Owner.class, owner.id ); - - assertNotNull(owner.cats); - assertEquals( 2, owner.cats.size() ); - assertEquals( "a", owner.cats.first().nickname ); - assertEquals( "B", owner.cats.last().nickname ); - - s.getTransaction().commit(); - s.close(); + public void testSortComparator(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Owner owner = new Owner(); + Cat cat1 = new Cat(); + Cat cat2 = new Cat(); + cat1.owner = owner; + cat1.name = "B"; + cat1.nickname = "B"; + cat2.owner = owner; + cat2.name = "a"; + cat2.nickname = "a"; + owner.cats.add( cat1 ); + owner.cats.add( cat2 ); + session.persist( owner ); + + session.getTransaction().commit(); + session.clear(); + + session.beginTransaction(); + + owner = session.get( Owner.class, owner.id ); + + assertThat( owner.cats ).isNotNull(); + assertThat( owner.cats.size() ).isEqualTo( 2 ); + assertThat( owner.cats.first().nickname ).isEqualTo( "a" ); + assertThat( owner.cats.last().nickname ).isEqualTo( "B" ); + } + ); } @Entity(name = "Owner") @Table(name = "Owner") - private static class Owner { + static class Owner { @Id @GeneratedValue private long id; @OneToMany(mappedBy = "owner", cascade = CascadeType.ALL) - @SortComparator( CatNicknameComparator.class ) + @SortComparator(CatNicknameComparator.class) private SortedSet cats = new TreeSet<>(); } @Entity(name = "Cat") @Table(name = "Cat") - private static class Cat implements Comparable { + static class Cat implements Comparable { @Id @GeneratedValue diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sorted/set/SortNaturalTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sorted/set/SortNaturalTest.java index 4ac8f4119531..7b29e26c9082 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sorted/set/SortNaturalTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sorted/set/SortNaturalTest.java @@ -4,8 +4,6 @@ */ package org.hibernate.orm.test.sorted.set; -import java.util.SortedSet; -import java.util.TreeSet; import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; @@ -13,60 +11,60 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; - -import org.hibernate.Session; import org.hibernate.annotations.SortNatural; - +import org.hibernate.testing.orm.junit.DomainModel; 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.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import java.util.SortedSet; +import java.util.TreeSet; -@SuppressWarnings( "unused" ) -public class SortNaturalTest extends BaseNonConfigCoreFunctionalTestCase { +import static org.assertj.core.api.Assertions.assertThat; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Owner.class, Cat.class }; - } +@DomainModel( + annotatedClasses = { + SortNaturalTest.Owner.class, + SortNaturalTest.Cat.class + } +) +@SessionFactory +public class SortNaturalTest { @Test - @JiraKey( value = "HHH-8827" ) - public void testSortNatural() { - Session s = openSession(); - s.beginTransaction(); - - Owner owner = new Owner(); - Cat cat1 = new Cat(); - Cat cat2 = new Cat(); - cat1.owner = owner; - cat1.name = "B"; - cat2.owner = owner; - cat2.name = "A"; - owner.cats.add( cat1 ); - owner.cats.add( cat2 ); - s.persist( owner ); - - s.getTransaction().commit(); - s.clear(); - - s.beginTransaction(); - - owner = s.get( Owner.class, owner.id ); - assertNotNull( owner.cats ); - assertEquals( 2, owner.cats.size() ); - assertEquals( "A", owner.cats.first().name ); - assertEquals( "B", owner.cats.last().name ); - - s.getTransaction().commit(); - s.close(); + @JiraKey(value = "HHH-8827") + public void testSortNatural(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Owner owner = new Owner(); + Cat cat1 = new Cat(); + Cat cat2 = new Cat(); + cat1.owner = owner; + cat1.name = "B"; + cat2.owner = owner; + cat2.name = "A"; + owner.cats.add( cat1 ); + owner.cats.add( cat2 ); + session.persist( owner ); + + session.getTransaction().commit(); + session.clear(); + + session.beginTransaction(); + + owner = session.get( Owner.class, owner.id ); + assertThat( owner.cats ).isNotNull(); + assertThat( owner.cats.size() ).isEqualTo( 2 ); + assertThat( owner.cats.first().name ).isEqualTo( "A" ); + assertThat( owner.cats.last().name ).isEqualTo( "B" ); + } + ); } @Entity(name = "Owner") @Table(name = "Owner") - private static class Owner { + static class Owner { @Id @GeneratedValue @@ -79,7 +77,7 @@ private static class Owner { @Entity(name = "Cat") @Table(name = "Cat") - private static class Cat implements Comparable { + static class Cat implements Comparable { @Id @GeneratedValue diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/CollectionLoaderTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/CollectionLoaderTest.java index 39edc051007b..b75fd0db4c22 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/CollectionLoaderTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/CollectionLoaderTest.java @@ -4,38 +4,37 @@ */ package org.hibernate.orm.test.sql; -import java.sql.Statement; -import java.sql.Types; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - import jakarta.persistence.ElementCollection; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; - import org.hibernate.annotations.SQLDelete; import org.hibernate.annotations.SQLDeleteAll; import org.hibernate.annotations.SQLInsert; import org.hibernate.annotations.SQLSelect; import org.hibernate.annotations.SQLUpdate; +import org.hibernate.dialect.Dialect; import org.hibernate.dialect.H2Dialect; import org.hibernate.dialect.PostgreSQLDialect; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.metamodel.CollectionClassification; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.SettingProvider; import org.hibernate.type.descriptor.sql.spi.DdlTypeRegistry; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Before; -import org.junit.Test; +import java.sql.Statement; +import java.sql.Types; +import java.util.ArrayList; +import java.util.List; +import static org.assertj.core.api.Assertions.assertThat; import static org.hibernate.annotations.ResultCheckStyle.COUNT; import static org.hibernate.cfg.AvailableSettings.DEFAULT_LIST_SEMANTICS; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; /** * This test is for replicating the HHH-10557 issue. @@ -44,65 +43,70 @@ */ @RequiresDialect(H2Dialect.class) @RequiresDialect(PostgreSQLDialect.class) -public class CollectionLoaderTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class - }; - } - - @Override - protected void addConfigOptions(Map options) { - super.addConfigOptions( options ); - options.put( DEFAULT_LIST_SEMANTICS, CollectionClassification.BAG.name() ); +@Jpa( + annotatedClasses = { + CollectionLoaderTest.Person.class + }, + settingProviders = @SettingProvider( + settingName = DEFAULT_LIST_SEMANTICS, + provider = CollectionLoaderTest.ListSemanticsProvider.class + ) +) +public class CollectionLoaderTest { + + public static class ListSemanticsProvider implements SettingProvider.Provider { + @Override + public String getSetting() { + return CollectionClassification.BAG.name(); + } } - @Before - public void init() { - doInJPA(this::entityManagerFactory, entityManager -> { - SessionImplementor session = entityManager.unwrap( SessionImplementor.class); + @BeforeAll + public void init(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Dialect dialect = scope.getDialect(); + SessionImplementor session = entityManager.unwrap( SessionImplementor.class ); DdlTypeRegistry ddlTypeRegistry = session.getTypeConfiguration().getDdlTypeRegistry(); - session.doWork(connection -> { - try(Statement statement = connection.createStatement();) { - statement.executeUpdate(String.format( "ALTER TABLE person %s valid %s", - getDialect().getAddColumnString(), - ddlTypeRegistry.getTypeName( Types.BOOLEAN, getDialect()))); - statement.executeUpdate(String.format( "ALTER TABLE Person_phones %s valid %s", - getDialect().getAddColumnString(), - ddlTypeRegistry.getTypeName( Types.BOOLEAN, getDialect()))); + session.doWork( connection -> { + try (Statement statement = connection.createStatement()) { + statement.executeUpdate( String.format( "ALTER TABLE person %s valid %s", + dialect.getAddColumnString(), + ddlTypeRegistry.getTypeName( Types.BOOLEAN, dialect ) ) ); + statement.executeUpdate( String.format( "ALTER TABLE Person_phones %s valid %s", + dialect.getAddColumnString(), + ddlTypeRegistry.getTypeName( Types.BOOLEAN, dialect ) ) ); } - }); - }); + } ); + } ); } - @Test @JiraKey(value = "HHH-10557") - public void test_HHH10557() { + @Test + @JiraKey(value = "HHH-10557") + public void test_HHH10557(EntityManagerFactoryScope scope) { - Person _person = doInJPA(this::entityManagerFactory, entityManager -> { + Person _person = scope.fromTransaction( entityManager -> { Person person = new Person(); - person.setName("John Doe"); - entityManager.persist(person); - person.getPhones().add("123-456-7890"); - person.getPhones().add("123-456-0987"); + person.setName( "John Doe" ); + entityManager.persist( person ); + person.getPhones().add( "123-456-7890" ); + person.getPhones().add( "123-456-0987" ); return person; - }); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Long postId = _person.getId(); - Person person = entityManager.find(Person.class, postId); - assertEquals(2, person.getPhones().size()); - person.getPhones().remove(0); - person.setName("Mr. John Doe"); - }); + Person person = entityManager.find( Person.class, postId ); + assertThat( person.getPhones() ).hasSize( 2 ); + person.getPhones().remove( 0 ); + person.setName( "Mr. John Doe" ); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Long postId = _person.getId(); - Person person = entityManager.find(Person.class, postId); - assertEquals(1, person.getPhones().size()); - }); + Person person = entityManager.find( Person.class, postId ); + assertThat( person.getPhones() ).hasSize( 1 ); + } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/CustomSQLSecondaryTableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/CustomSQLSecondaryTableTest.java index f8574586dac4..00207d33e676 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/CustomSQLSecondaryTableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/CustomSQLSecondaryTableTest.java @@ -4,7 +4,6 @@ */ package org.hibernate.orm.test.sql; -import java.sql.Statement; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; @@ -12,7 +11,6 @@ import jakarta.persistence.PrimaryKeyJoinColumn; import jakarta.persistence.SecondaryTable; import jakarta.persistence.Table; - import org.hibernate.Session; import org.hibernate.annotations.ResultCheckStyle; import org.hibernate.annotations.SQLDelete; @@ -20,66 +18,65 @@ import org.hibernate.annotations.SQLSelect; import org.hibernate.dialect.H2Dialect; import org.hibernate.dialect.PostgreSQLDialect; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.sql.Statement; -import org.hibernate.testing.RequiresDialect; -import org.junit.Before; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertNull; /** * @author Vlad Mihalcea */ @RequiresDialect(H2Dialect.class) @RequiresDialect(PostgreSQLDialect.class) -public class CustomSQLSecondaryTableTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class - }; - } - - @Before - public void init() { - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); - session.doWork(connection -> { - try(Statement statement = connection.createStatement();) { - statement.executeUpdate("ALTER TABLE person ADD COLUMN valid boolean"); - statement.executeUpdate("ALTER TABLE person_details ADD COLUMN valid boolean"); +@Jpa( + annotatedClasses = { + CustomSQLSecondaryTableTest.Person.class + } +) +public class CustomSQLSecondaryTableTest { + + @BeforeAll + public void init(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); + session.doWork( connection -> { + try (Statement statement = connection.createStatement()) { + statement.executeUpdate( "ALTER TABLE person ADD COLUMN valid boolean" ); + statement.executeUpdate( "ALTER TABLE person_details ADD COLUMN valid boolean" ); } - }); - }); + } ); + } ); } @Test - public void test_sql_custom_crud() { + public void test_sql_custom_crud(EntityManagerFactoryScope scope) { - Person _person = doInJPA(this::entityManagerFactory, entityManager -> { + Person _person = scope.fromTransaction( entityManager -> { Person person = new Person(); - person.setName("John Doe"); - entityManager.persist(person); - person.setImage(new byte[] {1, 2, 3}); + person.setName( "John Doe" ); + entityManager.persist( person ); + person.setImage( new byte[] {1, 2, 3} ); return person; - }); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Long postId = _person.getId(); - Person person = entityManager.find(Person.class, postId); - assertArrayEquals(new byte[] {1, 2, 3}, person.getImage()); - entityManager.remove(person); - }); + Person person = entityManager.find( Person.class, postId ); + assertThat( person.getImage() ).isEqualTo( new byte[] {1, 2, 3} ); + entityManager.remove( person ); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Long postId = _person.getId(); - Person person = entityManager.find(Person.class, postId); - assertNull(person); - }); + Person person = entityManager.find( Person.class, postId ); + assertThat( person ).isNull(); + } ); } @@ -89,23 +86,23 @@ public void test_sql_custom_crud() { @SecondaryTable(name = "person_details", pkJoinColumns = @PrimaryKeyJoinColumn(name = "person_id")) @SQLInsert( - sql = "INSERT INTO person (name, id, valid) VALUES (?, ?, true) " -) + sql = "INSERT INTO person (name, id, valid) VALUES (?, ?, true) " + ) @SQLDelete( - sql = "UPDATE person SET valid = false WHERE id = ? " + sql = "UPDATE person SET valid = false WHERE id = ? " ) @SQLInsert( - table = "person_details", - sql = "INSERT INTO person_details (image, person_id, valid) VALUES (?, ?, true) ", - check = ResultCheckStyle.COUNT + table = "person_details", + sql = "INSERT INTO person_details (image, person_id, valid) VALUES (?, ?, true) ", + check = ResultCheckStyle.COUNT ) @SQLDelete( - table = "person_details", - sql = "UPDATE person_details SET valid = false WHERE person_id = ? " + table = "person_details", + sql = "UPDATE person_details SET valid = false WHERE person_id = ? " ) @SQLSelect( - sql = "SELECT " + + sql = "SELECT " + " p.id, " + " p.name, " + " pd.image " + @@ -126,7 +123,7 @@ public static class Person { //Getters and setters are omitted for brevity - //end::sql-custom-crud-secondary-table-example[] + //end::sql-custom-crud-secondary-table-example[] public Long getId() { return id; @@ -151,7 +148,7 @@ public byte[] getImage() { public void setImage(byte[] image) { this.image = image; } - //tag::sql-custom-crud-secondary-table-example[] + //tag::sql-custom-crud-secondary-table-example[] } //end::sql-custom-crud-secondary-table-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/CustomSQLTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/CustomSQLTest.java index 4b304885c24e..18c65bcbb198 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/CustomSQLTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/CustomSQLTest.java @@ -4,16 +4,10 @@ */ package org.hibernate.orm.test.sql; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - import jakarta.persistence.ElementCollection; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; - import org.hibernate.Session; import org.hibernate.annotations.SQLDelete; import org.hibernate.annotations.SQLDeleteAll; @@ -25,98 +19,104 @@ import org.hibernate.dialect.PostgreSQLDialect; import org.hibernate.jdbc.Expectation; import org.hibernate.metamodel.CollectionClassification; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.SettingProvider; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.RequiresDialect; -import org.junit.Before; -import org.junit.Test; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import static org.assertj.core.api.Assertions.assertThat; import static org.hibernate.cfg.AvailableSettings.DEFAULT_LIST_SEMANTICS; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; /** * @author Vlad Mihalcea */ @RequiresDialect(H2Dialect.class) @RequiresDialect(PostgreSQLDialect.class) -public class CustomSQLTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class - }; - } - - @Override - protected void addConfigOptions(Map options) { - super.addConfigOptions( options ); - options.put( DEFAULT_LIST_SEMANTICS, CollectionClassification.BAG.name() ); +@Jpa( + annotatedClasses = { + CustomSQLTest.Person.class + }, + settingProviders = @SettingProvider( + settingName = DEFAULT_LIST_SEMANTICS, + provider = CustomSQLTest.ListSemanticsProvider.class + ) +) +public class CustomSQLTest { + + public static class ListSemanticsProvider implements SettingProvider.Provider { + @Override + public String getSetting() { + return CollectionClassification.BAG.name(); + } } - @Before - public void init() { - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); - session.doWork(connection -> { - try(Statement statement = connection.createStatement();) { - statement.executeUpdate("ALTER TABLE person ADD COLUMN valid boolean"); - statement.executeUpdate("ALTER TABLE Person_phones ADD COLUMN valid boolean"); + @BeforeAll + public void init(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); + session.doWork( connection -> { + try (Statement statement = connection.createStatement()) { + statement.executeUpdate( "ALTER TABLE person ADD COLUMN valid boolean" ); + statement.executeUpdate( "ALTER TABLE Person_phones ADD COLUMN valid boolean" ); } - }); - }); + } ); + } ); } @Test - public void test_sql_custom_crud() { + public void test_sql_custom_crud(EntityManagerFactoryScope scope) { - Person _person = doInJPA(this::entityManagerFactory, entityManager -> { + Person _person = scope.fromTransaction( entityManager -> { Person person = new Person(); - person.setName("John Doe"); - entityManager.persist(person); - person.getPhones().add("123-456-7890"); - person.getPhones().add("123-456-0987"); + person.setName( "John Doe" ); + entityManager.persist( person ); + person.getPhones().add( "123-456-7890" ); + person.getPhones().add( "123-456-0987" ); return person; - }); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Long postId = _person.getId(); - Person person = entityManager.find(Person.class, postId); - assertEquals(2, person.getPhones().size()); - person.getPhones().remove(0); - person.setName("Mr. John Doe"); - }); + Person person = entityManager.find( Person.class, postId ); + assertThat( person.getPhones() ).hasSize( 2 ); + person.getPhones().remove( 0 ); + person.setName( "Mr. John Doe" ); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Long postId = _person.getId(); - Person person = entityManager.find(Person.class, postId); - assertEquals(1, person.getPhones().size()); - entityManager.remove(person); - }); + Person person = entityManager.find( Person.class, postId ); + assertThat( person.getPhones() ).hasSize( 1 ); + entityManager.remove( person ); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Long postId = _person.getId(); - Person person = entityManager.find(Person.class, postId); - assertNull(person); - }); + Person person = entityManager.find( Person.class, postId ); + assertThat( person ).isNull(); + } ); } //tag::sql-custom-crud-example[] @Entity(name = "Person") @SQLInsert( - sql = "INSERT INTO person (name, id, valid) VALUES (?, ?, true) ", - verify = Expectation.RowCount.class + sql = "INSERT INTO person (name, id, valid) VALUES (?, ?, true) ", + verify = Expectation.RowCount.class ) @SQLUpdate( - sql = "UPDATE person SET name = ? where id = ? " + sql = "UPDATE person SET name = ? where id = ? " ) @SQLDelete( - sql = "UPDATE person SET valid = false WHERE id = ? " + sql = "UPDATE person SET valid = false WHERE id = ? " ) @SQLSelect( - sql ="SELECT id, name FROM person WHERE id = ? and valid = true" + sql = "SELECT id, name FROM person WHERE id = ? and valid = true" ) public static class Person { @@ -128,15 +128,15 @@ public static class Person { @ElementCollection @SQLInsert( - sql = "INSERT INTO person_phones (person_id, phones, valid) VALUES (?, ?, true) ") + sql = "INSERT INTO person_phones (person_id, phones, valid) VALUES (?, ?, true) ") @SQLDeleteAll( - sql = "UPDATE person_phones SET valid = false WHERE person_id = ?") + sql = "UPDATE person_phones SET valid = false WHERE person_id = ?") @SQLRestriction("valid = true") private List phones = new ArrayList<>(); //Getters and setters are omitted for brevity - //end::sql-custom-crud-example[] + //end::sql-custom-crud-example[] public Long getId() { return id; @@ -157,7 +157,7 @@ public void setName(String name) { public List getPhones() { return phones; } - //tag::sql-custom-crud-example[] + //tag::sql-custom-crud-example[] } //end::sql-custom-crud-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/SQLSelectTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/SQLSelectTest.java index 33bc90131332..4125078deae3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/SQLSelectTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/SQLSelectTest.java @@ -13,27 +13,28 @@ import org.hibernate.annotations.SQLInsert; import org.hibernate.annotations.SQLSelect; import org.hibernate.annotations.SQLUpdate; +import org.hibernate.dialect.Dialect; import org.hibernate.dialect.H2Dialect; import org.hibernate.dialect.PostgreSQLDialect; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.metamodel.CollectionClassification; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.SettingProvider; import org.hibernate.type.descriptor.sql.spi.DdlTypeRegistry; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.sql.Statement; import java.sql.Types; import java.util.ArrayList; import java.util.List; -import java.util.Map; +import static org.assertj.core.api.Assertions.assertThat; import static org.hibernate.annotations.ResultCheckStyle.COUNT; import static org.hibernate.cfg.AvailableSettings.DEFAULT_LIST_SEMANTICS; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; /** * This test is for replicating the HHH-10557 issue. @@ -42,65 +43,70 @@ */ @RequiresDialect(H2Dialect.class) @RequiresDialect(PostgreSQLDialect.class) -public class SQLSelectTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class - }; - } - - @Override - protected void addConfigOptions(Map options) { - super.addConfigOptions( options ); - options.put( DEFAULT_LIST_SEMANTICS, CollectionClassification.BAG.name() ); +@Jpa( + annotatedClasses = { + SQLSelectTest.Person.class + }, + settingProviders = @SettingProvider( + settingName = DEFAULT_LIST_SEMANTICS, + provider = SQLSelectTest.ListSemanticsProvider.class + ) +) +public class SQLSelectTest { + + public static class ListSemanticsProvider implements SettingProvider.Provider { + @Override + public String getSetting() { + return CollectionClassification.BAG.name(); + } } - @Before - public void init() { - doInJPA(this::entityManagerFactory, entityManager -> { - SessionImplementor session = entityManager.unwrap( SessionImplementor.class); + @BeforeAll + public void init(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Dialect dialect = scope.getDialect(); + SessionImplementor session = entityManager.unwrap( SessionImplementor.class ); DdlTypeRegistry ddlTypeRegistry = session.getTypeConfiguration().getDdlTypeRegistry(); - session.doWork(connection -> { - try(Statement statement = connection.createStatement();) { - statement.executeUpdate(String.format( "ALTER TABLE person %s valid %s", - getDialect().getAddColumnString(), - ddlTypeRegistry.getTypeName( Types.BOOLEAN, getDialect()))); - statement.executeUpdate(String.format( "ALTER TABLE Person_phones %s valid %s", - getDialect().getAddColumnString(), - ddlTypeRegistry.getTypeName( Types.BOOLEAN, getDialect()))); + session.doWork( connection -> { + try (Statement statement = connection.createStatement()) { + statement.executeUpdate( String.format( "ALTER TABLE person %s valid %s", + dialect.getAddColumnString(), + ddlTypeRegistry.getTypeName( Types.BOOLEAN, dialect ) ) ); + statement.executeUpdate( String.format( "ALTER TABLE Person_phones %s valid %s", + dialect.getAddColumnString(), + ddlTypeRegistry.getTypeName( Types.BOOLEAN, dialect ) ) ); } - }); - }); + } ); + } ); } - @Test @JiraKey(value = "HHH-10557") - public void test_HHH10557() { + @Test + @JiraKey(value = "HHH-10557") + public void test_HHH10557(EntityManagerFactoryScope scope) { - Person _person = doInJPA(this::entityManagerFactory, entityManager -> { + Person _person = scope.fromTransaction( entityManager -> { Person person = new Person(); - person.setName("John Doe"); - entityManager.persist(person); - person.getPhones().add("123-456-7890"); - person.getPhones().add("123-456-0987"); + person.setName( "John Doe" ); + entityManager.persist( person ); + person.getPhones().add( "123-456-7890" ); + person.getPhones().add( "123-456-0987" ); return person; - }); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Long postId = _person.getId(); - Person person = entityManager.find(Person.class, postId); - assertEquals(2, person.getPhones().size()); - person.getPhones().remove(0); - person.setName("Mr. John Doe"); - }); + Person person = entityManager.find( Person.class, postId ); + assertThat( person.getPhones() ).hasSize( 2 ); + person.getPhones().remove( 0 ); + person.setName( "Mr. John Doe" ); + } ); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Long postId = _person.getId(); - Person person = entityManager.find(Person.class, postId); - assertEquals(1, person.getPhones().size()); - }); + Person person = entityManager.find( Person.class, postId ); + assertThat( person.getPhones() ).hasSize( 1 ); + } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/SQLTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/SQLTest.java index 2e7f8035f657..180d35649268 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/SQLTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/SQLTest.java @@ -4,21 +4,15 @@ */ package org.hibernate.orm.test.sql; -import java.math.BigDecimal; -import java.time.LocalDateTime; -import java.util.List; import jakarta.persistence.PersistenceException; import jakarta.persistence.Tuple; - import org.hibernate.Session; import org.hibernate.dialect.H2Dialect; import org.hibernate.dialect.OracleDialect; import org.hibernate.dialect.PostgreSQLDialect; import org.hibernate.loader.NonUniqueDiscoveredSqlAliasException; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; import org.hibernate.proxy.HibernateProxy; import org.hibernate.query.TupleTransformer; -import org.hibernate.type.StandardBasicTypes; import org.hibernate.testing.orm.domain.userguide.Account; import org.hibernate.testing.orm.domain.userguide.AddressType; import org.hibernate.testing.orm.domain.userguide.Call; @@ -30,769 +24,766 @@ import org.hibernate.testing.orm.domain.userguide.Phone; import org.hibernate.testing.orm.domain.userguide.PhoneType; import org.hibernate.testing.orm.domain.userguide.WireTransferPayment; - -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.type.StandardBasicTypes; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; import static org.assertj.core.api.Assertions.assertThat; -import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Vlad Mihalcea */ -public class SQLTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Partner.class, - Phone.class, - Call.class, - Account.class, - CreditCardPayment.class, - WireTransferPayment.class, - SpaceShip.class, - Captain.class, - }; - } - - @Before - public void init() { - doInJPA(this::entityManagerFactory, entityManager -> { - Person person1 = new Person("John Doe"); - person1.setNickName("JD"); - person1.setAddress("Earth"); - person1.setCreatedOn(LocalDateTime.of(2000, 1, 1, 0, 0, 0)) ; - person1.getAddresses().put(AddressType.HOME, "Home address"); - person1.getAddresses().put(AddressType.OFFICE, "Office address"); - entityManager.persist(person1); - - Person person2 = new Person("Mrs. John Doe"); - person2.setAddress("Earth"); - person2.setCreatedOn(LocalDateTime.of(2000, 1, 2, 12, 0, 0)) ; - entityManager.persist(person2); - - Person person3 = new Person("Dr_ John Doe"); - entityManager.persist(person3); - - Phone phone1 = new Phone("123-456-7890"); - phone1.setId(1L); - phone1.setType(PhoneType.MOBILE); - person1.addPhone(phone1); - phone1.getRepairTimestamps().add(LocalDateTime.of(2005, 1, 1, 12, 0, 0)); - phone1.getRepairTimestamps().add(LocalDateTime.of(2006, 1, 1, 12, 0, 0)); +@Jpa( + annotatedClasses = { + Person.class, + Partner.class, + Phone.class, + Call.class, + Account.class, + CreditCardPayment.class, + WireTransferPayment.class, + SpaceShip.class, + Captain.class, + } +) +public class SQLTest { + + @BeforeAll + public void init(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Person person1 = new Person( "John Doe" ); + person1.setNickName( "JD" ); + person1.setAddress( "Earth" ); + person1.setCreatedOn( LocalDateTime.of( 2000, 1, 1, 0, 0, 0 ) ); + person1.getAddresses().put( AddressType.HOME, "Home address" ); + person1.getAddresses().put( AddressType.OFFICE, "Office address" ); + entityManager.persist( person1 ); + + Person person2 = new Person( "Mrs. John Doe" ); + person2.setAddress( "Earth" ); + person2.setCreatedOn( LocalDateTime.of( 2000, 1, 2, 12, 0, 0 ) ); + entityManager.persist( person2 ); + + Person person3 = new Person( "Dr_ John Doe" ); + entityManager.persist( person3 ); + + Phone phone1 = new Phone( "123-456-7890" ); + phone1.setId( 1L ); + phone1.setType( PhoneType.MOBILE ); + person1.addPhone( phone1 ); + phone1.getRepairTimestamps().add( LocalDateTime.of( 2005, 1, 1, 12, 0, 0 ) ); + phone1.getRepairTimestamps().add( LocalDateTime.of( 2006, 1, 1, 12, 0, 0 ) ); Call call11 = new Call(); - call11.setDuration(12); - call11.setTimestamp(LocalDateTime.of(2000, 1, 1, 0, 0, 0)); + call11.setDuration( 12 ); + call11.setTimestamp( LocalDateTime.of( 2000, 1, 1, 0, 0, 0 ) ); Call call12 = new Call(); - call12.setDuration(33); - call12.setTimestamp(LocalDateTime.of(2000, 1, 1, 1, 0, 0)); + call12.setDuration( 33 ); + call12.setTimestamp( LocalDateTime.of( 2000, 1, 1, 1, 0, 0 ) ); - phone1.addCall(call11); - phone1.addCall(call12); + phone1.addCall( call11 ); + phone1.addCall( call12 ); - Phone phone2 = new Phone("098_765-4321"); - phone2.setId(2L); - phone2.setType(PhoneType.LAND_LINE); + Phone phone2 = new Phone( "098_765-4321" ); + phone2.setId( 2L ); + phone2.setType( PhoneType.LAND_LINE ); - Phone phone3 = new Phone("098-765-4320"); - phone3.setId(3L); - phone3.setType(PhoneType.LAND_LINE); + Phone phone3 = new Phone( "098-765-4320" ); + phone3.setId( 3L ); + phone3.setType( PhoneType.LAND_LINE ); - person2.addPhone(phone2); - person2.addPhone(phone3); + person2.addPhone( phone2 ); + person2.addPhone( phone3 ); CreditCardPayment creditCardPayment = new CreditCardPayment(); - creditCardPayment.setCompleted(true); - creditCardPayment.setAmount(BigDecimal.ZERO); - creditCardPayment.setPerson(person1); + creditCardPayment.setCompleted( true ); + creditCardPayment.setAmount( BigDecimal.ZERO ); + creditCardPayment.setPerson( person1 ); WireTransferPayment wireTransferPayment = new WireTransferPayment(); - wireTransferPayment.setCompleted(true); - wireTransferPayment.setAmount(BigDecimal.valueOf(100)); - wireTransferPayment.setPerson(person2); + wireTransferPayment.setCompleted( true ); + wireTransferPayment.setAmount( BigDecimal.valueOf( 100 ) ); + wireTransferPayment.setPerson( person2 ); - entityManager.persist(creditCardPayment); - entityManager.persist(wireTransferPayment); + entityManager.persist( creditCardPayment ); + entityManager.persist( wireTransferPayment ); - Partner partner = new Partner("John Doe"); - entityManager.persist(partner); + Partner partner = new Partner( "John Doe" ); + entityManager.persist( partner ); Captain captain = new Captain(); - captain.setId(new Identity()); - captain.getId().setFirstname("Jean-Luc"); - captain.getId().setLastname("Picard"); + captain.setId( new Identity() ); + captain.getId().setFirstname( "Jean-Luc" ); + captain.getId().setLastname( "Picard" ); - entityManager.persist(captain); + entityManager.persist( captain ); SpaceShip spaceShip = new SpaceShip(); - spaceShip.setName("Enterprise"); - spaceShip.setDimensions(new Dimensions()); - spaceShip.getDimensions().setLength(100); - spaceShip.getDimensions().setWidth(20); - spaceShip.setModel("E-1"); - spaceShip.setSpeed(150); - spaceShip.setCaptain(captain); - entityManager.persist(spaceShip); - }); + spaceShip.setName( "Enterprise" ); + spaceShip.setDimensions( new Dimensions() ); + spaceShip.getDimensions().setLength( 100 ); + spaceShip.getDimensions().setWidth( 20 ); + spaceShip.setModel( "E-1" ); + spaceShip.setSpeed( 150 ); + spaceShip.setCaptain( captain ); + entityManager.persist( spaceShip ); + } ); } @Test - public void test_sql_jpa_all_columns_scalar_query_example() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_sql_jpa_all_columns_scalar_query_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::sql-jpa-all-columns-scalar-query-example[] List persons = entityManager.createNativeQuery( - "SELECT * FROM Person") - .getResultList(); + "SELECT * FROM Person" ) + .getResultList(); //end::sql-jpa-all-columns-scalar-query-example[] - assertEquals(3, persons.size()); - }); + assertThat( persons ).hasSize( 3 ); + } ); } @Test - public void test_sql_jpa_custom_column_selection_scalar_query_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_sql_jpa_custom_column_selection_scalar_query_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::sql-jpa-custom-column-selection-scalar-query-example[] List persons = entityManager.createNativeQuery( - "SELECT id, name FROM Person") - .getResultList(); + "SELECT id, name FROM Person" ) + .getResultList(); - for(Object[] person : persons) { + for ( Object[] person : persons ) { Number id = (Number) person[0]; String name = (String) person[1]; } //end::sql-jpa-custom-column-selection-scalar-query-example[] - assertEquals(3, persons.size()); - }); + assertThat( persons ).hasSize( 3 ); + } ); } @Test - public void test_sql_hibernate_query_scalar_example() { - - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + public void test_sql_hibernate_query_scalar_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); //tag::sql-hibernate-all-columns-scalar-query-example[] List persons = session.createNativeQuery( - "SELECT * FROM Person", Object[].class) - .list(); + "SELECT * FROM Person", Object[].class ) + .list(); //end::sql-hibernate-all-columns-scalar-query-example[] - assertEquals(3, persons.size()); - }); + assertThat( persons ).hasSize( 3 ); + } ); } @Test - @JiraKey( value = "HHH-15914" ) - public void test_sql_hibernate_custom_column_selection_scalar_query_example() { - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + @JiraKey(value = "HHH-15914") + public void test_sql_hibernate_custom_column_selection_scalar_query_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); //tag::sql-hibernate-custom-column-selection-scalar-query-example[] List persons = session.createNativeQuery( - "SELECT id, name FROM Person", Object[].class) - .list(); + "SELECT id, name FROM Person", Object[].class ) + .list(); - for(Object[] person : persons) { + for ( Object[] person : persons ) { Number id = (Number) person[0]; String name = (String) person[1]; } //end::sql-hibernate-custom-column-selection-scalar-query-example[] - assertEquals(3, persons.size()); - }); + assertThat( persons ).hasSize( 3 ); + } ); } @Test - public void test_sql_hibernate_query_scalar_explicit_result_set_example() { - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + public void test_sql_hibernate_query_scalar_explicit_result_set_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); //tag::sql-hibernate-scalar-query-explicit-result-set-example[] List persons = session.createNativeQuery( - "SELECT * FROM Person", Object[].class) - .addScalar("id", StandardBasicTypes.LONG) - .addScalar("name", StandardBasicTypes.STRING) - .list(); + "SELECT * FROM Person", Object[].class ) + .addScalar( "id", StandardBasicTypes.LONG ) + .addScalar( "name", StandardBasicTypes.STRING ) + .list(); - for(Object[] person : persons) { + for ( Object[] person : persons ) { Long id = (Long) person[0]; String name = (String) person[1]; } //end::sql-hibernate-scalar-query-explicit-result-set-example[] - assertEquals(3, persons.size()); - }); + assertThat( persons ).hasSize( 3 ); + } ); } @Test - public void test_sql_hibernate_query_scalar_partial_explicit_result_set_example() { - - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + public void test_sql_hibernate_query_scalar_partial_explicit_result_set_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); //tag::sql-hibernate-scalar-query-partial-explicit-result-set-example[] List persons = session.createNativeQuery( - "SELECT * FROM Person", Object[].class) - .addScalar("id", StandardBasicTypes.LONG) - .addScalar("name") - .list(); + "SELECT * FROM Person", Object[].class ) + .addScalar( "id", StandardBasicTypes.LONG ) + .addScalar( "name" ) + .list(); - for(Object[] person : persons) { + for ( Object[] person : persons ) { Long id = (Long) person[0]; String name = (String) person[1]; } //end::sql-hibernate-scalar-query-partial-explicit-result-set-example[] - assertEquals(3, persons.size()); - }); + assertThat( persons ).hasSize( 3 ); + } ); } @Test - public void test_sql_jpa_entity_query_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_sql_jpa_entity_query_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::sql-jpa-entity-query-example[] List persons = entityManager.createNativeQuery( - "SELECT * FROM Person", Person.class) - .getResultList(); + "SELECT * FROM Person", Person.class ) + .getResultList(); //end::sql-jpa-entity-query-example[] - assertEquals(3, persons.size()); - }); + assertThat( persons ).hasSize( 3 ); + } ); } @Test - public void test_sql_hibernate_entity_query_example() { - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + public void test_sql_hibernate_entity_query_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); //tag::sql-hibernate-entity-query-example[] List persons = session.createNativeQuery( - "SELECT * FROM Person", Person.class) - .list(); + "SELECT * FROM Person", Person.class ) + .list(); //end::sql-hibernate-entity-query-example[] - assertEquals(3, persons.size()); - }); + assertThat( persons ).hasSize( 3 ); + } ); } @Test - public void test_sql_jpa_entity_query_explicit_result_set_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_sql_jpa_entity_query_explicit_result_set_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::sql-jpa-entity-query-explicit-result-set-example[] List persons = entityManager.createNativeQuery( - "SELECT id, name, nick_name, address, created_on, version " + - "FROM Person", Person.class) - .getResultList(); + "SELECT id, name, nick_name, address, created_on, version " + + "FROM Person", Person.class ) + .getResultList(); //end::sql-jpa-entity-query-explicit-result-set-example[] - assertEquals(3, persons.size()); - }); + assertThat( persons ).hasSize( 3 ); + } ); } @Test - public void test_sql_hibernate_entity_query_explicit_result_set_example() { - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + public void test_sql_hibernate_entity_query_explicit_result_set_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); //tag::sql-hibernate-entity-query-explicit-result-set-example[] List persons = session.createNativeQuery( - "SELECT id, name, nick_name, address, created_on, version " + - "FROM Person", Person.class) - .list(); + "SELECT id, name, nick_name, address, created_on, version " + + "FROM Person", Person.class ) + .list(); //end::sql-hibernate-entity-query-explicit-result-set-example[] - assertEquals(3, persons.size()); - }); + assertThat( persons ).hasSize( 3 ); + } ); } @Test - public void test_sql_jpa_entity_associations_query_many_to_one_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_sql_jpa_entity_associations_query_many_to_one_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::sql-jpa-entity-associations-query-many-to-one-example[] List phones = entityManager.createNativeQuery( - "SELECT id, phone_number, phone_type, person_id " + - "FROM Phone", Phone.class) - .getResultList(); + "SELECT id, phone_number, phone_type, person_id " + + "FROM Phone", Phone.class ) + .getResultList(); //end::sql-jpa-entity-associations-query-many-to-one-example[] - assertEquals(3, phones.size()); - }); + assertThat( phones ).hasSize( 3 ); + } ); } @Test - public void test_sql_hibernate_entity_associations_query_many_to_one_example() { - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + public void test_sql_hibernate_entity_associations_query_many_to_one_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); //tag::sql-hibernate-entity-associations-query-many-to-one-example[] List phones = session.createNativeQuery( - "SELECT id, phone_number, phone_type, person_id " + - "FROM Phone", Phone.class) - .list(); + "SELECT id, phone_number, phone_type, person_id " + + "FROM Phone", Phone.class ) + .list(); //end::sql-hibernate-entity-associations-query-many-to-one-example[] - assertEquals(3, phones.size()); - }); + assertThat( phones ).hasSize( 3 ); + } ); } @Test - public void test_sql_jpa_entity_associations_query_many_to_one_join_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_sql_jpa_entity_associations_query_many_to_one_join_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { List phones = entityManager.createNativeQuery( - "SELECT ph.* " + - "FROM Phone ph " + - "JOIN Person pr ON ph.person_id = pr.id", Phone.class) - .getResultList(); + "SELECT ph.* " + + "FROM Phone ph " + + "JOIN Person pr ON ph.person_id = pr.id", Phone.class ) + .getResultList(); - for(Phone phone : phones) { - assertNotNull(phone.getPerson().getName()); + for ( Phone phone : phones ) { + assertThat( phone.getPerson().getName() ).isNotNull(); } - assertEquals(3, phones.size()); - }); + assertThat( phones ).hasSize( 3 ); + } ); } @Test - public void test_sql_hibernate_entity_associations_query_many_to_one_join_example() { - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + public void test_sql_hibernate_entity_associations_query_many_to_one_join_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); //tag::sql-hibernate-entity-associations-query-many-to-one-join-example[] List tuples = session.createNativeQuery( - "SELECT {ph.*}, {pr.*} " + - "FROM Phone ph " + - "JOIN Person pr ON ph.person_id = pr.id", Phone.class, "ph") - .addJoin("pr", "ph.person") - .list(); - - for (Phone phone : tuples) { - assertNotNull(phone.getPerson().getName()); + "SELECT {ph.*}, {pr.*} " + + "FROM Phone ph " + + "JOIN Person pr ON ph.person_id = pr.id", Phone.class, "ph" ) + .addJoin( "pr", "ph.person" ) + .list(); + + for ( Phone phone : tuples ) { + assertThat( phone.getPerson().getName() ).isNotNull(); } //end::sql-hibernate-entity-associations-query-many-to-one-join-example[] - assertEquals(3, tuples.size()); - }); + assertThat( tuples ).hasSize( 3 ); + } ); } @Test - public void test_sql_hibernate_entity_associations_query_many_to_one_join_result_transformer_example() { - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + public void test_sql_hibernate_entity_associations_query_many_to_one_join_result_transformer_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); //tag::sql-hibernate-entity-associations-query-many-to-one-join-tuple-transformer-example[] List phones = session.createNativeQuery( - "SELECT {ph.*}, {pr.*} " + - "FROM Phone ph " + - "JOIN Person pr ON ph.person_id = pr.id", Phone.class, "ph") - .addJoin("pr", "ph.person") - .setTupleTransformer( (TupleTransformer) (tuple, aliases) -> (Phone) tuple[0] ) - .list(); - - for (Phone person : phones) { + "SELECT {ph.*}, {pr.*} " + + "FROM Phone ph " + + "JOIN Person pr ON ph.person_id = pr.id", Phone.class, "ph" ) + .addJoin( "pr", "ph.person" ) + .setTupleTransformer( (TupleTransformer) (tuple, aliases) -> (Phone) tuple[0] ) + .list(); + + for ( Phone person : phones ) { person.getPerson(); } //end::sql-hibernate-entity-associations-query-many-to-one-join-tuple-transformer-example[] - assertEquals(3, phones.size()); - }); + assertThat( phones ).hasSize( 3 ); + } ); } @Test @RequiresDialect(H2Dialect.class) @RequiresDialect(OracleDialect.class) @RequiresDialect(PostgreSQLDialect.class) - public void test_sql_jpa_entity_associations_query_one_to_many_join_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_sql_jpa_entity_associations_query_one_to_many_join_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::sql-jpa-entity-associations-query-one-to-many-join-example[] List phones = entityManager.createNativeQuery( - "SELECT ph.* " + - "FROM Phone ph " + - "JOIN phone_call c ON c.phone_id = ph.id", Phone.class) - .getResultList(); + "SELECT ph.* " + + "FROM Phone ph " + + "JOIN phone_call c ON c.phone_id = ph.id", Phone.class ) + .getResultList(); - for (Phone phone : phones) { + for ( Phone phone : phones ) { List calls = phone.getCalls(); } //end::sql-jpa-entity-associations-query-one-to-many-join-example[] - assertEquals(2, phones.size()); - }); + assertThat( phones ).hasSize( 2 ); + } ); } @Test @JiraKey(value = "HHH-10504") - public void test_sql_hibernate_entity_associations_query_one_to_many_join_example_1() { - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + public void test_sql_hibernate_entity_associations_query_one_to_many_join_example_1(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); List phones = session.createNativeQuery( - "SELECT {ph.*}, {c.*} " + - "FROM Phone ph " + - "JOIN phone_call c ON c.phone_id = ph.id", Phone.class, "ph") - .addJoin("c", "ph.calls") - .list(); + "SELECT {ph.*}, {c.*} " + + "FROM Phone ph " + + "JOIN phone_call c ON c.phone_id = ph.id", Phone.class, "ph" ) + .addJoin( "c", "ph.calls" ) + .list(); - for (Phone phone : phones) { + for ( Phone phone : phones ) { List calls = phone.getCalls(); } - assertEquals(2, phones.size()); - }); + assertThat( phones ).hasSize( 2 ); + } ); } @Test @RequiresDialect(H2Dialect.class) @RequiresDialect(OracleDialect.class) @RequiresDialect(PostgreSQLDialect.class) - public void test_sql_hibernate_entity_associations_query_one_to_many_join_example_2() { - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + public void test_sql_hibernate_entity_associations_query_one_to_many_join_example_2(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); //tag::sql-hibernate-entity-associations-query-one-to-many-join-example[] List tuples = session.createNativeQuery( - "SELECT {ph.*}, {c.*} " + - "FROM Phone ph " + - "JOIN phone_call c ON c.phone_id = ph.id", Phone.class, "ph") - .addJoin("c", "ph.calls") - .list(); + "SELECT {ph.*}, {c.*} " + + "FROM Phone ph " + + "JOIN phone_call c ON c.phone_id = ph.id", Phone.class, "ph" ) + .addJoin( "c", "ph.calls" ) + .list(); - for (Phone phone : tuples) { + for ( Phone phone : tuples ) { List calls = phone.getCalls(); } //end::sql-hibernate-entity-associations-query-one-to-many-join-example[] - assertEquals(2, tuples.size()); - }); + assertThat( tuples ).hasSize( 2 ); + } ); } @Test - public void test_sql_jpa_multi_entity_query_example() { - try { - doInJPA(this::entityManagerFactory, entityManager -> { - //tag::sql-jpa-multi-entity-query-example[] - List entities = entityManager.createNativeQuery( - "SELECT * " + - "FROM Person pr, Partner pt " + - "WHERE pr.name = pt.name", Person.class) - .getResultList(); - //end::sql-jpa-multi-entity-query-example[] - assertEquals(2, entities.size()); - }); - fail("Should throw NonUniqueDiscoveredSqlAliasException!"); - } - catch (PersistenceException expected) { - assertEquals(NonUniqueDiscoveredSqlAliasException.class, expected.getClass()); - } + public void test_sql_jpa_multi_entity_query_example(EntityManagerFactoryScope scope) { + assertThrows( NonUniqueDiscoveredSqlAliasException.class, () -> scope.inTransaction( entityManager -> { + //tag::sql-jpa-multi-entity-query-example[] + List entities = entityManager.createNativeQuery( + "SELECT * " + + "FROM Person pr, Partner pt " + + "WHERE pr.name = pt.name", Person.class ) + .getResultList(); + //end::sql-jpa-multi-entity-query-example[] + assertThat( entities ).hasSize( 2 ); + } ) ); } @Test - public void test_sql_hibernate_multi_entity_query_example() { + public void test_sql_hibernate_multi_entity_query_example(EntityManagerFactoryScope scope) { try { - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); //tag::sql-hibernate-multi-entity-query-example[] List entities = session.createNativeQuery( - "SELECT * " + - "FROM Person pr, Partner pt " + - "WHERE pr.name = pt.name", Person.class) - .list(); + "SELECT * " + + "FROM Person pr, Partner pt " + + "WHERE pr.name = pt.name", Person.class ) + .list(); //end::sql-hibernate-multi-entity-query-example[] - assertEquals(2, entities.size()); - }); - fail("Should throw NonUniqueDiscoveredSqlAliasException!"); + assertThat( entities ).hasSize( 2 ); + } ); + fail( "Should throw NonUniqueDiscoveredSqlAliasException!" ); } catch (NonUniqueDiscoveredSqlAliasException e) { // expected } catch (PersistenceException e) { - assertTyping(NonUniqueDiscoveredSqlAliasException.class, e.getCause()); + assertThat( e.getCause() ).isInstanceOf( NonUniqueDiscoveredSqlAliasException.class ); } } @Test - @JiraKey( value = "HHH-15914" ) - public void test_sql_hibernate_multi_entity_query_alias_example() { - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + @JiraKey(value = "HHH-15914") + public void test_sql_hibernate_multi_entity_query_alias_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); //tag::sql-hibernate-multi-entity-query-alias-example[] List entities = session.createNativeQuery( - "SELECT {pr.*}, {pt.*} " + - "FROM Person pr, Partner pt " + - "WHERE pr.name = pt.name", Object.class) - .addEntity("pr", Person.class) - .addEntity("pt", Partner.class) - .list(); + "SELECT {pr.*}, {pt.*} " + + "FROM Person pr, Partner pt " + + "WHERE pr.name = pt.name", Object.class ) + .addEntity( "pr", Person.class ) + .addEntity( "pt", Partner.class ) + .list(); //end::sql-hibernate-multi-entity-query-alias-example[] - assertEquals(1, entities.size()); - }); + assertThat( entities ).hasSize( 1 ); + } ); } @Test - public void test_sql_hibernate_dto_query_example() { - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + public void test_sql_hibernate_dto_query_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); //tag::sql-hibernate-dto-query-example[] List dtos = session.createNativeQuery( - "SELECT p.id as \"id\", p.name as \"name\" " + - "FROM Person p", Tuple.class) - .setTupleTransformer( - (tuple, aliases) -> { - PersonSummaryDTO dto = new PersonSummaryDTO(); - dto.setId( (Long)tuple[0] ); - dto.setName( (String)tuple[1] ); - return dto; - } - ) - .list(); + "SELECT p.id as \"id\", p.name as \"name\" " + + "FROM Person p", Tuple.class ) + .setTupleTransformer( + (tuple, aliases) -> { + PersonSummaryDTO dto = new PersonSummaryDTO(); + dto.setId( (Long) tuple[0] ); + dto.setName( (String) tuple[1] ); + return dto; + } + ) + .list(); //end::sql-hibernate-dto-query-example[] - assertEquals(3, dtos.size()); - }); + assertThat( dtos ).hasSize( 3 ); + } ); } @Test - public void test_sql_hibernate_inheritance_query_example() { - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + public void test_sql_hibernate_inheritance_query_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); //tag::sql-hibernate-inheritance-query-example[] List payments = session.createNativeQuery( - "SELECT * " + - "FROM Payment p " + - "JOIN CreditCardPayment cp on cp.id = p.id", CreditCardPayment.class) - .list(); + "SELECT * " + + "FROM Payment p " + + "JOIN CreditCardPayment cp on cp.id = p.id", CreditCardPayment.class ) + .list(); //end::sql-hibernate-inheritance-query-example[] - assertEquals(1, payments.size()); - }); + assertThat( payments ).hasSize( 1 ); + } ); } @Test - public void test_sql_jpa_query_parameters_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_sql_jpa_query_parameters_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::sql-jpa-query-parameters-example[] List persons = entityManager.createNativeQuery( - "SELECT * " + - "FROM Person " + - "WHERE name like :name", Person.class) - .setParameter("name", "J%") - .getResultList(); + "SELECT * " + + "FROM Person " + + "WHERE name like :name", Person.class ) + .setParameter( "name", "J%" ) + .getResultList(); //end::sql-jpa-query-parameters-example[] - assertEquals(1, persons.size()); - }); + assertThat( persons ).hasSize( 1 ); + } ); } @Test - public void test_sql_hibernate_query_parameters_example() { - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + public void test_sql_hibernate_query_parameters_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); //tag::sql-hibernate-query-parameters-example[] List persons = session.createNativeQuery( - "SELECT * " + - "FROM Person " + - "WHERE name like :name", Person.class) - .setParameter("name", "J%") - .list(); + "SELECT * " + + "FROM Person " + + "WHERE name like :name", Person.class ) + .setParameter( "name", "J%" ) + .list(); //end::sql-hibernate-query-parameters-example[] - assertEquals(1, persons.size()); - }); + assertThat( persons ).hasSize( 1 ); + } ); } @Test - public void test_sql_jpa_scalar_named_query_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_sql_jpa_scalar_named_query_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::sql-jpa-scalar-named-query-example[] List names = entityManager.createNamedQuery( - "find_person_name", String.class) - .getResultList(); + "find_person_name", String.class ) + .getResultList(); //end::sql-jpa-scalar-named-query-example[] - assertEquals(3, names.size()); - }); + assertThat( names ).hasSize( 3 ); + + } ); } @Test - public void test_sql_hibernate_scalar_named_query_example() { - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + public void test_sql_hibernate_scalar_named_query_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); //tag::sql-hibernate-scalar-named-query-example[] List names = session.createNamedQuery( - "find_person_name", String.class) - .list(); + "find_person_name", String.class ) + .list(); //end::sql-hibernate-scalar-named-query-example[] - assertEquals(3, names.size()); - }); + assertThat( names ).hasSize( 3 ); + } ); } @Test - public void test_sql_jpa_multiple_scalar_values_named_query_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_sql_jpa_multiple_scalar_values_named_query_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::sql-jpa-multiple-scalar-values-named-query-example[] List tuples = entityManager.createNamedQuery( - "find_person_name_and_nickName", Object[].class) - .getResultList(); + "find_person_name_and_nickName", Object[].class ) + .getResultList(); - for(Object[] tuple : tuples) { + for ( Object[] tuple : tuples ) { String name = (String) tuple[0]; String nickName = (String) tuple[1]; } //end::sql-jpa-multiple-scalar-values-named-query-example[] - assertEquals(3, tuples.size()); - }); + assertThat( tuples ).hasSize( 3 ); + } ); } @Test - public void test_sql_hibernate_multiple_scalar_values_named_query_example() { - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + public void test_sql_hibernate_multiple_scalar_values_named_query_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); //tag::sql-hibernate-multiple-scalar-values-named-query-example[] List tuples = session.createNamedQuery( - "find_person_name_and_nickName", Object[].class) - .list(); + "find_person_name_and_nickName", Object[].class ) + .list(); - for(Object[] tuple : tuples) { + for ( Object[] tuple : tuples ) { String name = (String) tuple[0]; String nickName = (String) tuple[1]; } //end::sql-hibernate-multiple-scalar-values-named-query-example[] - assertEquals(3, tuples.size()); - }); + assertThat( tuples ).hasSize( 3 ); + } ); } @Test - public void test_sql_jpa_multiple_scalar_values_dto_named_query_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_sql_jpa_multiple_scalar_values_dto_named_query_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::sql-jpa-multiple-scalar-values-dto-named-query-example[] List personNames = entityManager.createNamedQuery( - "find_person_name_and_nickName_dto", PersonNames.class) - .getResultList(); + "find_person_name_and_nickName_dto", PersonNames.class ) + .getResultList(); //end::sql-jpa-multiple-scalar-values-dto-named-query-example[] - assertEquals(3, personNames.size()); - assertThat( personNames.get( 0) ).isNotNull(); - assertThat( personNames.get( 0) ).isInstanceOf( PersonNames.class); - }); + assertThat( personNames ).hasSize( 3 ); + + assertThat( personNames.get( 0 ) ).isNotNull(); + assertThat( personNames.get( 0 ) ).isInstanceOf( PersonNames.class ); + } ); } @Test - public void test_sql_hibernate_multiple_scalar_values_dto_named_query_example() { - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + public void test_sql_hibernate_multiple_scalar_values_dto_named_query_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); //tag::sql-hibernate-multiple-scalar-values-dto-named-query-example[] List personNames = session.createNamedQuery( - "find_person_name_and_nickName_dto", PersonNames.class) - .list(); + "find_person_name_and_nickName_dto", PersonNames.class ) + .list(); //end::sql-hibernate-multiple-scalar-values-dto-named-query-example[] - assertEquals(3, personNames.size()); - }); + assertThat( personNames ).hasSize( 3 ); + } ); } @Test - public void test_sql_hibernate_multiple_scalar_values_dto_hibernate_named_query_example() { - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + public void test_sql_hibernate_multiple_scalar_values_dto_hibernate_named_query_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); //tag::sql-hibernate-multiple-scalar-values-dto-hibernate-named-query-example[] List personNames = session.createNamedQuery( - "get_person_phone_count", PersonPhoneCount.class) - .getResultList(); + "get_person_phone_count", PersonPhoneCount.class ) + .getResultList(); //end::sql-hibernate-multiple-scalar-values-dto-hibernate-named-query-example[] - assertEquals(2, personNames.size()); - assertEquals( 1, personNames.stream().filter( person -> person.getName().equals( "John Doe")).map( PersonPhoneCount::getPhoneCount).findAny().get().intValue()); - assertEquals( 2, personNames.stream().filter( person -> person.getName().equals( "Mrs. John Doe")).map( PersonPhoneCount::getPhoneCount).findAny().get().intValue()); - }); + assertThat( personNames ).hasSize( 2 ); + assertThat( personNames.stream().filter( person -> person.getName().equals( "John Doe" ) ) + .map( PersonPhoneCount::getPhoneCount ).findAny().get().intValue() ).isEqualTo( 1 ); + assertThat( personNames.stream().filter( person -> person.getName().equals( "Mrs. John Doe" ) ) + .map( PersonPhoneCount::getPhoneCount ).findAny().get().intValue() ).isEqualTo( 2 ); + } ); } @Test - public void test_sql_jpa_entity_named_query_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_sql_jpa_entity_named_query_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::sql-jpa-entity-named-query-example[] List persons = entityManager.createNamedQuery( - "find_person_by_name", Person.class) - .setParameter("name", "J%") - .getResultList(); + "find_person_by_name", Person.class ) + .setParameter( "name", "J%" ) + .getResultList(); //end::sql-jpa-entity-named-query-example[] - assertEquals(1, persons.size()); + assertThat( persons ).hasSize( 1 ); + assertThat( persons ).hasSize( 1 ); assertThat( persons.get( 0 ) ).isInstanceOf( Person.class ); - }); + } ); } @Test - public void test_sql_hibernate_entity_named_query_example() { - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + public void test_sql_hibernate_entity_named_query_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); //tag::sql-hibernate-entity-named-query-example[] List persons = session.createNamedQuery( - "find_person_by_name", Person.class) - .setParameter("name", "J%") - .list(); + "find_person_by_name", Person.class ) + .setParameter( "name", "J%" ) + .list(); //end::sql-hibernate-entity-named-query-example[] - assertEquals(1, persons.size()); - }); + assertThat( persons ).hasSize( 1 ); + } ); } @Test @RequiresDialect(H2Dialect.class) @RequiresDialect(OracleDialect.class) @RequiresDialect(PostgreSQLDialect.class) - public void test_sql_jpa_entity_associations_named_query_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_sql_jpa_entity_associations_named_query_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::sql-jpa-entity-associations_named-query-example[] List tuples = entityManager.createNamedQuery( - "find_person_with_phones_by_name", Object[].class) - .setParameter("name", "J%") - .getResultList(); + "find_person_with_phones_by_name", Object[].class ) + .setParameter( "name", "J%" ) + .getResultList(); - for(Object[] tuple : tuples) { + for ( Object[] tuple : tuples ) { Person person = (Person) tuple[0]; Phone phone = (Phone) tuple[1]; } //end::sql-jpa-entity-associations_named-query-example[] - assertEquals(1, tuples.size()); - assertThat( tuples.get(0).getClass().isArray() ).isTrue(); - }); + assertThat( tuples ).hasSize( 1 ); + assertThat( tuples.get( 0 ).getClass().isArray() ).isTrue(); + } ); } @Test @RequiresDialect(H2Dialect.class) @RequiresDialect(OracleDialect.class) @RequiresDialect(PostgreSQLDialect.class) - public void test_sql_hibernate_entity_associations_named_query_example() { - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + public void test_sql_hibernate_entity_associations_named_query_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); //tag::sql-hibernate-entity-associations_named-query-example[] List tuples = session.createNamedQuery( - "find_person_with_phones_by_name", Object[].class) - .setParameter("name", "J%") - .list(); + "find_person_with_phones_by_name", Object[].class ) + .setParameter( "name", "J%" ) + .list(); - for(Object[] tuple : tuples) { + for ( Object[] tuple : tuples ) { Person person = (Person) tuple[0]; Phone phone = (Phone) tuple[1]; } //end::sql-hibernate-entity-associations_named-query-example[] - assertEquals(1, tuples.size()); - }); + assertThat( tuples ).hasSize( 1 ); + } ); } @Test - public void test_sql_jpa_composite_key_entity_associations_named_query_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_sql_jpa_composite_key_entity_associations_named_query_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::sql-jpa-composite-key-entity-associations_named-query-example[] List tuples = entityManager.createNamedQuery( - "find_all_spaceships", Object[].class) - .getResultList(); + "find_all_spaceships", Object[].class ) + .getResultList(); - for(Object[] tuple : tuples) { + for ( Object[] tuple : tuples ) { SpaceShip spaceShip = (SpaceShip) tuple[0]; Number surface = (Number) tuple[1]; Number volume = (Number) tuple[2]; } //end::sql-jpa-composite-key-entity-associations_named-query-example[] - assertEquals(1, tuples.size()); - SpaceShip spaceShip = (SpaceShip) tuples.get(0)[0]; - assertNotNull(spaceShip.getCaptain()); - assertTrue(spaceShip.getCaptain() instanceof HibernateProxy); - assertTrue(((HibernateProxy) spaceShip.getCaptain()).getHibernateLazyInitializer().isUninitialized()); - }); + assertThat( tuples ).hasSize( 1 ); + SpaceShip spaceShip = (SpaceShip) tuples.get( 0 )[0]; + assertThat( spaceShip.getCaptain() ).isNotNull(); + assertThat( spaceShip.getCaptain() ).isInstanceOf( HibernateProxy.class ); + assertThat( ((HibernateProxy) spaceShip.getCaptain()).getHibernateLazyInitializer() + .isUninitialized() ).isTrue(); + } ); } @Test - public void test_sql_hibernate_composite_key_entity_associations_named_query_example() { - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + public void test_sql_hibernate_composite_key_entity_associations_named_query_example(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap( Session.class ); //tag::sql-hibernate-composite-key-entity-associations_named-query-example[] List tuples = session.createNamedQuery( - "find_all_spaceships", Object[].class) - .list(); + "find_all_spaceships", Object[].class ) + .list(); - for(Object[] tuple : tuples) { + for ( Object[] tuple : tuples ) { SpaceShip spaceShip = (SpaceShip) tuple[0]; Number surface = (Number) tuple[1]; Number volume = (Number) tuple[2]; } //end::sql-hibernate-composite-key-entity-associations_named-query-example[] - assertEquals(1, tuples.size()); - }); + assertThat( tuples ).hasSize( 1 ); + } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/autodiscovery/AutoDiscoveryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/autodiscovery/AutoDiscoveryTest.java index 4b07143bad2a..8e728d7c9597 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/autodiscovery/AutoDiscoveryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/autodiscovery/AutoDiscoveryTest.java @@ -4,159 +4,178 @@ */ package org.hibernate.orm.test.sql.autodiscovery; +import org.hibernate.boot.model.naming.ImplicitNamingStrategy; +import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl; +import org.hibernate.cfg.AvailableSettings; +import org.hibernate.community.dialect.AltibaseDialect; +import org.hibernate.dialect.Dialect; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.JiraKey; +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.SettingProvider; +import org.hibernate.testing.orm.junit.SkipForDialect; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + import java.math.BigDecimal; -import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; -import java.sql.SQLException; import java.util.List; -import org.hibernate.Session; -import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl; -import org.hibernate.cfg.Configuration; -import org.hibernate.community.dialect.AltibaseDialect; -import org.hibernate.engine.spi.SessionImplementor; -import org.hibernate.jdbc.Work; +import static org.assertj.core.api.Assertions.assertThat; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.orm.junit.SkipForDialect; -import org.junit.Assert; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; /** * @author Steve Ebersole */ -public class AutoDiscoveryTest extends BaseCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + Group.class, + User.class, + Membership.class + } +) +@SessionFactory +@ServiceRegistry( + settingProviders = @SettingProvider( + settingName = AvailableSettings.IMPLICIT_NAMING_STRATEGY, + provider = AutoDiscoveryTest.ImplicitNamingStrategyProvider.class + ) +) +public class AutoDiscoveryTest { private static final String QUERY_STRING = "select u.name as username, g.name as groupname, m.joinDate " + - "from t_membership m " + - " inner join t_user u on m.member_id = u.id " + - " inner join t_group g on m.group_id = g.id"; + "from t_membership m " + + " inner join t_user u on m.member_id = u.id " + + " inner join t_group g on m.group_id = g.id"; - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - configuration.setImplicitNamingStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE ); + public static class ImplicitNamingStrategyProvider implements SettingProvider.Provider { + @Override + public ImplicitNamingStrategy getSetting() { + return ImplicitNamingStrategyJpaCompliantImpl.INSTANCE; + } } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Group.class, User.class, Membership.class }; + @AfterEach + public void tearDown(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Test - public void testAutoDiscoveryWithDuplicateColumnLabels() { - Session session = openSession(); - session.beginTransaction(); - session.persist( new User( "steve" ) ); - session.persist( new User( "stliu" ) ); - session.getTransaction().commit(); - session.close(); + public void testAutoDiscoveryWithDuplicateColumnLabels(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.persist( new User( "steve" ) ); + session.persist( new User( "stliu" ) ); + } + ); - session = openSession(); - session.beginTransaction(); - List results = session.createNativeQuery( - "select u.name, u2.name from t_user u, t_user u2 where u.name='steve'" ).list(); - // this should result in a result set like: - // [0] steve, steve - // [1] steve, stliu - // although the rows could be reversed - assertEquals( 2, results.size() ); - final Object[] row1 = (Object[]) results.get( 0 ); - final Object[] row2 = (Object[]) results.get( 1 ); - assertEquals( "steve", row1[0] ); - assertEquals( "steve", row2[0] ); - if ( "steve".equals( row1[1] ) ) { - assertEquals( "stliu", row2[1] ); - } - else { - assertEquals( "stliu", row1[1] ); - } - session.getTransaction().commit(); - session.close(); + scope.inTransaction( + session -> { + List results = session.createNativeQuery( + "select u.name, u2.name from t_user u, t_user u2 where u.name='steve'", Object[].class ) + .list(); + // this should result in a result set like: + // [0] steve, steve + // [1] steve, stliu + // although the rows could be reversed + assertThat( results ).hasSize( 2 ); + final Object[] row1 = results.get( 0 ); + final Object[] row2 = results.get( 1 ); + assertThat( row1[0] ).isEqualTo( "steve" ); + assertThat( row2[0] ).isEqualTo( "steve" ); + if ( "steve".equals( row1[1] ) ) { + assertThat( row2[1] ).isEqualTo( "stliu" ); + } + else { + assertThat( row1[1] ).isEqualTo( "stliu" ); + } - session = openSession(); - session.beginTransaction(); - session.createQuery( "delete from User" ).executeUpdate(); - session.getTransaction().commit(); - session.close(); + } + ); + scope.inTransaction( + session -> session.createMutationQuery( "delete from User" ).executeUpdate() + ); } @Test - public void testSqlQueryAutoDiscovery() throws Exception { - Session session = openSession(); - session.beginTransaction(); + public void testSqlQueryAutoDiscovery(SessionFactoryScope scope) { User u = new User( "steve" ); Group g = new Group( "developer" ); Membership m = new Membership( u, g ); - session.persist( u ); - session.persist( g ); - session.persist( m ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( + session -> { + session.persist( u ); + session.persist( g ); + session.persist( m ); + } + ); - session = openSession(); - session.beginTransaction(); - List result = session.createNativeQuery( QUERY_STRING ).list(); - Object[] row = (Object[]) result.get( 0 ); - Assert.assertEquals( "steve", row[0] ); - Assert.assertEquals( "developer", row[1] ); - session.remove( m ); - session.remove( u ); - session.remove( g ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( + session -> { + List result = session.createNativeQuery( QUERY_STRING, Object[].class ).list(); + Object[] row = result.get( 0 ); + assertThat( row[0] ).isEqualTo( "steve" ); + assertThat( row[1] ).isEqualTo( "developer" ); + session.remove( m ); + session.remove( u ); + session.remove( g ); + } + ); } @Test - public void testDialectGetColumnAliasExtractor() { - Session session = openSession(); - final SessionImplementor sessionImplementor = (SessionImplementor) session; - session.beginTransaction(); - session.doWork( - new Work() { - @Override - public void execute(Connection connection) throws SQLException { - PreparedStatement ps = sessionImplementor.getJdbcCoordinator().getStatementPreparer().prepareStatement( QUERY_STRING ); - ResultSet rs = sessionImplementor.getJdbcCoordinator().getResultSetReturn().extract( ps, QUERY_STRING ); - try { - ResultSetMetaData metadata = rs.getMetaData(); - String column1Alias = getDialect().getColumnAliasExtractor().extractColumnAlias( metadata, 1 ); - String column2Alias = getDialect().getColumnAliasExtractor().extractColumnAlias( metadata, 2 ); - Assert.assertFalse( "bad dialect.getColumnAliasExtractor impl", column1Alias.equals( column2Alias ) ); - } - finally { - sessionImplementor.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( rs, ps ); - sessionImplementor.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( ps ); - } - } - } + public void testDialectGetColumnAliasExtractor(SessionFactoryScope scope) { + scope.inTransaction( + session -> + session.doWork( + connection -> { + Dialect dialect = session.getDialect(); + PreparedStatement ps = session.getJdbcCoordinator() + .getStatementPreparer().prepareStatement( QUERY_STRING ); + ResultSet rs = session.getJdbcCoordinator().getResultSetReturn() + .extract( ps, QUERY_STRING ); + try { + ResultSetMetaData metadata = rs.getMetaData(); + String column1Alias = dialect.getColumnAliasExtractor() + .extractColumnAlias( metadata, 1 ); + String column2Alias = dialect.getColumnAliasExtractor() + .extractColumnAlias( metadata, 2 ); + assertThat( column1Alias.equals( column2Alias ) ) + .describedAs( "bad dialect.getColumnAliasExtractor impl" ) + .isFalse(); + } + finally { + session.getJdbcCoordinator().getLogicalConnection() + .getResourceRegistry().release( rs, ps ); + session.getJdbcCoordinator().getLogicalConnection() + .getResourceRegistry().release( ps ); + } + } + ) ); - session.getTransaction().commit(); - session.close(); } @Test - @JiraKey( "HHH-16697" ) - @SkipForDialect( dialectClass = AltibaseDialect.class, reason = "Altibase sum(39.74) returns Float" ) - public void testAggregateQueryAutoDiscovery() { - Session session = openSession(); - session.beginTransaction(); + @JiraKey("HHH-16697") + @SkipForDialect(dialectClass = AltibaseDialect.class, reason = "Altibase sum(39.74) returns Float", + matchSubTypes = true) + public void testAggregateQueryAutoDiscovery(SessionFactoryScope scope) { User u = new User( "steve" ); - session.persist( u ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( + session -> session.persist( u ) + ); - session = openSession(); - session.beginTransaction(); - List result = session.createNativeQuery( "select sum(39.74) from t_user u" ).list(); - Assert.assertEquals( new BigDecimal( "39.74" ), result.get( 0 ) ); - session.remove( u ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( + session -> { + List result = session.createNativeQuery( "select sum(39.74) from t_user u", Object.class ) + .list(); + assertThat( result.get( 0 ) ).isEqualTo( new BigDecimal( "39.74" ) ); + session.remove( u ); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/check/OracleCheckStyleTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/check/OracleCheckStyleTest.java index 2b7d6b6a283c..f0c98017a95a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/check/OracleCheckStyleTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/check/OracleCheckStyleTest.java @@ -5,21 +5,17 @@ package org.hibernate.orm.test.sql.check; import org.hibernate.dialect.OracleDialect; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.RequiresDialect; -import org.hibernate.testing.RequiresDialect; /** * @author Steve Ebersole */ -@RequiresDialect( value = OracleDialect.class ) +@RequiresDialect(value = OracleDialect.class) +@DomainModel( + xmlMappings = "org/hibernate/orm/test/sql/check/oracle-mappings.hbm.xml", + overrideCacheStrategy = false +) public class OracleCheckStyleTest extends ResultCheckStyleTest { - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } - - @Override - public String[] getMappings() { - return new String[] { "sql/check/oracle-mappings.hbm.xml" }; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/check/ResultCheckStyleTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/check/ResultCheckStyleTest.java index 7ba8a8fec828..331a29efd52c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/check/ResultCheckStyleTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/check/ResultCheckStyleTest.java @@ -4,137 +4,118 @@ */ package org.hibernate.orm.test.sql.check; -import org.hibernate.Session; +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 org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; - -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * @author Steve Ebersole */ @SuppressWarnings("unused") -public abstract class ResultCheckStyleTest extends BaseCoreFunctionalTestCase { +@SessionFactory +public abstract class ResultCheckStyleTest { public String getCacheConcurrencyStrategy() { return null; } + @AfterEach + public void cleanUp(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); + } + @Test - public void testInsertionFailureWithExceptionChecking() { - Session s = openSession(); - s.beginTransaction(); - ExceptionCheckingEntity e = new ExceptionCheckingEntity(); - e.setName( "dummy" ); - s.persist( e ); - try { - s.flush(); - fail( "expection flush failure!" ); - } - catch( Exception ex ) { - // these should specifically be JDBCExceptions... - } - s.clear(); - s.getTransaction().rollback(); - s.close(); + public void testInsertionFailureWithExceptionChecking(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + ExceptionCheckingEntity e = new ExceptionCheckingEntity(); + e.setName( "dummy" ); + session.persist( e ); + // these should specifically be JDBCExceptions... + Exception exception = assertThrows( Exception.class, session::flush ); + + session.clear(); + } + ); } @Test - public void testInsertionFailureWithParamChecking() { - Session s = openSession(); - s.beginTransaction(); - ParamCheckingEntity e = new ParamCheckingEntity(); - e.setName( "dummy" ); - s.persist( e ); - try { - s.flush(); - fail( "expection flush failure!" ); - } - catch( Exception ex ) { - // these should specifically be HibernateExceptions... - } - s.clear(); - s.getTransaction().rollback(); - s.close(); + public void testInsertionFailureWithParamChecking(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + ParamCheckingEntity e = new ParamCheckingEntity(); + e.setName( "dummy" ); + session.persist( e ); + // these should specifically be HibernateExceptions... + assertThrows( Exception.class, session::flush ); + session.clear(); + } + ); } @Test - public void testMergeFailureWithExceptionChecking() { - Session s = openSession(); - s.beginTransaction(); - ExceptionCheckingEntity e = new ExceptionCheckingEntity(); - e.setId( Long.valueOf( 1 ) ); - e.setName( "dummy" ); - try { - s.merge( e ); - s.flush(); - fail( "expection flush failure!" ); - } - catch( Exception ex ) { - // these should specifically be JDBCExceptions... - } - s.clear(); - s.getTransaction().rollback(); - s.close(); + public void testMergeFailureWithExceptionChecking(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + ExceptionCheckingEntity e = new ExceptionCheckingEntity(); + e.setId( 1L ); + e.setName( "dummy" ); + // these should specifically be JDBCExceptions... + assertThrows( Exception.class, () -> { + session.merge( e ); + session.flush(); + } ); + session.clear(); + } + ); } @Test - public void testUpdateFailureWithParamChecking() { - Session s = openSession(); - s.beginTransaction(); - ParamCheckingEntity e = new ParamCheckingEntity(); - e.setId( Long.valueOf( 1 ) ); - e.setName( "dummy" ); - try { - s.merge( e ); - s.flush(); - fail( "expection flush failure!" ); - } - catch( Exception ex ) { - // these should specifically be HibernateExceptions... - } - s.clear(); - s.getTransaction().rollback(); - s.close(); + public void testUpdateFailureWithParamChecking(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + ParamCheckingEntity e = new ParamCheckingEntity(); + e.setId( 1L ); + e.setName( "dummy" ); + // these should specifically be HibernateExceptions... + assertThrows( Exception.class, () -> { + session.merge( e ); + session.flush(); + } ); + session.clear(); + } + ); } @Test - public void testDeleteWithExceptionChecking() { - Session s = openSession(); - s.beginTransaction(); - ExceptionCheckingEntity e = new ExceptionCheckingEntity(); - e.setId( Long.valueOf( 1 ) ); - e.setName( "dummy" ); - s.remove( e ); - try { - s.flush(); - fail( "expection flush failure!" ); - } - catch( Exception ex ) { - // these should specifically be JDBCExceptions... - } - s.clear(); - s.getTransaction().rollback(); - s.close(); + public void testDeleteWithExceptionChecking(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + ExceptionCheckingEntity e = new ExceptionCheckingEntity(); + e.setId( Long.valueOf( 1 ) ); + e.setName( "dummy" ); + session.remove( e ); + // these should specifically be JDBCExceptions... + assertThrows( Exception.class, session::flush ); + session.clear(); + } + ); } @Test - public void testDeleteWithParamChecking() { - Session s = openSession(); - s.beginTransaction(); - ParamCheckingEntity e = new ParamCheckingEntity(); - e.setId( Long.valueOf( 1 ) ); - e.setName( "dummy" ); - s.remove( e ); - try { - s.flush(); - fail( "expection flush failure!" ); - } - catch( Exception ex ) { - // these should specifically be HibernateExceptions... - } - s.clear(); - s.getTransaction().rollback(); - s.close(); + public void testDeleteWithParamChecking(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + ParamCheckingEntity e = new ParamCheckingEntity(); + e.setId( Long.valueOf( 1 ) ); + e.setName( "dummy" ); + session.remove( e ); + // these should specifically be HibernateExceptions... + assertThrows( Exception.class, session::flush ); + session.clear(); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/function/JpaFunctionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/function/JpaFunctionTest.java index 1cbcf9ce3c6e..67867cef667a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/function/JpaFunctionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/function/JpaFunctionTest.java @@ -4,78 +4,72 @@ */ package org.hibernate.orm.test.sql.function; -import java.sql.Timestamp; -import java.util.Date; import jakarta.persistence.Entity; import jakarta.persistence.Id; - import org.hibernate.dialect.H2Dialect; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - import org.hibernate.query.SyntaxException; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import java.sql.Timestamp; +import java.util.Date; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * @author Vlad Mihalcea */ -@JiraKey( value = "HHH-11233") +@JiraKey(value = "HHH-11233") @RequiresDialect(H2Dialect.class) -public class JpaFunctionTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Event.class - }; - } - - @Override - protected void afterEntityManagerFactoryBuilt() { - super.afterEntityManagerFactoryBuilt(); - doInJPA( this::entityManagerFactory, entityManager -> { - Event event = new Event(); - event.setId( 1L ); - event.setMessage( "ABC" ); - event.setCreatedOn( Timestamp.valueOf( "9999-12-31 00:00:00" ) ); - entityManager.persist( event ); - } ); +@Jpa( + annotatedClasses = { + JpaFunctionTest.Event.class + } +) +public class JpaFunctionTest { + + @BeforeAll + protected void afterEntityManagerFactoryBuilt(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + Event event = new Event(); + event.setId( 1L ); + event.setMessage( "ABC" ); + event.setCreatedOn( Timestamp.valueOf( "9999-12-31 00:00:00" ) ); + entityManager.persist( event ); + } + ); } @Test - public void testWithoutComma() { - doInJPA( this::entityManagerFactory, entityManager -> { - Date now = entityManager.createQuery( - "select FUNCTION('now') " + - "from Event " + - "where id = :id", Date.class) - .setParameter( "id", 1L ) - .getSingleResult(); - log.infof( "Current time: {}", now ); - } ); + public void testWithoutComma(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> + entityManager.createQuery( + "select FUNCTION('now') " + + "from Event " + + "where id = :id", Date.class ) + .setParameter( "id", 1L ) + .getSingleResult() + ); } @Test - public void testWithoutCommaFail() { - try { - doInJPA( this::entityManagerFactory, entityManager -> { - String result = entityManager.createQuery( - "select FUNCTION('substring' 'abc', 1,2) " + - "from Event " + - "where id = :id", String.class) - .setParameter( "id", 1L ) - .getSingleResult(); - fail("Should have thrown exception"); - } ); - } - catch ( Exception e ) { - assertEquals( SyntaxException.class, e.getCause().getClass() ); - } + public void testWithoutCommaFail(EntityManagerFactoryScope scope) { + Exception exception = assertThrows( Exception.class, () -> + scope.inTransaction( entityManager -> + entityManager.createQuery( + "select FUNCTION('substring' 'abc', 1,2) " + + "from Event " + + "where id = :id", String.class ) + .setParameter( "id", 1L ) + .getSingleResult() + ) ); + assertThat( exception.getCause() ).isInstanceOf( SyntaxException.class ); } @Entity(name = "Event") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/Organization.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/Organization.java index 44108acfdb3d..92a18c94e392 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/Organization.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/Organization.java @@ -3,6 +3,7 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.sql.hand; + import java.util.Collection; import java.util.HashSet; @@ -12,11 +13,11 @@ public class Organization { private long id; private String name; - private Collection employments; + private Collection employments; public Organization(String name) { this.name = name; - employments = new HashSet(); + employments = new HashSet<>(); } public Organization() {} @@ -24,13 +25,13 @@ public Organization() {} /** * @return Returns the employments. */ - public Collection getEmployments() { + public Collection getEmployments() { return employments; } /** * @param employments The employments to set. */ - public void setEmployments(Collection employments) { + public void setEmployments(Collection employments) { this.employments = employments; } /** diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/custom/CustomSQLTestSupport.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/custom/CustomSQLTestSupport.java index 2b001030f428..a0989511949c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/custom/CustomSQLTestSupport.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/custom/CustomSQLTestSupport.java @@ -4,25 +4,24 @@ */ package org.hibernate.orm.test.sql.hand.custom; -import java.util.Arrays; -import java.util.Date; -import java.util.Iterator; - import org.hibernate.LockMode; -import org.hibernate.Session; -import org.hibernate.Transaction; - -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.orm.test.sql.hand.Employment; import org.hibernate.orm.test.sql.hand.ImageHolder; import org.hibernate.orm.test.sql.hand.Organization; import org.hibernate.orm.test.sql.hand.Person; import org.hibernate.orm.test.sql.hand.TextHolder; -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.Date; +import java.util.Iterator; + +import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * Abstract test case defining tests for the support for user-supplied (aka @@ -30,139 +29,143 @@ * * @author Steve Ebersole */ -@SuppressWarnings("unused") -public abstract class CustomSQLTestSupport extends BaseCoreFunctionalTestCase { - public String getCacheConcurrencyStrategy() { - return null; +@DomainModel( + overrideCacheStrategy = false +) +@SessionFactory +public abstract class CustomSQLTestSupport { + + @AfterEach + public void tearDown(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Test - public void testHandSQL() { - Session s = openSession(); - Transaction t = s.beginTransaction(); + public void testHandSQL(SessionFactoryScope scope) { Organization ifa = new Organization( "IFA" ); - Organization jboss = new Organization( "JBoss" ); - Person gavin = new Person( "Gavin" ); - Employment emp = new Employment( gavin, jboss, "AU" ); - s.persist( jboss ); - Object orgId = jboss.getId(); - s.persist( ifa ); - s.persist( gavin ); - s.persist( emp ); - t.commit(); - - t = s.beginTransaction(); - Person christian = new Person( "Christian" ); - s.persist( christian ); - Employment emp2 = new Employment( christian, jboss, "EU" ); - s.persist( emp2 ); - t.commit(); - s.close(); - - sessionFactory().getCache().evictEntityData( Organization.class ); - sessionFactory().getCache().evictEntityData( Person.class ); - sessionFactory().getCache().evictEntityData( Employment.class ); - - s = openSession(); - t = s.beginTransaction(); - jboss = ( Organization ) s.get( Organization.class, orgId ); - assertEquals( jboss.getEmployments().size(), 2 ); - assertEquals( jboss.getName(), "JBOSS" ); - emp = ( Employment ) jboss.getEmployments().iterator().next(); - gavin = emp.getEmployee(); - assertEquals( "GAVIN" , gavin.getName() ); - assertEquals( LockMode.PESSIMISTIC_WRITE , s.getCurrentLockMode( gavin )); - emp.setEndDate( new Date() ); - Employment emp3 = new Employment( gavin, jboss, "US" ); - s.persist( emp3 ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - Iterator itr = s.getNamedQuery( "allOrganizationsWithEmployees" ).list().iterator(); - assertTrue( itr.hasNext() ); - Organization o = ( Organization ) itr.next(); - assertEquals( o.getEmployments().size(), 3 ); - Iterator itr2 = o.getEmployments().iterator(); - while ( itr2.hasNext() ) { - Employment e = ( Employment ) itr2.next(); - s.remove( e ); - } - itr2 = o.getEmployments().iterator(); - while ( itr2.hasNext() ) { - Employment e = ( Employment ) itr2.next(); - s.remove( e.getEmployee() ); - } - s.remove( o ); - assertFalse( itr.hasNext() ); - s.remove( ifa ); - t.commit(); - s.close(); + Object orgId = scope.fromTransaction( + session -> { + Organization jboss = new Organization( "JBoss" ); + Person gavin = new Person( "Gavin" ); + Employment emp = new Employment( gavin, jboss, "AU" ); + session.persist( jboss ); + Object oId = jboss.getId(); + session.persist( ifa ); + session.persist( gavin ); + session.persist( emp ); + Person christian = new Person( "Christian" ); + session.persist( christian ); + Employment emp2 = new Employment( christian, jboss, "EU" ); + session.persist( emp2 ); + return oId; + } + ); + + SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); + sessionFactory.getCache().evictEntityData( Organization.class ); + sessionFactory.getCache().evictEntityData( Person.class ); + sessionFactory.getCache().evictEntityData( Employment.class ); + + scope.inTransaction( + session -> { + Organization jboss = session.get( Organization.class, orgId ); + assertThat( jboss.getEmployments() ).hasSize( 2 ); + assertThat( jboss.getName() ).isEqualTo( "JBOSS" ); + Employment emp = jboss.getEmployments().iterator().next(); + Person gavin = emp.getEmployee(); + assertThat( gavin.getName() ).isEqualTo( "GAVIN" ); + assertThat( session.getCurrentLockMode( gavin ) ).isEqualTo( LockMode.PESSIMISTIC_WRITE ); + emp.setEndDate( new Date() ); + Employment emp3 = new Employment( gavin, jboss, "US" ); + session.persist( emp3 ); + } + ); + + scope.inTransaction( + session -> { + Iterator itr = session.getNamedQuery( "allOrganizationsWithEmployees" ).list().iterator(); + assertThat( itr.hasNext() ).isTrue(); + Organization o = (Organization) itr.next(); + assertThat( o.getEmployments() ).hasSize( 3 ); + Iterator itr2 = o.getEmployments().iterator(); + while ( itr2.hasNext() ) { + Employment e = (Employment) itr2.next(); + session.remove( e ); + } + itr2 = o.getEmployments().iterator(); + while ( itr2.hasNext() ) { + Employment e = (Employment) itr2.next(); + session.remove( e.getEmployee() ); + } + session.remove( o ); + assertThat( itr.hasNext() ).isFalse(); + session.remove( ifa ); + } + ); } @Test - public void testTextProperty() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - String description = buildLongString( 15000, 'a' ); - TextHolder holder = new TextHolder( description ); - s.persist( holder ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - holder = s.get( TextHolder.class, holder.getId() ); - assertEquals( description, holder.getDescription() ); - description = buildLongString( 15000, 'b' ); - holder.setDescription( description ); - s.persist( holder ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - holder = s.get( TextHolder.class, holder.getId() ); - assertEquals( description, holder.getDescription() ); - s.remove( holder ); - t.commit(); - s.close(); + public void testTextProperty(SessionFactoryScope scope) { + String d = buildLongString( 15000, 'a' ); + TextHolder h = new TextHolder( d ); + scope.inTransaction( + session -> { + session.persist( h ); + } + ); + + String description = buildLongString( 15000, 'b' ); + scope.inTransaction( + session -> { + TextHolder holder = session.get( TextHolder.class, h.getId() ); + assertThat( holder.getDescription() ).isEqualTo( d ); + holder.setDescription( description ); + session.persist( holder ); + } + ); + + scope.inTransaction( + session -> { + TextHolder holder = session.get( TextHolder.class, h.getId() ); + assertThat( holder.getDescription() ).isEqualTo( description ); + session.remove( holder ); + } + ); } @Test - public void testImageProperty() { - Session s = openSession(); - Transaction t = s.beginTransaction(); + public void testImageProperty(SessionFactoryScope scope) { // Make sure the last byte is non-zero as Sybase cuts that off - byte[] photo = buildLongByteArray( 14999, true ); - ImageHolder holder = new ImageHolder( photo ); - s.persist( holder ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - holder = s.get( ImageHolder.class, holder.getId() ); - assertTrue( Arrays.equals( photo, holder.getPhoto() ) ); - photo = buildLongByteArray( 15000, false ); - holder.setPhoto( photo ); - s.persist( holder ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - holder = s.get( ImageHolder.class, holder.getId() ); - assertTrue( Arrays.equals( photo, holder.getPhoto() ) ); - s.remove( holder ); - t.commit(); - s.close(); + byte[] p = buildLongByteArray( 14999, true ); + ImageHolder h = new ImageHolder( p ); + scope.inTransaction( + session -> { + session.persist( h ); + } + ); + + byte[] photo = buildLongByteArray( 15000, false ); + scope.inTransaction( + session -> { + ImageHolder holder = session.get( ImageHolder.class, h.getId() ); + assertThat( holder.getPhoto() ).isEqualTo( p ); + holder.setPhoto( photo ); + session.persist( holder ); + } + ); + + scope.inTransaction( + session -> { + ImageHolder holder = session.get( ImageHolder.class, h.getId() ); + assertThat( holder.getPhoto() ).isEqualTo( photo ); + session.remove( h ); + } + ); } private String buildLongString(int size, char baseChar) { StringBuilder buff = new StringBuilder(); - for( int i = 0; i < size; i++ ) { + for ( int i = 0; i < size; i++ ) { buff.append( baseChar ); } return buff.toString(); @@ -179,6 +182,6 @@ private byte[] buildLongByteArray(int size, boolean on) { } private byte mask(boolean on) { - return on ? ( byte ) 1 : ( byte ) 0; + return on ? (byte) 1 : (byte) 0; } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/custom/CustomStoredProcTestSupport.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/custom/CustomStoredProcTestSupport.java index 5d7bd28f18fa..062026682f30 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/custom/CustomStoredProcTestSupport.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/custom/CustomStoredProcTestSupport.java @@ -4,111 +4,92 @@ */ package org.hibernate.orm.test.sql.hand.custom; -import java.sql.SQLException; -import java.util.List; - -import org.junit.Test; - -import org.hibernate.HibernateException; -import org.hibernate.procedure.ProcedureCall; -import org.hibernate.Session; -import org.hibernate.Transaction; import org.hibernate.orm.test.sql.hand.Employment; import org.hibernate.orm.test.sql.hand.Organization; import org.hibernate.orm.test.sql.hand.Person; +import org.hibernate.procedure.ProcedureCall; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Abstract test case defining tests of stored procedure support. * * @author Gail Badner */ -@SuppressWarnings("unused") public abstract class CustomStoredProcTestSupport extends CustomSQLTestSupport { - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } - @Test - public void testScalarStoredProcedure() throws HibernateException, SQLException { - Session s = openSession(); -// Query namedQuery = s.getNamedQuery( "simpleScalar" ); - ProcedureCall namedQuery = s.createNamedStoredProcedureQuery( "simpleScalar" ); - namedQuery.setParameter( "p_number", 43 ); - List list = namedQuery.getResultList(); - Object o[] = ( Object[] ) list.get( 0 ); - assertEquals( o[0], "getAll" ); - assertEquals( o[1], Long.valueOf( 43 ) ); - s.close(); + public void testScalarStoredProcedure(SessionFactoryScope scope) { + scope.inSession( + session -> { + ProcedureCall namedQuery = session.createNamedStoredProcedureQuery( "simpleScalar" ); + namedQuery.setParameter( "p_number", 43 ); + List list = namedQuery.getResultList(); + Object[] o = (Object[]) list.get( 0 ); + assertThat( o[0] ).isEqualTo( "getAll" ); + assertThat( o[1] ).isEqualTo( 43L ); + } + ); } @Test - public void testParameterHandling() throws HibernateException, SQLException { - Session s = openSession(); - + public void testParameterHandling(SessionFactoryScope scope) { // Query namedQuery = s.getNamedQuery( "paramhandling" ); - ProcedureCall namedQuery = s.createNamedStoredProcedureQuery( "paramhandling" ); - namedQuery.setParameter( 1, 10 ); - namedQuery.setParameter( 2, 20 ); - List list = namedQuery.getResultList(); - Object[] o = ( Object[] ) list.get( 0 ); - assertEquals( o[0], Long.valueOf( 10 ) ); - assertEquals( o[1], Long.valueOf( 20 ) ); - s.close(); + scope.inSession( + session -> { + ProcedureCall namedQuery = session.createNamedStoredProcedureQuery( "paramhandling" ); + namedQuery.setParameter( 1, 10 ); + namedQuery.setParameter( 2, 20 ); + List list = namedQuery.getResultList(); + Object[] o = (Object[]) list.get( 0 ); + assertThat( o[0] ).isEqualTo( 10L ); + assertThat( o[1] ).isEqualTo( 20L ); + } + ); } @Test - public void testMixedParameterHandling() throws HibernateException, SQLException { - inTransaction( + public void testMixedParameterHandling(SessionFactoryScope scope) { + scope.inTransaction( session -> { - try { - session.createNamedStoredProcedureQuery( "paramhandling_mixed" ); - fail( "Expecting an exception" ); - } - catch (IllegalArgumentException expected) { - assertEquals( - "Cannot mix named parameter with positional parameter registrations", - expected.getMessage() - ); - } - catch (Exception other) { - throw new AssertionError( "Expecting a ParameterRecognitionException, but encountered " + other.getClass().getSimpleName(), other ); - } + IllegalArgumentException illegalArgumentException = + assertThrows( IllegalArgumentException.class, () -> + session.createNamedStoredProcedureQuery( "paramhandling_mixed" ) ); + assertThat( illegalArgumentException.getMessage() ) + .isEqualTo( "Cannot mix named parameter with positional parameter registrations" ); } ); } @Test - public void testEntityStoredProcedure() throws HibernateException, SQLException { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Organization ifa = new Organization( "IFA" ); - Organization jboss = new Organization( "JBoss" ); - Person gavin = new Person( "Gavin" ); - Employment emp = new Employment( gavin, jboss, "AU" ); - s.persist( ifa ); - s.persist( jboss ); - s.persist( gavin ); - s.persist( emp ); - s.flush(); - -// Query namedQuery = s.getNamedQuery( "selectAllEmployments" ); - ProcedureCall namedQuery = s.createNamedStoredProcedureQuery( "selectAllEmployments" ); - List list = namedQuery.getResultList(); - assertTrue( list.get( 0 ) instanceof Employment ); - s.remove( emp ); - s.remove( ifa ); - s.remove( jboss ); - s.remove( gavin ); + public void testEntityStoredProcedure(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Organization ifa = new Organization( "IFA" ); + Organization jboss = new Organization( "JBoss" ); + Person gavin = new Person( "Gavin" ); + Employment emp = new Employment( gavin, jboss, "AU" ); + session.persist( ifa ); + session.persist( jboss ); + session.persist( gavin ); + session.persist( emp ); + session.flush(); - t.commit(); - s.close(); + // Query namedQuery = s.getNamedQuery( "selectAllEmployments" ); + ProcedureCall namedQuery = session.createNamedStoredProcedureQuery( "selectAllEmployments" ); + List list = namedQuery.getResultList(); + assertThat( list.get( 0 ) ).isInstanceOf( Employment.class ); + session.remove( emp ); + session.remove( ifa ); + session.remove( jboss ); + session.remove( gavin ); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/custom/db2/DB2CustomSQLTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/custom/db2/DB2CustomSQLTest.java index 3c6c5b3321d0..53dfad6f07b8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/custom/db2/DB2CustomSQLTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/custom/db2/DB2CustomSQLTest.java @@ -6,17 +6,17 @@ import org.hibernate.dialect.DB2Dialect; import org.hibernate.orm.test.sql.hand.custom.CustomStoredProcTestSupport; - -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.RequiresDialect; /** * Custom SQL tests for DB2 * * @author Max Rydahl Andersen */ -@RequiresDialect( DB2Dialect.class ) +@RequiresDialect(DB2Dialect.class) +@DomainModel( + xmlMappings = "org/hibernate/orm/test/sql/hand/custom/db2/Mappings.hbm.xml" +) public class DB2CustomSQLTest extends CustomStoredProcTestSupport { - public String[] getMappings() { - return new String[] { "sql/hand/custom/db2/Mappings.hbm.xml" }; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/custom/mysql/MySQLCustomSQLTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/custom/mysql/MySQLCustomSQLTest.java index 78fd87a931af..0fc80b6d0769 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/custom/mysql/MySQLCustomSQLTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/custom/mysql/MySQLCustomSQLTest.java @@ -4,22 +4,23 @@ */ package org.hibernate.orm.test.sql.hand.custom.mysql; -import org.hibernate.dialect.MySQLDialect; import org.hibernate.community.dialect.TiDBDialect; +import org.hibernate.dialect.MySQLDialect; import org.hibernate.orm.test.sql.hand.custom.CustomStoredProcTestSupport; - -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.SkipForDialect; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.SkipForDialect; /** * Custom SQL tests for MySQL * * @author Gavin King */ -@RequiresDialect( MySQLDialect.class ) -@SkipForDialect(value = TiDBDialect.class, comment = "TiDB doesn't support stored procedures") +@RequiresDialect(MySQLDialect.class) +@SkipForDialect(dialectClass = TiDBDialect.class, reason = "TiDB doesn't support stored procedures", + matchSubTypes = true) +@DomainModel( + xmlMappings = "org/hibernate/orm/test/sql/hand/custom/mysql/Mappings.hbm.xml" +) public class MySQLCustomSQLTest extends CustomStoredProcTestSupport { - public String[] getMappings() { - return new String[] { "sql/hand/custom/mysql/Mappings.hbm.xml" }; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/custom/oracle/OracleCustomSQLTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/custom/oracle/OracleCustomSQLTest.java index c46c59cc34ae..1449827737d4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/custom/oracle/OracleCustomSQLTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/custom/oracle/OracleCustomSQLTest.java @@ -6,17 +6,20 @@ import org.hibernate.dialect.OracleDialect; import org.hibernate.orm.test.sql.hand.custom.CustomStoredProcTestSupport; - -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.RequiresDialect; /** * Custom SQL tests for Oracle * * @author Gavin King */ -@RequiresDialect( OracleDialect.class ) +@RequiresDialect(OracleDialect.class) +@DomainModel( + xmlMappings = { + "org/hibernate/orm/test/sql/hand/custom/oracle/Mappings.hbm.xml", + "org/hibernate/orm/test/sql/hand/custom/oracle/StoredProcedures.hbm.xml" + } +) public class OracleCustomSQLTest extends CustomStoredProcTestSupport { - public String[] getMappings() { - return new String[] { "sql/hand/custom/oracle/Mappings.hbm.xml", "sql/hand/custom/oracle/StoredProcedures.hbm.xml" }; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/custom/sqlserver/SQLServerCustomSQLTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/custom/sqlserver/SQLServerCustomSQLTest.java index 15a4496fe2c2..fd42b7db2c02 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/custom/sqlserver/SQLServerCustomSQLTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/custom/sqlserver/SQLServerCustomSQLTest.java @@ -6,17 +6,17 @@ import org.hibernate.dialect.SQLServerDialect; import org.hibernate.orm.test.sql.hand.custom.CustomStoredProcTestSupport; - -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.RequiresDialect; /** * Custom SQL tests for SQLServer * * @author Gail Badner */ -@RequiresDialect( SQLServerDialect.class ) +@RequiresDialect(SQLServerDialect.class) +@DomainModel( + xmlMappings = "org/hibernate/orm/test/sql/hand/custom/sqlserver/Mappings.hbm.xml" +) public class SQLServerCustomSQLTest extends CustomStoredProcTestSupport { - public String[] getMappings() { - return new String[] { "sql/hand/custom/sqlserver/Mappings.hbm.xml" }; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/custom/sybase/SybaseCustomSQLTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/custom/sybase/SybaseCustomSQLTest.java index 245212272299..dced3c5c0b88 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/custom/sybase/SybaseCustomSQLTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/custom/sybase/SybaseCustomSQLTest.java @@ -6,8 +6,8 @@ import org.hibernate.dialect.SybaseDialect; import org.hibernate.orm.test.sql.hand.custom.CustomStoredProcTestSupport; - -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.RequiresDialect; /** * Custom SQL tests for Sybase dialects @@ -15,8 +15,8 @@ * @author Gavin King */ @RequiresDialect(SybaseDialect.class) +@DomainModel( + xmlMappings = "org/hibernate/orm/test/sql/hand/custom/sybase/Mappings.hbm.xml" +) public class SybaseCustomSQLTest extends CustomStoredProcTestSupport { - public String[] getMappings() { - return new String[] { "sql/hand/custom/sybase/Mappings.hbm.xml" }; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/identity/CustomInsertSQLWithIdentityColumnTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/identity/CustomInsertSQLWithIdentityColumnTest.java index 47ee73591ee7..714ae8aaaa45 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/identity/CustomInsertSQLWithIdentityColumnTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/identity/CustomInsertSQLWithIdentityColumnTest.java @@ -4,50 +4,42 @@ */ package org.hibernate.orm.test.sql.hand.identity; -import org.junit.Test; import org.hibernate.JDBCException; -import org.hibernate.Session; import org.hibernate.orm.test.sql.hand.Organization; -import org.hibernate.testing.DialectChecks; -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.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.jupiter.api.Assertions.assertThrows; -import static org.junit.Assert.fail; /** * Custom SQL tests for combined usage of custom insert SQL and identity columns * * @author Gail Badner */ -@RequiresDialectFeature( DialectChecks.SupportsIdentityColumns.class ) -public class CustomInsertSQLWithIdentityColumnTest extends BaseCoreFunctionalTestCase { - - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } - - @Override - public String[] getMappings() { - return new String[] {"sql/hand/identity/Mappings.hbm.xml"}; - } +@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsIdentityColumns.class) +@DomainModel( + xmlMappings = "org/hibernate/orm/test/sql/hand/identity/Mappings.hbm.xml" +) +@SessionFactory +public class CustomInsertSQLWithIdentityColumnTest { @Test - public void testBadInsertionFails() { - Session session = openSession(); - session.beginTransaction(); - Organization org = new Organization( "hola!" ); - try { - session.persist( org ); - session.remove( org ); - fail( "expecting bad custom insert statement to fail" ); - } - catch( JDBCException e ) { - // expected failure - } - - session.getTransaction().rollback(); - session.close(); + public void testBadInsertionFails(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Organization org = new Organization( "hola!" ); + // expecting bad custom insert statement to fail + assertThrows( JDBCException.class, () -> { + session.persist( org ); + session.remove( org ); + } ); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/quotedidentifiers/NativeSqlAndQuotedIdentifiersTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/quotedidentifiers/NativeSqlAndQuotedIdentifiersTest.java index 80ee202d2008..dbaabb56f0ac 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/quotedidentifiers/NativeSqlAndQuotedIdentifiersTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/quotedidentifiers/NativeSqlAndQuotedIdentifiersTest.java @@ -4,96 +4,86 @@ */ package org.hibernate.orm.test.sql.hand.quotedidentifiers; -import org.hibernate.Session; import org.hibernate.dialect.Dialect; import org.hibernate.query.NativeQuery; +import org.hibernate.testing.orm.junit.DialectFeatureCheck; +import org.hibernate.testing.orm.junit.DomainModel; +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.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.DialectCheck; -import org.hibernate.testing.RequiresDialectFeature; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; /** * Test of various situations with native-sql queries and quoted identifiers * * @author Steve Ebersole */ -@RequiresDialectFeature( value = NativeSqlAndQuotedIdentifiersTest.LocalDialectCheck.class ) -public class NativeSqlAndQuotedIdentifiersTest extends BaseCoreFunctionalTestCase { +@RequiresDialectFeature(feature = NativeSqlAndQuotedIdentifiersTest.LocalDialectCheck.class) +@DomainModel( + xmlMappings = "org/hibernate/orm/test/sql/hand/quotedidentifiers/Mappings.hbm.xml" +) +@SessionFactory +public class NativeSqlAndQuotedIdentifiersTest { - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } - - @Override - public String[] getMappings() { - return new String[] { "sql/hand/quotedidentifiers/Mappings.hbm.xml" }; - } + public static class LocalDialectCheck implements DialectFeatureCheck { - public static class LocalDialectCheck implements DialectCheck { @Override - public boolean isMatch(Dialect dialect) { + public boolean apply(Dialect dialect) { return '\"' == dialect.openQuote(); } } - @Override - protected void prepareTest() throws Exception { - if( sessionFactory()==null)return; - Session session = sessionFactory().openSession(); - session.beginTransaction(); - session.persist( new Person( "me" ) ); - session.getTransaction().commit(); - session.close(); + @BeforeAll + protected void prepareTest(SessionFactoryScope scope) throws Exception { + scope.inTransaction( + session -> + session.persist( new Person( "me" ) ) + ); } - @Override - protected void cleanupTest() throws Exception { - if( sessionFactory()==null)return; - Session session = sessionFactory().openSession(); - session.beginTransaction(); - session.createQuery( "delete Person" ).executeUpdate(); - session.getTransaction().commit(); - session.close(); + @AfterAll + protected void cleanupTest(SessionFactoryScope scope) throws Exception { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Test - public void testCompleteScalarDiscovery() { - Session session = openSession(); - session.beginTransaction(); - session.getNamedQuery( "query-person" ).list(); - session.getTransaction().commit(); - session.close(); + public void testCompleteScalarDiscovery(SessionFactoryScope scope) { + scope.inTransaction( + session -> + session.getNamedQuery( "query-person" ).list() + ); } @Test - public void testPartialScalarDiscovery() { - Session session = openSession(); - session.beginTransaction(); - NativeQuery query = session.getNamedNativeQuery( "query-person", "person-scalar" ); - query.list(); - session.getTransaction().commit(); - session.close(); + public void testPartialScalarDiscovery(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + NativeQuery query = session.getNamedNativeQuery( "query-person", "person-scalar" ); + query.list(); + } + ); } @Test - public void testBasicEntityMapping() { - Session session = openSession(); - session.beginTransaction(); - NativeQuery query = session.getNamedNativeQuery( "query-person", "person-entity-basic" ); - query.list(); - session.getTransaction().commit(); - session.close(); + public void testBasicEntityMapping(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + NativeQuery query = session.getNamedNativeQuery( "query-person", "person-entity-basic" ); + query.list(); + } + ); } @Test - public void testExpandedEntityMapping() { - Session session = openSession(); - session.beginTransaction(); - NativeQuery query = session.getNamedNativeQuery( "query-person", "person-entity-expanded" ); - query.list(); - session.getTransaction().commit(); - session.close(); + public void testExpandedEntityMapping(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + NativeQuery query = session.getNamedNativeQuery( "query-person", "person-entity-expanded" ); + query.list(); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/refcursor/CursorFromCallableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/refcursor/CursorFromCallableTest.java index b944e6c5d012..50aa1e0a87d6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/refcursor/CursorFromCallableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/refcursor/CursorFromCallableTest.java @@ -4,13 +4,6 @@ */ package org.hibernate.orm.test.sql.refcursor; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.util.Arrays; -import java.util.List; - -import org.hibernate.Session; import org.hibernate.dialect.OracleDialect; import org.hibernate.engine.jdbc.spi.JdbcCoordinator; import org.hibernate.engine.jdbc.spi.ResultSetReturn; @@ -18,118 +11,122 @@ import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.jdbc.Work; import org.hibernate.procedure.ProcedureCall; - -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.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; /** * @author Lukasz Antoniak */ -@RequiresDialect( OracleDialect.class ) -public class CursorFromCallableTest extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { NumValue.class }; - } +@RequiresDialect(OracleDialect.class) +@DomainModel( + annotatedClasses = { + NumValue.class + } +) +@SessionFactory +public class CursorFromCallableTest { - @Before - public void createRefCursorFunction() { + @BeforeAll + public void createRefCursorFunction(SessionFactoryScope scope) { executeStatement( "CREATE OR REPLACE FUNCTION f_test_return_cursor RETURN SYS_REFCURSOR " + - "IS " + - " l_Cursor SYS_REFCURSOR; " + - "BEGIN " + - " OPEN l_Cursor FOR " + - " SELECT 1 AS BOT_NUM " + - " , 'Line 1' AS BOT_VALUE " + - " FROM DUAL " + - " UNION " + - " SELECT 2 AS BOT_NUM " + - " , 'Line 2' AS BOT_VALUE " + - " FROM DUAL; " + - " RETURN(l_Cursor); " + - "END f_test_return_cursor;" ); + "IS " + + " l_Cursor SYS_REFCURSOR; " + + "BEGIN " + + " OPEN l_Cursor FOR " + + " SELECT 1 AS BOT_NUM " + + " , 'Line 1' AS BOT_VALUE " + + " FROM DUAL " + + " UNION " + + " SELECT 2 AS BOT_NUM " + + " , 'Line 2' AS BOT_VALUE " + + " FROM DUAL; " + + " RETURN(l_Cursor); " + + "END f_test_return_cursor;" + , + scope ); } - @After - public void dropRefCursorFunction() { - executeStatement( "DROP FUNCTION f_test_return_cursor" ); + @AfterAll + public void dropRefCursorFunction(SessionFactoryScope scope) { + executeStatement( "DROP FUNCTION f_test_return_cursor", scope ); } @Test - @JiraKey( value = "HHH-8022" ) - public void testReadResultSetFromRefCursor() { - Session session = openSession(); - session.getTransaction().begin(); - - Assert.assertEquals( - Arrays.asList( new NumValue( 1, "Line 1" ), new NumValue( 2, "Line 2" ) ), - session.createNamedStoredProcedureQuery( "NumValue.getSomeValues" ).getResultList() + @JiraKey(value = "HHH-8022") + public void testReadResultSetFromRefCursor(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + assertThat( session.createNamedStoredProcedureQuery( "NumValue.getSomeValues" ).getResultList() ) + .isEqualTo( Arrays.asList( new NumValue( 1, "Line 1" ), new NumValue( 2, "Line 2" ) ) ); + } ); - - session.getTransaction().commit(); - session.close(); } @Test - @JiraKey( value = "HHH-7984" ) - public void testStatementClosing() { - Session session = openSession(); - session.getTransaction().begin(); - // Reading maximum number of opened cursors requires SYS privileges. - // Verify statement closing with JdbcCoordinator#hasRegisteredResources() instead. - // BigDecimal maxCursors = (BigDecimal) session.createSQLQuery( "SELECT value FROM v$parameter WHERE name = 'open_cursors'" ).uniqueResult(); - // for ( int i = 0; i < maxCursors + 10; ++i ) { named_query_execution } - ProcedureCall namedStoredProcedureQuery = session.createNamedStoredProcedureQuery( "NumValue.getSomeValues" ); - List resultList = namedStoredProcedureQuery.getResultList(); - Assert.assertEquals( - Arrays.asList( new NumValue( 1, "Line 1" ), new NumValue( 2, "Line 2" ) ), - resultList - ); - namedStoredProcedureQuery.close(); - JdbcCoordinator jdbcCoordinator = ( (SessionImplementor) session ).getJdbcCoordinator(); - Assert.assertFalse( - "Prepared statement and result set should be released after query execution.", - jdbcCoordinator.getLogicalConnection().getResourceRegistry().hasRegisteredResources() + @JiraKey(value = "HHH-7984") + public void testStatementClosing(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + // Reading maximum number of opened cursors requires SYS privileges. + // Verify statement closing with JdbcCoordinator#hasRegisteredResources() instead. + // BigDecimal maxCursors = (BigDecimal) session.createSQLQuery( "SELECT value FROM v$parameter WHERE name = 'open_cursors'" ).uniqueResult(); + // for ( int i = 0; i < maxCursors + 10; ++i ) { named_query_execution } + ProcedureCall namedStoredProcedureQuery = session.createNamedStoredProcedureQuery( + "NumValue.getSomeValues" ); + List resultList = namedStoredProcedureQuery.getResultList(); + assertThat( resultList ) + .isEqualTo( Arrays.asList( new NumValue( 1, "Line 1" ), new NumValue( 2, "Line 2" ) ) ); + namedStoredProcedureQuery.close(); + JdbcCoordinator jdbcCoordinator = ((SessionImplementor) session).getJdbcCoordinator(); + assertThat( jdbcCoordinator.getLogicalConnection().getResourceRegistry().hasRegisteredResources() ) + .describedAs("Prepared statement and result set should be released after query execution." ) + .isFalse(); + } ); - - session.getTransaction().commit(); - session.close(); } - private void executeStatement(final String sql) { - final Session session = openSession(); - session.getTransaction().begin(); - - session.doWork( new Work() { - @Override - public void execute(Connection connection) throws SQLException { - final JdbcCoordinator jdbcCoordinator = ( (SessionImplementor) session ).getJdbcCoordinator(); - final StatementPreparer statementPreparer = jdbcCoordinator.getStatementPreparer(); - final ResultSetReturn resultSetReturn = jdbcCoordinator.getResultSetReturn(); - PreparedStatement preparedStatement = null; - try { - preparedStatement = statementPreparer.prepareStatement( sql ); - resultSetReturn.execute( preparedStatement, sql ); - } - finally { - if ( preparedStatement != null ) { - try { - jdbcCoordinator.getLogicalConnection().getResourceRegistry().release( preparedStatement ); + private void executeStatement(final String sql, SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.doWork( new Work() { + @Override + public void execute(Connection connection) throws SQLException { + final JdbcCoordinator jdbcCoordinator = ((SessionImplementor) session).getJdbcCoordinator(); + final StatementPreparer statementPreparer = jdbcCoordinator.getStatementPreparer(); + final ResultSetReturn resultSetReturn = jdbcCoordinator.getResultSetReturn(); + PreparedStatement preparedStatement = null; + try { + preparedStatement = statementPreparer.prepareStatement( sql ); + resultSetReturn.execute( preparedStatement, sql ); + } + finally { + if ( preparedStatement != null ) { + try { + jdbcCoordinator.getLogicalConnection().getResourceRegistry() + .release( preparedStatement ); + } + catch (Throwable ignore) { + // ignore... + } + } + } } - catch ( Throwable ignore ) { - // ignore... - } - } + } ); } - } - } ); - - session.getTransaction().commit(); - session.close(); + ); } } diff --git a/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/BaseSessionFactoryFunctionalTest.java b/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/BaseSessionFactoryFunctionalTest.java index 33bcef603a02..b04d1d058422 100644 --- a/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/BaseSessionFactoryFunctionalTest.java +++ b/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/BaseSessionFactoryFunctionalTest.java @@ -349,4 +349,53 @@ public static void doInHibernateSessionBuilder( } } + /** + * Execute function in a Hibernate transaction without return value + * + * @param sessionBuilderSupplier SessionFactory supplier + * @param function function + */ + public static T doInHibernateSessionBuilder( + Supplier sessionBuilderSupplier, + TransactionUtil.HibernateTransactionFunction function) { + Session session = null; + Transaction txn = null; + try { + session = sessionBuilderSupplier.get().openSession(); + function.beforeTransactionCompletion(); + txn = session.beginTransaction(); + + T result = function.apply( session ); + if ( !txn.getRollbackOnly() ) { + txn.commit(); + } + else { + try { + txn.rollback(); + } + catch (Exception e) { + log.error( "Rollback failure", e ); + } + } + return result; + } + catch ( Throwable t ) { + if ( txn != null && txn.isActive() ) { + try { + txn.rollback(); + } + catch (Exception e) { + log.error( "Rollback failure", e ); + } + } + throw t; + } + finally { + function.afterTransactionCompletion(); + if ( session != null ) { + session.close(); + } + } + } + } diff --git a/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/DomainModelExtension.java b/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/DomainModelExtension.java index 634847d3495d..2072b49442e3 100644 --- a/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/DomainModelExtension.java +++ b/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/DomainModelExtension.java @@ -203,6 +203,9 @@ private static DomainModelScope createDomainModelScope( try { final DomainModelDescriptor modelDescriptor = modelDescriptorClass.newInstance(); modelDescriptor.applyDomainModel( metadataSources ); + for ( Class annotatedClass : modelDescriptor.getAnnotatedClasses() ) { + metadataSources.addAnnotatedClass( annotatedClass ); + } } catch (IllegalAccessException | InstantiationException e) { throw new RuntimeException( "Error instantiating DomainModelDescriptor - " + modelDescriptorClass.getName(), e ); diff --git a/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/EntityManagerFactoryBasedFunctionalTest.java b/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/EntityManagerFactoryBasedFunctionalTest.java index 3f885e22e8ad..06b297ab7603 100644 --- a/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/EntityManagerFactoryBasedFunctionalTest.java +++ b/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/EntityManagerFactoryBasedFunctionalTest.java @@ -27,6 +27,7 @@ import org.hibernate.query.sqm.mutation.internal.temptable.PersistentTableStrategy; import org.hibernate.testing.util.ServiceRegistryUtil; +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import jakarta.persistence.EntityManager; @@ -112,6 +113,19 @@ protected Map buildSettings() { return settings; } + @AfterAll + public void afterAll() { + if ( entityManagerFactoryScope != null ) { + try { + entityManagerFactoryScope.close(); + } + catch (Exception e) { + throw new RuntimeException( e ); + } + } + } + + protected Map getConfig() { Map config = Environment.getProperties(); ArrayList> classes = new ArrayList<>(); diff --git a/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/EntityManagerFactoryScope.java b/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/EntityManagerFactoryScope.java index 759d8496a426..5c65274be6d9 100644 --- a/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/EntityManagerFactoryScope.java +++ b/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/EntityManagerFactoryScope.java @@ -18,7 +18,7 @@ /** * @author Steve Ebersole */ -public interface EntityManagerFactoryScope { +public interface EntityManagerFactoryScope extends AutoCloseable { EntityManagerFactory getEntityManagerFactory(); void releaseEntityManagerFactory(); diff --git a/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/Jpa.java b/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/Jpa.java index c8681ce2864c..6ce48c0303f5 100644 --- a/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/Jpa.java +++ b/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/Jpa.java @@ -45,6 +45,8 @@ */ Setting[] integrationSettings() default {}; + SettingProvider[] integrationSettingProviders() default {}; + // todo : multiple persistence units? /** diff --git a/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/ServiceRegistryScope.java b/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/ServiceRegistryScope.java index 90caaaa14fc2..b51cc1b99659 100644 --- a/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/ServiceRegistryScope.java +++ b/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/ServiceRegistryScope.java @@ -59,7 +59,6 @@ default HibernatePersistenceConfiguration createPersistenceConfiguration(String final ConfigurationService configurationService = registry.requireService( ConfigurationService.class ); configuration.properties( configurationService.getSettings() ); - return configuration; } 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..13b3338a960b 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 @@ -145,9 +145,7 @@ else if ( ! explicitInspectorClass.equals( StatementInspector.class ) ) { sessionFactoryBuilder.applyStatementInspector( explicitInspectorClass.getConstructor().newInstance() ); } sessionFactoryBuilder.applyCollectionsInDefaultFetchGroup( sessionFactoryConfig.applyCollectionsInDefaultFetchGroup() ); - final SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) sessionFactoryBuilder.build(); - if ( sessionFactoryConfig.exportSchema() ) { prepareSchemaExport( sessionFactory, model, sessionFactoryConfig.createSecondarySchemas() ); }