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..c4f38e010e0b 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,38 @@ */ 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); - SessionFactory sf = null; + configuration.addAnnotatedClass( Month.class ); + SessionFactory sf; try { sf = configuration.buildSessionFactory(); sf.close(); } catch (ConcurrentModificationException e) { - fail(e.toString()); + fail( e.toString() ); } } } 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..c68d867865a8 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() ); + public void testTableIndex(SessionFactoryScope scope) { + PersistentClass entity = scope.getMetadataImplementor().getEntityBinding( Car.class.getName() ); Iterator itr = entity.getTable().getUniqueKeys().values().iterator(); - assertTrue( itr.hasNext() ); + assertThat( itr.hasNext() ).isTrue(); 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() ); + 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() ); 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() ); + assertThat( itr.hasNext() ).isTrue(); + Index index = (Index) itr.next(); + assertThat( itr.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/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..e13a14fb1e2b 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.AfterAll; +import org.junit.jupiter.api.BeforeAll; +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 + @BeforeAll public void setUp() { serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry( Environment.getProperties() ); } - @After + @AfterAll 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..e3504a25a766 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 { 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/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..ac6a983b3e31 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,65 @@ */ 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 org.hibernate.testing.RequiresDialect; -import org.junit.Test; +import java.util.List; +import java.util.Map; + +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..94d0b5da2687 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 @@ -36,14 +36,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-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/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 ce584a3dc1f2..f323d10308e9 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() ); }