diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoone/ManyToOneMapsIdFlushModeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoone/ManyToOneMapsIdFlushModeTest.java index 12c5f1bafdbc..73c8bb7f6897 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoone/ManyToOneMapsIdFlushModeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoone/ManyToOneMapsIdFlushModeTest.java @@ -4,9 +4,6 @@ */ package org.hibernate.orm.test.annotations.manytoone; -import java.util.HashSet; -import java.util.Set; - import jakarta.persistence.Entity; import jakarta.persistence.FlushModeType; import jakarta.persistence.GeneratedValue; @@ -15,56 +12,53 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.MapsId; import jakarta.persistence.OneToMany; - -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; - -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.transaction.TransactionUtil; +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.Assertions; +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 java.util.HashSet; +import java.util.Set; /** * @author Chris Cranford */ +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey(value = "HHH-13044") -@RequiresDialectFeature(DialectChecks.SupportsIdentityColumns.class) -public class ManyToOneMapsIdFlushModeTest extends BaseEntityManagerFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { ParentEntity.class, ChildEntity.class }; - } - +@RequiresDialectFeature(feature= DialectFeatureChecks.SupportsIdentityColumns.class) +@DomainModel(annotatedClasses = { ManyToOneMapsIdFlushModeTest.ParentEntity.class, ManyToOneMapsIdFlushModeTest.ChildEntity.class }) +@SessionFactory +public class ManyToOneMapsIdFlushModeTest { @Test - public void testFlushModeCommitWithMapsIdAndIdentity() { - final ParentEntity parent = TransactionUtil.doInJPA( this::entityManagerFactory, entityManager -> { - entityManager.setFlushMode( FlushModeType.COMMIT ); + public void testFlushModeCommitWithMapsIdAndIdentity(SessionFactoryScope factoryScope) { + final ParentEntity parent = factoryScope.fromTransaction( (session) -> { + session.setFlushMode( FlushModeType.COMMIT ); - final ParentEntity parentEntity = new ParentEntity(); + var parentEntity = new ParentEntity(); parentEntity.setData( "test" ); - final ChildEntity childEntity = new ChildEntity(); + var childEntity = new ChildEntity(); parentEntity.addChild( childEntity ); - entityManager.persist( parentEntity ); - entityManager.persist( childEntity ); + session.persist( parentEntity ); + session.persist( childEntity ); return parentEntity; } ); - TransactionUtil.doInJPA( this::entityManagerFactory, entityManager -> { - final ParentEntity parentEntity = entityManager.find( ParentEntity.class, parent.getId() ); - assertNotNull( parentEntity ); - assertNotNull( parentEntity.getChildren() ); - assertTrue( !parentEntity.getChildren().isEmpty() ); + factoryScope.inTransaction( (session) -> { + final ParentEntity parentEntity = session.find( ParentEntity.class, parent.getId() ); + Assertions.assertNotNull( parentEntity ); + Assertions.assertNotNull( parentEntity.getChildren() ); + Assertions.assertFalse( parentEntity.getChildren().isEmpty() ); final ChildEntity childEntity = parentEntity.getChildren().iterator().next(); - assertNotNull( childEntity ); - assertEquals( parentEntity.getId(), childEntity.getId() ); + Assertions.assertNotNull( childEntity ); + Assertions.assertEquals( parentEntity.getId(), childEntity.getId() ); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoone/ManyToOneTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoone/ManyToOneTest.java index 307e34787105..5f5d7e2e9425 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoone/ManyToOneTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoone/ManyToOneTest.java @@ -4,384 +4,330 @@ */ package org.hibernate.orm.test.annotations.manytoone; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - import org.hibernate.Hibernate; -import org.hibernate.query.Query; -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.hibernate.orm.test.annotations.Company; import org.hibernate.orm.test.annotations.Customer; import org.hibernate.orm.test.annotations.Discount; import org.hibernate.orm.test.annotations.Flight; import org.hibernate.orm.test.annotations.Passport; import org.hibernate.orm.test.annotations.Ticket; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; -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.hibernate.cfg.MappingSettings.IMPLICIT_NAMING_STRATEGY; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Emmanuel Bernard */ -public class ManyToOneTest extends BaseCoreFunctionalTestCase { - @Test - public void testEager() { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - Color c = new Color(); - c.setName( "Yellow" ); - s.persist( c ); - Car car = new Car(); - car.setBodyColor( c ); - s.persist( car ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - car = s.get( Car.class, car.getId() ); - tx.commit(); - s.close(); - assertNotNull( car ); - assertNotNull( car.getBodyColor() ); - assertEquals( "Yellow", car.getBodyColor().getName() ); +@SuppressWarnings("JUnitMalformedDeclaration") +@ServiceRegistry( settings = @Setting( name = IMPLICIT_NAMING_STRATEGY, value = "legacy-jpa" ) ) +@DomainModel(annotatedClasses = { + Deal.class, + org.hibernate.orm.test.annotations.manytoone.Customer.class, + Car.class, + Color.class, + Flight.class, + Company.class, + Customer.class, + Discount.class, + Ticket.class, + Passport.class, + Parent.class, + Child.class, + Node.class, + User.class, + DistrictUser.class, + Order.class, + OrderLine.class, + Frame.class, + Lens.class +} ) +@SessionFactory +public class ManyToOneTest { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test - public void testDefaultMetadata() { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - Color c = new Color(); - c.setName( "Blue" ); - s.persist( c ); - Car car = new Car(); - car.setBodyColor( c ); - s.persist( car ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - car = s.get( Car.class, car.getId() ); - assertNotNull( car ); - assertNotNull( car.getBodyColor() ); - assertEquals( c.getId(), car.getBodyColor().getId() ); - tx.rollback(); - s.close(); + public void testEager(SessionFactoryScope factoryScope) { + var carId = factoryScope.fromTransaction( (session) -> { + var color = new Color(); + color.setName( "Yellow" ); + session.persist( color ); + var car = new Car(); + car.setBodyColor( color ); + session.persist( car ); + return car.getId(); + } ); + + factoryScope.inTransaction( (session) -> { + var car = session.find( Car.class, carId ); + assertNotNull( car ); + assertNotNull( car.getBodyColor() ); + assertEquals( "Yellow", car.getBodyColor().getName() ); + } ); } @Test - public void testCreate() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - Flight firstOne = new Flight(); - firstOne.setId(1L); - firstOne.setName( "AF0101" ); - firstOne.setDuration(1000L); - Company frenchOne = new Company(); - frenchOne.setName( "Air France" ); - firstOne.setCompany( frenchOne ); - s.persist( firstOne ); - tx.commit(); - s.close(); - assertNotNull( "identity id should work", frenchOne.getId() ); - - s = openSession(); - tx = s.beginTransaction(); - firstOne = s.get( Flight.class, 1L); - assertNotNull( firstOne.getCompany() ); - assertEquals( frenchOne.getName(), firstOne.getCompany().getName() ); - tx.commit(); - s.close(); + public void testDefaultMetadata(SessionFactoryScope factoryScope) { + var carId = factoryScope.fromTransaction( (session) -> { + var color = new Color(); + color.setName( "Blue" ); + session.persist( color ); + var car = new Car(); + car.setBodyColor( color ); + session.persist( car ); + return car.getId(); + } ); + + factoryScope.inTransaction( (session) -> { + var car = session.find( Car.class, carId ); + assertNotNull( car ); + assertNotNull( car.getBodyColor() ); + assertEquals( "Blue", car.getBodyColor().getName() ); + } ); } @Test - public void testCascade() { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - Discount discount = new Discount(); - discount.setDiscount( 20.12 ); - Customer customer = new Customer(); - Collection discounts = new ArrayList<>(); - discounts.add( discount ); - customer.setName( "Quentin Tarantino" ); - discount.setOwner( customer ); - customer.setDiscountTickets( discounts ); - s.persist( discount ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - discount = s.get( Discount.class, discount.getId() ); - assertNotNull( discount ); - assertEquals( 20.12, discount.getDiscount(), 0.01 ); - assertNotNull( discount.getOwner() ); - customer = new Customer(); - customer.setName( "Clooney" ); - discount.setOwner( customer ); - discounts = new ArrayList<>(); - discounts.add( discount ); - customer.setDiscountTickets( discounts ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - discount = s.get( Discount.class, discount.getId() ); - assertNotNull( discount ); - assertNotNull( discount.getOwner() ); - assertEquals( "Clooney", discount.getOwner().getName() ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - customer = s.get( Customer.class, customer.getId() ); - s.remove( customer ); - tx.commit(); - s.close(); + public void testCreate(SessionFactoryScope factoryScope) throws Exception { + factoryScope.inTransaction( (session) -> { + Flight firstOne = new Flight(); + firstOne.setId(1L); + firstOne.setName( "AF0101" ); + firstOne.setDuration(1000L); + Company frenchOne = new Company(); + frenchOne.setName( "Air France" ); + firstOne.setCompany( frenchOne ); + + session.persist( firstOne ); + session.persist( frenchOne ); + } ); + + factoryScope.inTransaction( (session) -> { + var flight = session.find( Flight.class, 1L ); + assertNotNull( flight.getCompany() ); + assertEquals( "Air France", flight.getCompany().getName() ); + } ); } @Test - public void testFetch() { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - Discount discount = new Discount(); - discount.setDiscount( 20 ); - Customer customer = new Customer(); - Collection discounts = new ArrayList<>(); - discounts.add( discount ); - customer.setName( "Quentin Tarantino" ); - discount.setOwner( customer ); - customer.setDiscountTickets( discounts ); - s.persist( discount ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - discount = s.get( Discount.class, discount.getId() ); - assertNotNull( discount ); - assertFalse( Hibernate.isInitialized( discount.getOwner() ) ); - tx.commit(); - - s = openSession(); - tx = s.beginTransaction(); - discount = s.getReference( Discount.class, discount.getId() ); - assertNotNull( discount ); - assertFalse( Hibernate.isInitialized( discount.getOwner() ) ); - tx.commit(); - - s = openSession(); - tx = s.beginTransaction(); - s.remove( s.get( Discount.class, discount.getId() ) ); - tx.commit(); - s.close(); + public void testCascade(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + var discount = new Discount(); + discount.setDiscount( 20.12 ); + var customer = new Customer(); + var discounts = new ArrayList<>(); + discounts.add( discount ); + customer.setName( "Quentin Tarantino" ); + discount.setOwner( customer ); + customer.setDiscountTickets( discounts ); + session.persist( discount ); + } ); + + factoryScope.inTransaction( (session) -> { + var discount = session.find( Discount.class, 1L ); + assertNotNull( discount ); + assertEquals( 20.12, discount.getDiscount(), 0.01 ); + assertNotNull( discount.getOwner() ); + var customer = new Customer(); + customer.setName( "Clooney" ); + discount.setOwner( customer ); + var discounts = new ArrayList<>(); + discounts.add( discount ); + customer.setDiscountTickets( discounts ); + } ); + + factoryScope.inTransaction( (session) -> { + var discount = session.find( Discount.class, 1L ); + assertNotNull( discount ); + assertNotNull( discount.getOwner() ); + assertEquals( "Clooney", discount.getOwner().getName() ); + } ); } @Test - public void testCompositeFK() { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - ParentPk ppk = new ParentPk(); - ppk.firstName = "John"; - ppk.lastName = "Doe"; - Parent p = new Parent(); - p.age = 45; - p.id = ppk; - s.persist( p ); - Child c = new Child(); - c.parent = p; - s.persist( c ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - //FIXME: fix this when the small parser bug will be fixed - Query q = s.createQuery( "from " + Child.class.getName() ); //+ " c where c.parent.id.lastName = :lastName"); - //q.setString("lastName", p.id.lastName); - List result = q.list(); - assertEquals( 1, result.size() ); - Child c2 = (Child) result.get( 0 ); - assertEquals( c2.id, c.id ); - tx.commit(); - s.close(); + public void testFetch(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + var discount = new Discount(); + discount.setDiscount( 20 ); + var customer = new Customer(); + var discounts = new ArrayList<>(); + discounts.add( discount ); + customer.setName( "Quentin Tarantino" ); + discount.setOwner( customer ); + customer.setDiscountTickets( discounts ); + session.persist( discount ); + } ); + + factoryScope.inTransaction( (session) -> { + var discount = session.find( Discount.class, 1L ); + assertNotNull( discount ); + assertFalse( Hibernate.isInitialized( discount.getOwner() ) ); + } ); + + factoryScope.inTransaction( (session) -> { + var discount = session.getReference( Discount.class, 1L ); + assertNotNull( discount ); + assertFalse( Hibernate.isInitialized( discount.getOwner() ) ); + } ); } @Test - public void testImplicitCompositeFk() { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - Node n1 = new Node(); - n1.setDescription( "Parent" ); - NodePk n1pk = new NodePk(); - n1pk.setLevel( 1 ); - n1pk.setName( "Root" ); - n1.setId( n1pk ); - Node n2 = new Node(); - NodePk n2pk = new NodePk(); - n2pk.setLevel( 2 ); - n2pk.setName( "Level 1: A" ); - n2.setParent( n1 ); - n2.setId( n2pk ); - s.persist( n2 ); - tx.commit(); - - s = openSession(); - tx = s.beginTransaction(); - n2 = s.get( Node.class, n2pk ); - assertNotNull( n2 ); - assertNotNull( n2.getParent() ); - assertEquals( 1, n2.getParent().getId().getLevel() ); - tx.commit(); - s.close(); + public void testCompositeFK(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + var ppk = new ParentPk(); + ppk.firstName = "John"; + ppk.lastName = "Doe"; + var p = new Parent(); + p.age = 45; + p.id = ppk; + session.persist( p ); + var c = new Child(); + c.parent = p; + session.persist( c ); + } ); + + factoryScope.inTransaction( (session) -> { + //FIXME: fix this when the small parser bug will be fixed + var result = session.createQuery( "from Child c where c.parent.id.lastName = :lastName" ) + .setParameter( "lastName", "Doe") + .list(); + assertEquals( 1, result.size() ); + Child c2 = (Child) result.get( 0 ); + assertEquals( 1, c2.id ); + } ); } @Test - public void testManyToOneNonPk() { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Order order = new Order(); - order.setOrderNbr( "123" ); - s.persist( order ); - OrderLine ol = new OrderLine(); - ol.setItem( "Mouse" ); - ol.setOrder( order ); - s.persist( ol ); - s.flush(); - s.clear(); - ol = s.get( OrderLine.class, ol.getId() ); - assertNotNull( ol.getOrder() ); - assertEquals( "123", ol.getOrder().getOrderNbr() ); - assertTrue( ol.getOrder().getOrderLines().contains( ol ) ); - tx.rollback(); - s.close(); + public void testImplicitCompositeFk(SessionFactoryScope factoryScope) { + var node2Pk = factoryScope.fromTransaction( (session) -> { + var n1 = new Node(); + n1.setDescription( "Parent" ); + var n1pk = new NodePk(); + n1pk.setLevel( 1 ); + n1pk.setName( "Root" ); + n1.setId( n1pk ); + + var n2 = new Node(); + var n2pk = new NodePk(); + n2pk.setLevel( 2 ); + n2pk.setName( "Level 1: A" ); + n2.setParent( n1 ); + n2.setId( n2pk ); + + session.persist( n2 ); + + return n2pk; + } ); + + factoryScope.inTransaction( (session) -> { + var n2 = session.find( Node.class, node2Pk ); + assertNotNull( n2 ); + assertNotNull( n2.getParent() ); + assertEquals( 1, n2.getParent().getId().getLevel() ); + } ); } @Test - public void testManyToOneNonPkSecondaryTable() { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Order order = new Order(); - order.setOrderNbr( "123" ); - s.persist( order ); - OrderLine ol = new OrderLine(); - ol.setItem( "Mouse" ); - ol.setReplacementOrder( order ); - s.persist( ol ); - s.flush(); - s.clear(); - ol = s.get( OrderLine.class, ol.getId() ); - assertNotNull( ol.getReplacementOrder() ); - assertEquals( "123", ol.getReplacementOrder().getOrderNbr() ); - assertFalse( ol.getReplacementOrder().getOrderLines().contains( ol ) ); - tx.rollback(); - s.close(); + public void testManyToOneNonPk(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + var order = new Order(); + order.setOrderNbr( "123" ); + session.persist( order ); + + var ol = new OrderLine(); + ol.setItem( "Mouse" ); + ol.setOrder( order ); + session.persist( ol ); + } ); + + factoryScope.inTransaction( (session) -> { + var ol = session.find( OrderLine.class, 1 ); + assertNotNull( ol.getOrder() ); + assertEquals( "123", ol.getOrder().getOrderNbr() ); + assertTrue( ol.getOrder().getOrderLines().contains( ol ) ); + } ); } @Test - public void testTwoManyToOneNonPk() { - //2 many to one non pk pointing to the same referencedColumnName should not fail - Session s = openSession(); - Transaction tx = s.beginTransaction(); - org.hibernate.orm.test.annotations.manytoone.Customer customer = new org.hibernate.orm.test.annotations.manytoone.Customer(); - customer.userId="123"; - org.hibernate.orm.test.annotations.manytoone.Customer customer2 = new org.hibernate.orm.test.annotations.manytoone.Customer(); - customer2.userId="124"; - s.persist( customer2 ); - s.persist( customer ); - Deal deal = new Deal(); - deal.from = customer; - deal.to = customer2; - s.persist( deal ); - s.flush(); - s.clear(); - deal = s.get( Deal.class, deal.id ); - assertNotNull( deal.from ); - assertNotNull( deal.to ); - tx.rollback(); - s.close(); + public void testManyToOneNonPkSecondaryTable(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + var order = new Order(); + order.setOrderNbr( "123" ); + session.persist( order ); + + var ol = new OrderLine(); + ol.setItem( "Mouse" ); + ol.setReplacementOrder( order ); + session.persist( ol ); + } ); + + factoryScope.inTransaction( (session) -> { + var ol = session.find( OrderLine.class, 1 ); + assertNotNull( ol.getReplacementOrder() ); + assertEquals( "123", ol.getReplacementOrder().getOrderNbr() ); + assertFalse( ol.getReplacementOrder().getOrderLines().contains( ol ) ); + } ); } @Test - public void testFormulaOnOtherSide() { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Frame frame = new Frame(); - frame.setName( "Prada" ); - s.persist( frame ); - Lens l = new Lens(); - l.setFocal( 2.5f ); - l.setFrame( frame ); - s.persist( l ); - Lens r = new Lens(); - r.setFocal( 1.2f); - r.setFrame( frame ); - s.persist( r ); - s.flush(); - s.clear(); - frame = s.get( Frame.class, frame.getId() ); - assertEquals( 2, frame.getLenses().size() ); - assertTrue( frame.getLenses().iterator().next().getLength() <= 1/1.2f ); - assertTrue( frame.getLenses().iterator().next().getLength() >= 1/2.5f ); - tx.rollback(); - s.close(); - } + public void testTwoManyToOneNonPk(SessionFactoryScope factoryScope) { + //2 many-to-one non pk pointing to the same referencedColumnName should not fail + factoryScope.inTransaction( (session) -> { + var customer = new org.hibernate.orm.test.annotations.manytoone.Customer(); + customer.userId="123"; + var customer2 = new org.hibernate.orm.test.annotations.manytoone.Customer(); + customer2.userId="124"; + session.persist( customer2 ); + session.persist( customer ); + var deal = new Deal(); + deal.from = customer; + deal.to = customer2; + session.persist( deal ); + } ); - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - configuration.setImplicitNamingStrategy( ImplicitNamingStrategyLegacyJpaImpl.INSTANCE ); + factoryScope.inTransaction( (session) -> { + var deal = session.find( Deal.class, 1 ); + assertNotNull( deal.from ); + assertNotNull( deal.to ); + } ); } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - Deal.class, - org.hibernate.orm.test.annotations.manytoone.Customer.class, - Car.class, - Color.class, - Flight.class, - Company.class, - Customer.class, - Discount.class, - Ticket.class, - Passport.class, - Parent.class, - Child.class, - Node.class, - User.class, - DistrictUser.class, - Order.class, - OrderLine.class, - Frame.class, - Lens.class - }; - } + @Test + public void testFormulaOnOtherSide(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + var frame = new Frame(); + frame.setName( "Prada" ); + session.persist( frame ); + var l = new Lens(); + l.setFocal( 2.5f ); + l.setFrame( frame ); + session.persist( l ); + + var r = new Lens(); + r.setFocal( 1.2f); + r.setFrame( frame ); + session.persist( r ); + } ); + + factoryScope.inTransaction( (session) -> { + var frame = session.find( Frame.class, 1L ); + assertEquals( 2, frame.getLenses().size() ); + assertTrue( frame.getLenses().iterator().next().getLength() <= 1 / 1.2f ); + assertTrue( frame.getLenses().iterator().next().getLength() >= 1 / 2.5f ); + } ); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoone/NotNullManyToOneTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoone/NotNullManyToOneTest.java index 7560022f28b6..a9b1633a0869 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoone/NotNullManyToOneTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoone/NotNullManyToOneTest.java @@ -4,16 +4,6 @@ */ package org.hibernate.orm.test.annotations.manytoone; -import org.hibernate.boot.beanvalidation.ValidationMode; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; - -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; - import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; @@ -21,45 +11,53 @@ import jakarta.persistence.Id; import jakarta.persistence.ManyToOne; import jakarta.validation.constraints.NotNull; +import org.hibernate.testing.orm.junit.DialectFeatureChecks; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.ExpectedException; +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.Setting; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import static org.hibernate.cfg.ValidationSettings.JAKARTA_VALIDATION_MODE; /** * @author Andrea Boriero */ +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey(value = "HHH-13959") -@RequiresDialectFeature(DialectChecks.SupportsIdentityColumns.class) -public class NotNullManyToOneTest extends BaseCoreFunctionalTestCase { - - @Override - protected void configure(Configuration configuration) { - configuration.setProperty( AvailableSettings.JAKARTA_VALIDATION_MODE, ValidationMode.AUTO ); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Parent.class, - Child.class - }; +@RequiresDialectFeature(feature= DialectFeatureChecks.SupportsIdentityColumns.class) +@ServiceRegistry(settings = @Setting(name = JAKARTA_VALIDATION_MODE, value = "auto" ) ) +@DomainModel(annotatedClasses = { + NotNullManyToOneTest.Parent.class, + NotNullManyToOneTest.Child.class +}) +@SessionFactory +public class NotNullManyToOneTest { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test - public void testSave() { - inTransaction( - session -> { - Parent parent = new Parent( new Child() ); - session.persist( parent ); - } - ); + public void testSave(SessionFactoryScope factoryScope) { + factoryScope.inTransaction(session -> { + Parent parent = new Parent( new Child() ); + session.persist( parent ); + } ); } - @Test(expected = jakarta.validation.ConstraintViolationException.class) - public void testSaveChildWithoutParent() { - inTransaction( - session -> { - Child child = new Child(); - session.persist( child ); - } - ); + @Test + @ExpectedException( jakarta.validation.ConstraintViolationException.class ) + public void testSaveChildWithoutParent(SessionFactoryScope factoryScope) { + factoryScope.inTransaction(session -> { + Child child = new Child(); + session.persist( child ); + } ); } @Entity(name = "Child") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoone/referencedcolumnname/ManyToOneReferencedColumnNameTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoone/referencedcolumnname/ManyToOneReferencedColumnNameTest.java index 6d903880aa8a..9b34f131e0df 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoone/referencedcolumnname/ManyToOneReferencedColumnNameTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoone/referencedcolumnname/ManyToOneReferencedColumnNameTest.java @@ -4,60 +4,57 @@ */ package org.hibernate.orm.test.annotations.manytoone.referencedcolumnname; -import java.math.BigDecimal; - -import org.hibernate.Session; -import org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl; -import org.hibernate.cfg.Configuration; +import org.hibernate.cfg.MappingSettings; +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.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import java.math.BigDecimal; /** * @author Emmanuel Bernard */ -public class ManyToOneReferencedColumnNameTest extends BaseCoreFunctionalTestCase { - @Test - @RequiresDialectFeature(DialectChecks.SupportsIdentityColumns.class) - public void testRecoverableExceptionInFkOrdering() throws Exception { - //SF should not blow up - Vendor v = new Vendor(); - Item i = new Item(); - ZItemCost ic = new ZItemCost(); - ic.setCost( new BigDecimal( 2 ) ); - ic.setItem( i ); - ic.setVendor( v ); - WarehouseItem wi = new WarehouseItem(); - wi.setDefaultCost( ic ); - wi.setItem( i ); - wi.setVendor( v ); - wi.setQtyInStock( new BigDecimal( 2 ) ); - Session s = openSession(); - s.getTransaction().begin(); - s.persist( i ); - s.persist( v ); - s.persist( ic ); - s.persist( wi ); - s.flush(); - s.getTransaction().rollback(); - s.close(); +@SuppressWarnings("JUnitMalformedDeclaration") +@RequiresDialectFeature(feature= DialectFeatureChecks.SupportsIdentityColumns.class) +@ServiceRegistry(settings = @Setting(name= MappingSettings.IMPLICIT_NAMING_STRATEGY, value = "legacy-jpa")) +@DomainModel(annotatedClasses = { + Item.class, + Vendor.class, + WarehouseItem.class, + ZItemCost.class +}) +@SessionFactory +public class ManyToOneReferencedColumnNameTest { + @AfterEach + void tearDown(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - configuration.setImplicitNamingStrategy( ImplicitNamingStrategyLegacyJpaImpl.INSTANCE ); - } + @Test + public void testRecoverableExceptionInFkOrdering(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + var v = new Vendor(); + var i = new Item(); + var ic = new ZItemCost(); + ic.setCost( new BigDecimal( 2 ) ); + ic.setItem( i ); + ic.setVendor( v ); + var wi = new WarehouseItem(); + wi.setDefaultCost( ic ); + wi.setItem( i ); + wi.setVendor( v ); + wi.setQtyInStock( new BigDecimal( 2 ) ); - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Item.class, - Vendor.class, - WarehouseItem.class, - ZItemCost.class - }; + session.persist( i ); + session.persist( v ); + session.persist( ic ); + session.persist( wi ); + } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/ByteArrayNaturalIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/ByteArrayNaturalIdTest.java index 853477d29e4b..9d1231edb930 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/ByteArrayNaturalIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/ByteArrayNaturalIdTest.java @@ -21,6 +21,7 @@ import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +@SuppressWarnings("JUnitMalformedDeclaration") @DomainModel( annotatedClasses = { ByteArrayNaturalIdTest.TestEntity.class, @@ -31,12 +32,11 @@ @SkipForDialect(dialectClass = InformixDialect.class, reason = "Blobs are not allowed in this expression (equality test with column of type BYTE)") public class ByteArrayNaturalIdTest { - private static final String NATURAL_ID_1 = "N1"; @AfterEach - public void tearDown(SessionFactoryScope scope) { - scope.getSessionFactory().getSchemaManager().truncate(); + public void dropTestData(SessionFactoryScope scope) { + scope.dropData(); } @Test diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/Citizen.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/Citizen.java index 2dc751dbe45e..1254fac4e0ce 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/Citizen.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/Citizen.java @@ -4,7 +4,6 @@ */ package org.hibernate.orm.test.annotations.naturalid; import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.ManyToOne; @@ -18,7 +17,6 @@ @NaturalIdCache public class Citizen { @Id - @GeneratedValue private Integer id; private String firstname; private String lastname; @@ -28,6 +26,16 @@ public class Citizen { @NaturalId private String ssn; + public Citizen() { + } + + public Citizen(Integer id, String firstname, String lastname, State state, String ssn) { + this.id = id; + this.firstname = firstname; + this.lastname = lastname; + this.state = state; + this.ssn = ssn; + } public Integer getId() { return id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/ImmutableNaturalKeyLookupTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/ImmutableNaturalKeyLookupTest.java index 0adeb94f223c..c1bcbc477388 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/ImmutableNaturalKeyLookupTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/ImmutableNaturalKeyLookupTest.java @@ -5,321 +5,262 @@ package org.hibernate.orm.test.annotations.naturalid; import jakarta.persistence.FlushModeType; -import jakarta.persistence.criteria.CriteriaBuilder; -import jakarta.persistence.criteria.CriteriaQuery; -import jakarta.persistence.criteria.Root; - -import org.junit.Assert; -import org.junit.Test; - import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.cfg.Configuration; -import org.hibernate.cfg.Environment; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.graph.GraphSemantic; import org.hibernate.graph.RootGraph; import org.hibernate.graph.spi.RootGraphImplementor; -import org.hibernate.query.Query; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import static org.hibernate.cfg.CacheSettings.USE_QUERY_CACHE; +import static org.hibernate.cfg.StatisticsSettings.GENERATE_STATISTICS; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Guenther Demetz */ -public class ImmutableNaturalKeyLookupTest extends BaseCoreFunctionalTestCase { +@SuppressWarnings("JUnitMalformedDeclaration") +@ServiceRegistry(settings = { + @Setting(name=GENERATE_STATISTICS, value="true"), + @Setting(name=USE_QUERY_CACHE, value="true") +}) +@DomainModel(annotatedClasses = {A.class, D.class}) +@SessionFactory +public class ImmutableNaturalKeyLookupTest { + @AfterEach + void tearDown(SessionFactoryScope factoryScope) { + factoryScope.dropData(); + } @JiraKey(value = "HHH-4838") @Test - public void testSimpleImmutableNaturalKeyLookup() { - Session s = openSession(); - Transaction newTx = s.getTransaction(); - - newTx.begin(); - A a1 = new A(); - a1.setName( "name1" ); - s.persist( a1 ); - newTx.commit(); - - newTx = s.beginTransaction(); - fetchA( s ); // put query-result into cache - A a2 = new A(); - a2.setName( "xxxxxx" ); - s.persist( a2 ); - newTx.commit(); // Invalidates space A in UpdateTimeStamps region - - //Create new session to avoid the session cache which can't be tracked - s.close(); - s = openSession(); - - newTx = s.beginTransaction(); - - Assert.assertTrue( s.getSessionFactory().getStatistics().isStatisticsEnabled() ); - s.getSessionFactory().getStatistics().clear(); - - fetchA( s ); // should produce a hit in StandardQuery cache region - - Assert.assertEquals( - "query is not considered as isImmutableNaturalKeyLookup, despite fullfilling all conditions", - 1, s.getSessionFactory().getStatistics().getNaturalIdCacheHitCount() - ); - - s.createQuery( "delete from A" ).executeUpdate(); - newTx.commit(); - // Shutting down the application - s.close(); + public void testSimpleImmutableNaturalKeyLookup(SessionFactoryScope factoryScope) { + assertTrue( factoryScope.getSessionFactory().getStatistics().isStatisticsEnabled() ); + + factoryScope.inTransaction( (s) -> { + A a1 = new A(); + a1.setName( "name1" ); + s.persist( a1 ); + } ); + + factoryScope.inTransaction( (s) -> { + // put query-result into cache + fetchA( s ); + + A a2 = new A(); + a2.setName( "xxxxxx" ); + s.persist( a2 ); + } ); + + factoryScope.getSessionFactory().getStatistics().clear(); + + factoryScope.inTransaction( (s) -> { + // should produce a hit in StandardQuery cache region + fetchA( s ); + + assertEquals( 1, s.getSessionFactory().getStatistics().getNaturalIdCacheHitCount(), + "query is not considered as isImmutableNaturalKeyLookup, despite fullfilling all conditions" ); + } ); } @JiraKey(value = "HHH-4838") @Test - public void testNaturalKeyLookupWithConstraint() { - Session s = openSession(); - Transaction newTx = s.getTransaction(); - - newTx.begin(); - A a1 = new A(); - a1.setName( "name1" ); - s.persist( a1 ); - newTx.commit(); - - newTx = s.beginTransaction(); - - CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); - CriteriaQuery criteria = criteriaBuilder.createQuery( A.class ); - Root root = criteria.from( A.class ); - criteria.where( criteriaBuilder.and( criteriaBuilder.equal( root.get( "name" ), "name1" ), criteriaBuilder.isNull( root.get( "singleD" ) )) ); - - Query query = session.createQuery( criteria ); - query.setFlushMode( FlushModeType.COMMIT ); - query.setCacheable( true ); - query.uniqueResult(); // put query-result into cache - - A a2 = new A(); - a2.setName( "xxxxxx" ); - s.persist( a2 ); - newTx.commit(); // Invalidates space A in UpdateTimeStamps region - - newTx = s.beginTransaction(); - - Assert.assertTrue( s.getSessionFactory().getStatistics().isStatisticsEnabled() ); - s.getSessionFactory().getStatistics().clear(); - - // should not produce a hit in StandardQuery cache region because there is a constraint - criteria = criteriaBuilder.createQuery( A.class ); - root = criteria.from( A.class ); - criteria.where( criteriaBuilder.and( criteriaBuilder.equal( root.get( "name" ), "name1" ), criteriaBuilder.isNull( root.get( "singleD" ) )) ); - - query = session.createQuery( criteria ); - query.setFlushMode( FlushModeType.COMMIT ); - query.setCacheable( true ); - query.uniqueResult(); - - Assert.assertEquals( 0, s.getSessionFactory().getStatistics().getQueryCacheHitCount() ); - - s.createQuery( "delete from A" ).executeUpdate(); - newTx.commit(); - // Shutting down the application - s.close(); + public void testNaturalKeyLookupWithConstraint(SessionFactoryScope factoryScope) { + assertTrue( factoryScope.getSessionFactory().getStatistics().isStatisticsEnabled() ); + + factoryScope.inTransaction( (s) -> { + A a1 = new A(); + a1.setName( "name1" ); + s.persist( a1 ); + } ); + + final var criteriaBuilder = factoryScope.getSessionFactory().getCriteriaBuilder(); + + factoryScope.inTransaction( (s) -> { + var criteria = criteriaBuilder.createQuery( A.class ); + var root = criteria.from( A.class ); + criteria.where( criteriaBuilder.and( criteriaBuilder.equal( root.get( "name" ), "name1" ), criteriaBuilder.isNull( root.get( "singleD" ) )) ); + + // put query-result into cache + s.createQuery( criteria ) + .setFlushMode( FlushModeType.COMMIT ) + .setCacheable( true ) + .uniqueResult(); + } ); + + factoryScope.inTransaction( (s) -> { + // Invalidates space A in UpdateTimeStamps region + A a2 = new A(); + a2.setName( "xxxxxx" ); + s.persist( a2 ); + } ); + + factoryScope.getSessionFactory().getStatistics().clear(); + + factoryScope.inTransaction( (s) -> { + // should not produce a hit in StandardQuery cache region because there is a constraint + + var criteria = criteriaBuilder.createQuery( A.class ); + var root = criteria.from( A.class ); + criteria.where( criteriaBuilder.and( criteriaBuilder.equal( root.get( "name" ), "name1" ), criteriaBuilder.isNull( root.get( "singleD" ) )) ); + + s.createQuery( criteria ) + .setFlushMode( FlushModeType.COMMIT ) + .setCacheable( true ) + .uniqueResult(); + + assertEquals( 0, s.getSessionFactory().getStatistics().getQueryCacheHitCount() ); + } ); } @JiraKey(value = "HHH-4838") @Test - public void testCriteriaWithFetchModeJoinCollection() { - Session s = openSession(); - Transaction newTx = s.getTransaction(); - - newTx.begin(); - A a1 = new A(); - a1.setName( "name1" ); - D d1 = new D(); - a1.getDs().add( d1 ); - d1.setA( a1 ); - s.persist( d1 ); - s.persist( a1 ); - newTx.commit(); - - newTx = s.beginTransaction(); - - fetchA( s, "ds" ); // put query-result into cache - - A a2 = new A(); - a2.setName( "xxxxxx" ); - s.persist( a2 ); - newTx.commit(); // Invalidates space A in UpdateTimeStamps region - - //Create new session to avoid the session cache which can't be tracked - s.close(); - s = openSession(); - - newTx = s.beginTransaction(); - - // please enable - // logger.standard-query-cache.name=org.hibernate.cache.StandardQueryCache - // logger.standard-query-cache.level=debug - // logger.update-timestamps-cache.name=org.hibernate.cache.UpdateTimestampsCache - // logger.update-timestamps-cache.level=debug - // to see that isUpToDate is called where not appropriated - - Assert.assertTrue( s.getSessionFactory().getStatistics().isStatisticsEnabled() ); - s.getSessionFactory().getStatistics().clear(); - - // should produce a hit in StandardQuery cache region - fetchA( s, "ds" ); - - Assert.assertEquals( - "query is not considered as isImmutableNaturalKeyLookup, despite fullfilling all conditions", - 1, s.getSessionFactory().getStatistics().getNaturalIdCacheHitCount() - ); - s.createQuery( "delete from D" ).executeUpdate(); - s.createQuery( "delete from A" ).executeUpdate(); - - newTx.commit(); - // Shutting down the application - s.close(); + public void testCriteriaWithFetchModeJoinCollection(SessionFactoryScope factoryScope) { + assertTrue( factoryScope.getSessionFactory().getStatistics().isStatisticsEnabled() ); + + factoryScope.inTransaction( (s) -> { + A a1 = new A(); + a1.setName( "name1" ); + D d1 = new D(); + a1.getDs().add( d1 ); + d1.setA( a1 ); + s.persist( d1 ); + s.persist( a1 ); + } ); + + factoryScope.inTransaction( (s) -> { + // put query-result into cache + fetchA( s, "ds" ); + + A a2 = new A(); + a2.setName( "xxxxxx" ); + // Invalidates space A in UpdateTimeStamps region + s.persist( a2 ); + } ); + + factoryScope.inTransaction( (s) -> { + s.getSessionFactory().getStatistics().clear(); + + // should produce a hit in StandardQuery cache region + fetchA( s, "ds" ); + + assertEquals( 1, s.getSessionFactory().getStatistics().getNaturalIdCacheHitCount(), + "query is not considered as isImmutableNaturalKeyLookup, despite fullfilling all conditions" ); + } ); } @JiraKey(value = "HHH-4838") @Test - public void testCriteriaWithFetchModeJoinOnetoOne() { - Session s = openSession(); - Transaction newTx = s.getTransaction(); - - newTx.begin(); - A a1 = new A(); - a1.setName( "name1" ); - D d1 = new D(); - a1.setSingleD( d1 ); - d1.setSingleA( a1 ); - s.persist( d1 ); - s.persist( a1 ); - newTx.commit(); - - newTx = s.beginTransaction(); - fetchA( s, "singleD" ); // put query-result into cache - - A a2 = new A(); - a2.setName( "xxxxxx" ); - s.persist( a2 ); - newTx.commit(); // Invalidates space A in UpdateTimeStamps region - - //Create new session to avoid the session cache which can't be tracked - s.close(); - s = openSession(); - - newTx = s.beginTransaction(); - - Assert.assertTrue( s.getSessionFactory().getStatistics().isStatisticsEnabled() ); - s.getSessionFactory().getStatistics().clear(); - - // should produce a hit in StandardQuery cache region - fetchA( s, "singleD" ); - - Assert.assertEquals( - "query is not considered as isImmutableNaturalKeyLookup, despite fullfilling all conditions", - 1, s.getSessionFactory().getStatistics().getNaturalIdCacheHitCount() - ); - s.createQuery( "delete from A" ).executeUpdate(); - s.createQuery( "delete from D" ).executeUpdate(); - - newTx.commit(); - // Shutting down the application - s.close(); + public void testCriteriaWithFetchModeJoinOneToOne(SessionFactoryScope factoryScope) { + assertTrue( factoryScope.getSessionFactory().getStatistics().isStatisticsEnabled() ); + + factoryScope.inTransaction( (s) -> { + A a1 = new A(); + a1.setName( "name1" ); + D d1 = new D(); + a1.setSingleD( d1 ); + d1.setSingleA( a1 ); + s.persist( d1 ); + s.persist( a1 ); + } ); + + factoryScope.inTransaction( (s) -> { + // put query-result into cache + fetchA( s, "singleD" ); + + // Invalidates space A in UpdateTimeStamps region + A a2 = new A(); + a2.setName( "xxxxxx" ); + s.persist( a2 ); + } ); + + factoryScope.inTransaction( (s) -> { + s.getSessionFactory().getStatistics().clear(); + + // should produce a hit in StandardQuery cache region + fetchA( s, "singleD" ); + + assertEquals( 1, s.getSessionFactory().getStatistics().getNaturalIdCacheHitCount(), + "query is not considered as isImmutableNaturalKeyLookup, despite fullfilling all conditions" ); + } ); } @JiraKey(value = "HHH-4838") @Test - public void testCriteriaWithAliasOneToOneJoin() { - Session s = openSession(); - Transaction newTx = s.getTransaction(); - - newTx.begin(); - A a1 = new A(); - a1.setName( "name1" ); - D d1 = new D(); - a1.setSingleD( d1 ); - d1.setSingleA( a1 ); - s.persist( d1 ); - s.persist( a1 ); - newTx.commit(); - - newTx = s.beginTransaction(); - fetchA( s, "singleD" ); // put query-result into cache - - A a2 = new A(); - a2.setName( "xxxxxx" ); - s.persist( a2 ); - newTx.commit(); // Invalidates space A in UpdateTimeStamps region - - newTx = s.beginTransaction(); - - // please enable - // logger.standard-query-cache.name=org.hibernate.cache.StandardQueryCache - // logger.standard-query-cache.level=debug - // logger.update-timestamps-cache.name=org.hibernate.cache.UpdateTimestampsCache - // logger.update-timestamps-cache.level=debug - // to see that isUpToDate is called where not appropriated - - Assert.assertTrue( s.getSessionFactory().getStatistics().isStatisticsEnabled() ); - s.getSessionFactory().getStatistics().clear(); - - // should not produce a hit in StandardQuery cache region because createAlias() creates a subcriteria - fetchA( s, "singleD" ); - - Assert.assertEquals( 0, s.getSessionFactory().getStatistics().getQueryCacheHitCount() ); - s.createQuery( "delete from A" ).executeUpdate(); - s.createQuery( "delete from D" ).executeUpdate(); - - newTx.commit(); - // Shutting down the application - s.close(); + public void testCriteriaWithAliasOneToOneJoin(SessionFactoryScope factoryScope) { + assertTrue( factoryScope.getSessionFactory().getStatistics().isStatisticsEnabled() ); + + factoryScope.inTransaction( (s) -> { + A a1 = new A(); + a1.setName( "name1" ); + D d1 = new D(); + a1.setSingleD( d1 ); + d1.setSingleA( a1 ); + s.persist( d1 ); + s.persist( a1 ); + } ); + + factoryScope.inTransaction( (s) -> { + // put query-result into cache + fetchA( s, "singleD" ); + + // Invalidates space A in UpdateTimeStamps region + A a2 = new A(); + a2.setName( "xxxxxx" ); + s.persist( a2 ); + } ); + + factoryScope.inTransaction( (s) -> { + s.getSessionFactory().getStatistics().clear(); + + // should not produce a hit in StandardQuery cache region because createAlias() creates a subcriteria + fetchA( s, "singleD" ); + + assertEquals( 0, s.getSessionFactory().getStatistics().getQueryCacheHitCount() ); + } ); } @JiraKey(value = "HHH-4838") @Test - public void testSubCriteriaOneToOneJoin() { - Session s = openSession(); - Transaction newTx = s.getTransaction(); - - newTx.begin(); - A a1 = new A(); - a1.setName( "name1" ); - D d1 = new D(); - a1.setSingleD( d1 ); - d1.setSingleA( a1 ); - s.persist( d1 ); - s.persist( a1 ); - newTx.commit(); - - newTx = s.beginTransaction(); - fetchA( s, "singleD" ); // put query-result into cache - - A a2 = new A(); - a2.setName( "xxxxxx" ); - s.persist( a2 ); - newTx.commit(); // Invalidates space A in UpdateTimeStamps region - - newTx = s.beginTransaction(); - - // please enable - // logger.standard-query-cache.name=org.hibernate.cache.StandardQueryCache - // logger.standard-query-cache.level=debug - // logger.update-timestamps-cache.name=org.hibernate.cache.UpdateTimestampsCache - // logger.update-timestamps-cache.level=debug - // to see that isUpToDate is called where not appropriated - - Assert.assertTrue( s.getSessionFactory().getStatistics().isStatisticsEnabled() ); - s.getSessionFactory().getStatistics().clear(); - - // should not produce a hit in StandardQuery cache region because createCriteria() creates a subcriteria - fetchA( s, "singleD" ); - - Assert.assertEquals( 0, s.getSessionFactory().getStatistics().getQueryCacheHitCount() ); - s.createQuery( "delete from A" ).executeUpdate(); - s.createQuery( "delete from D" ).executeUpdate(); - - newTx.commit(); - // Shutting down the application - s.close(); + public void testSubCriteriaOneToOneJoin(SessionFactoryScope factoryScope) { + assertTrue( factoryScope.getSessionFactory().getStatistics().isStatisticsEnabled() ); + + factoryScope.inTransaction( (s) -> { + A a1 = new A(); + a1.setName( "name1" ); + D d1 = new D(); + a1.setSingleD( d1 ); + d1.setSingleA( a1 ); + s.persist( d1 ); + s.persist( a1 ); + } ); + + factoryScope.inTransaction( (s) -> { + // put query-result into cache + fetchA( s, "singleD" ); + + // Invalidates space A in UpdateTimeStamps region + A a2 = new A(); + a2.setName( "xxxxxx" ); + s.persist( a2 ); + } ); + + factoryScope.inTransaction( (s) -> { + s.getSessionFactory().getStatistics().clear(); + + // should not produce a hit in StandardQuery cache region because createCriteria() creates a subcriteria + fetchA( s, "singleD" ); + + assertEquals( 0, s.getSessionFactory().getStatistics().getQueryCacheHitCount() ); + } ); } private A fetchA(Session s) { @@ -341,19 +282,5 @@ private A fetchA(Session s, String fetch) { return a; } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - A.class, - D.class - }; - } - - @Override - protected void configure(Configuration cfg) { - cfg.setProperty( Environment.GENERATE_STATISTICS, true ); - cfg.setProperty( Environment.USE_QUERY_CACHE, true ); - } - } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/NaturalIdAndAssociationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/NaturalIdAndAssociationTest.java index 00de58cb147b..a1b96cc424ef 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/NaturalIdAndAssociationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/NaturalIdAndAssociationTest.java @@ -12,6 +12,7 @@ import org.hibernate.testing.orm.junit.Jira; 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.Embeddable; @@ -23,6 +24,7 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; +@SuppressWarnings("JUnitMalformedDeclaration") @DomainModel( annotatedClasses = { NaturalIdAndAssociationTest.PositionEntity.class, @@ -31,6 +33,10 @@ @SessionFactory @Jira("HHH-18338") public class NaturalIdAndAssociationTest { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); + } @Test public void testPersist(SessionFactoryScope scope) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/NaturalIdOnManyToOne.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/NaturalIdOnManyToOne.java index 5b8eeb42641b..53730932a71d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/NaturalIdOnManyToOne.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/NaturalIdOnManyToOne.java @@ -11,14 +11,14 @@ import org.hibernate.annotations.NaturalId; import org.hibernate.annotations.NaturalIdCache; -@Entity -@NaturalIdCache /** * Test case for NaturalId annotation - ANN-750 * * @author Emmanuel Bernard * @author Hardy Ferentschik */ +@Entity +@NaturalIdCache class NaturalIdOnManyToOne { @Id diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/NaturalIdOnSingleManyToOneTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/NaturalIdOnSingleManyToOneTest.java index 71732d59166f..3a93b7da7492 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/NaturalIdOnSingleManyToOneTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/NaturalIdOnSingleManyToOneTest.java @@ -26,6 +26,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +@SuppressWarnings("JUnitMalformedDeclaration") @DomainModel( annotatedClasses = { NaturalIdOnSingleManyToOneTest.NaturalIdOnManyToOne.class, diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/NaturalIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/NaturalIdTest.java index 5d7dd4e5c3d1..f9d265ddee84 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/NaturalIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/NaturalIdTest.java @@ -7,25 +7,22 @@ import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Root; - -import org.hibernate.NaturalIdLoadAccess; import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.cfg.Configuration; import org.hibernate.metamodel.mapping.EntityMappingType; import org.hibernate.metamodel.mapping.NaturalIdMapping; import org.hibernate.query.Query; -import org.hibernate.stat.Statistics; - -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Test; -import org.junit.jupiter.api.Assertions; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.hibernate.cfg.CacheSettings.USE_QUERY_CACHE; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; /** @@ -34,24 +31,28 @@ * @author Emmanuel Bernard * @author Hardy Ferentschik */ -public class NaturalIdTest extends BaseCoreFunctionalTestCase { - @After - public void cleanupData() { - super.cleanupCache(); - Session s = sessionFactory().openSession(); - s.beginTransaction(); - s.createQuery( "delete NaturalIdOnManyToOne" ).executeUpdate(); - s.createQuery( "delete Citizen" ).executeUpdate(); - s.createQuery( "delete State" ).executeUpdate(); - s.getTransaction().commit(); - s.close(); +@SuppressWarnings("JUnitMalformedDeclaration") +@ServiceRegistry(settings = @Setting(name = USE_QUERY_CACHE, value = "true")) +@DomainModel( annotatedClasses = { Citizen.class, State.class, NaturalIdOnManyToOne.class } ) +@SessionFactory +public class NaturalIdTest { + @AfterEach + public void cleanupData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); + cleanupCaches( factoryScope ); + } + + protected void cleanupCaches(SessionFactoryScope factoryScope) { + factoryScope.getSessionFactory().getCache().evictAllRegions(); } @Test - public void testMappingProperties() { - final EntityMappingType citizenEntityMapping = sessionFactory() + public void testMappingProperties(SessionFactoryScope factoryScope) { + final EntityMappingType citizenEntityMapping = factoryScope + .getSessionFactory() .getRuntimeMetamodels() - .getEntityMappingType( Citizen.class ); + .getMappingMetamodel() + .getEntityDescriptor( Citizen.class ); final NaturalIdMapping naturalIdMapping = citizenEntityMapping.getNaturalIdMapping(); @@ -65,302 +66,226 @@ public void testMappingProperties() { } @Test - public void testNaturalIdCached() { - saveSomeCitizens(); - - Session s = openSession(); - Transaction tx = s.beginTransaction(); - State france = this.getState( s, "Ile de France" ); - NaturalIdLoadAccess loadAccess = s.byNaturalId( Citizen.class ) - .using( "ssn", "1234" ) - .using("state", france ); + public void testNaturalIdCached(SessionFactoryScope factoryScope) { + saveSomeCitizens( factoryScope ); - this.cleanupCache(); - - Statistics stats = sessionFactory().getStatistics(); + final var sessionFactory = factoryScope.getSessionFactory(); + final var stats = sessionFactory.getStatistics(); stats.setStatisticsEnabled( true ); stats.clear(); - assertEquals( "Cache hits should be empty", 0, stats.getNaturalIdCacheHitCount() ); - assertEquals( "Cache puts should be empty", 0, stats.getNaturalIdCachePutCount() ); - - // first query - assertNotNull( loadAccess.load() ); - assertEquals( "NaturalId Cache Hits", 0, stats.getNaturalIdCacheHitCount() ); - assertEquals( "NaturalId Cache Misses", 1, stats.getNaturalIdCacheMissCount() ); - assertEquals( "NaturalId Cache Puts", 1, stats.getNaturalIdCachePutCount() ); - assertEquals( "NaturalId Cache Queries", 1, stats.getNaturalIdQueryExecutionCount() ); - - // query a second time - result should be cached in session - loadAccess.load(); - assertEquals( "NaturalId Cache Hits", 0, stats.getNaturalIdCacheHitCount() ); - assertEquals( "NaturalId Cache Misses", 1, stats.getNaturalIdCacheMissCount() ); - assertEquals( "NaturalId Cache Puts", 1, stats.getNaturalIdCachePutCount() ); - assertEquals( "NaturalId Cache Queries", 1, stats.getNaturalIdQueryExecutionCount() ); - - // cleanup - tx.rollback(); - s.close(); + + factoryScope.inTransaction( (session) -> { + var france = session.find( State.class, 1 ); + var loadAccess = session.byNaturalId( Citizen.class ) + .using( "ssn", "1234" ) + .using("state", france ); + + cleanupCaches( factoryScope ); + + assertEquals( 0, stats.getNaturalIdCacheHitCount(), "Cache hits should be empty" ); + assertEquals( 0, stats.getNaturalIdCachePutCount(), "Cache puts should be empty" ); + + // first query + assertNotNull( loadAccess.load() ); + assertEquals( 0, stats.getNaturalIdCacheHitCount(), "NaturalId Cache Hits" ); + assertEquals( 1, stats.getNaturalIdCacheMissCount(), "NaturalId Cache Misses" ); + assertEquals( 1, stats.getNaturalIdCachePutCount(), "NaturalId Cache Puts" ); + assertEquals( 1, stats.getNaturalIdQueryExecutionCount(), "NaturalId Cache Queries" ); + + // query a second time - result should be cached in session + loadAccess.load(); + assertEquals( 0, stats.getNaturalIdCacheHitCount(), "NaturalId Cache Hits" ); + assertEquals( 1, stats.getNaturalIdCacheMissCount(), "NaturalId Cache Misses" ); + assertEquals( 1, stats.getNaturalIdCachePutCount(), "NaturalId Cache Puts" ); + assertEquals( 1, stats.getNaturalIdQueryExecutionCount(), "NaturalId Cache Queries" ); + } ); } @Test - public void testNaturalIdLoaderNotCached() { - saveSomeCitizens(); - - Session s = openSession(); - Transaction tx = s.beginTransaction(); - State france = this.getState( s, "Ile de France" ); - final NaturalIdLoadAccess naturalIdLoader = s.byNaturalId( Citizen.class ); - naturalIdLoader.using( "ssn", "1234" ).using( "state", france ); - - //NaturalId cache gets populated during entity loading, need to clear it out - this.cleanupCache(); - Statistics stats = sessionFactory().getStatistics(); + public void testNaturalIdLoaderNotCached(SessionFactoryScope factoryScope) { + saveSomeCitizens( factoryScope ); + + final var sessionFactory = factoryScope.getSessionFactory(); + final var stats = sessionFactory.getStatistics(); stats.setStatisticsEnabled( true ); - stats.clear(); - assertEquals( "NaturalId Cache Hits", 0, stats.getNaturalIdCacheHitCount() ); - assertEquals( "NaturalId Cache Misses", 0, stats.getNaturalIdCacheMissCount() ); - assertEquals( "NaturalId Cache Puts", 0, stats.getNaturalIdCachePutCount() ); - assertEquals( "NaturalId Cache Queries", 0, stats.getNaturalIdQueryExecutionCount() ); - - // first query - Citizen citizen = naturalIdLoader.load(); - assertNotNull( citizen ); - assertEquals( "NaturalId Cache Hits", 0, stats.getNaturalIdCacheHitCount() ); - assertEquals( "NaturalId Cache Misses", 1, stats.getNaturalIdCacheMissCount() ); - assertEquals( "NaturalId Cache Puts", 1, stats.getNaturalIdCachePutCount() ); - assertEquals( "NaturalId Cache Queries", 1, stats.getNaturalIdQueryExecutionCount() ); - - // cleanup - tx.rollback(); - s.close(); + + factoryScope.inTransaction( (session) -> { + var france = session.find( State.class, 1 ); + var naturalIdLoader = session.byNaturalId( Citizen.class ); + naturalIdLoader.using( "ssn", "1234" ).using( "state", france ); + + //NaturalId cache gets populated during entity loading, need to clear it out + cleanupCaches( factoryScope ); + stats.clear(); + + assertEquals( 0, stats.getNaturalIdCacheHitCount(), "NaturalId Cache Hits" ); + assertEquals( 0, stats.getNaturalIdCacheMissCount(), "NaturalId Cache Misses" ); + assertEquals( 0, stats.getNaturalIdCachePutCount(), "NaturalId Cache Puts" ); + assertEquals( 0, stats.getNaturalIdQueryExecutionCount(), "NaturalId Cache Queries" ); + + // first query + assertNotNull( naturalIdLoader.load() ); + assertEquals( 0, stats.getNaturalIdCacheHitCount(), "NaturalId Cache Hits" ); + assertEquals( 1, stats.getNaturalIdCacheMissCount(), "NaturalId Cache Misses" ); + assertEquals( 1, stats.getNaturalIdCachePutCount(), "NaturalId Cache Puts" ); + assertEquals( 1, stats.getNaturalIdQueryExecutionCount(), "NaturalId Cache Queries" ); + + } ); } @Test - public void testManyToOneNaturalLoadByNaturalId() { - NaturalIdOnManyToOne singleManyToOne1 = new NaturalIdOnManyToOne(); - NaturalIdOnManyToOne singleManyToOne2 = new NaturalIdOnManyToOne(); - - Citizen c1 = new Citizen(); - c1.setFirstname( "Emmanuel" ); - c1.setLastname( "Bernard" ); - c1.setSsn( "1234" ); - - State france = new State(); - france.setName( "Ile de France" ); - c1.setState( france ); - - singleManyToOne1.setCitizen( c1 ); - singleManyToOne2.setCitizen( null ); - - inTransaction( - session -> { - session.persist( france ); - session.persist( c1 ); - session.persist( singleManyToOne1 ); - session.persist( singleManyToOne2 ); - } - ); - - inSession( - session -> { - session.getSessionFactory().getCache().evictNaturalIdData(); // we want to go to the database - session.beginTransaction(); - try { - NaturalIdOnManyToOne instance1 = session.byNaturalId( NaturalIdOnManyToOne.class ) - .using( "citizen", c1 ) - .load(); - Assertions.assertNotNull( instance1 ); - Assertions.assertNotNull( instance1.getCitizen() ); - - NaturalIdOnManyToOne instance2 = session.byNaturalId( NaturalIdOnManyToOne.class ) - .using( "citizen", null ).load(); - - Assertions.assertNotNull( instance2 ); - assertNull( instance2.getCitizen() ); - } - finally { - session.getTransaction().rollback(); - } - } - ); + public void testManyToOneNaturalLoadByNaturalId(SessionFactoryScope factoryScope) { + saveSomeCitizens( factoryScope ); + + var citizen1 = factoryScope.fromTransaction( (session) -> { + NaturalIdOnManyToOne singleManyToOne1 = new NaturalIdOnManyToOne(); + NaturalIdOnManyToOne singleManyToOne2 = new NaturalIdOnManyToOne(); + + final Citizen citizen = session.find( Citizen.class, 1 ); + singleManyToOne1.setCitizen( citizen ); + singleManyToOne2.setCitizen( null ); + + session.persist( singleManyToOne1 ); + session.persist( singleManyToOne2 ); + + return citizen; + } ); + + factoryScope.inTransaction( (session) -> { + // we want to go to the database + session.getSessionFactory().getCache().evictNaturalIdData(); + + var instance1 = session.byNaturalId( NaturalIdOnManyToOne.class ) + .using( "citizen", citizen1 ) + .load(); + assertNotNull( instance1 ); + assertNotNull( instance1.getCitizen() ); + + var instance2 = session.byNaturalId( NaturalIdOnManyToOne.class ) + .using( "citizen", null ) + .load(); + assertNotNull( instance2 ); + assertNull( instance2.getCitizen() ); + } ); } @Test - public void testNaturalIdLoaderCached() { - Statistics stats = sessionFactory().getStatistics(); + public void testNaturalIdLoaderCached(SessionFactoryScope factoryScope) { + final var stats = factoryScope.getSessionFactory().getStatistics(); stats.setStatisticsEnabled( true ); stats.clear(); - assertEquals( "NaturalId Cache Hits", 0, stats.getNaturalIdCacheHitCount() ); - assertEquals( "NaturalId Cache Misses", 0, stats.getNaturalIdCacheMissCount() ); - assertEquals( "NaturalId Cache Puts", 0, stats.getNaturalIdCachePutCount() ); - assertEquals( "NaturalId Cache Queries", 0, stats.getNaturalIdQueryExecutionCount() ); + assertEquals( 0, stats.getNaturalIdCacheHitCount(), "NaturalId Cache Hits" ); + assertEquals( 0, stats.getNaturalIdCacheMissCount(), "NaturalId Cache Misses" ); + assertEquals( 0, stats.getNaturalIdCachePutCount(), "NaturalId Cache Puts" ); + assertEquals( 0, stats.getNaturalIdQueryExecutionCount(), "NaturalId Cache Queries" ); - saveSomeCitizens(); + saveSomeCitizens( factoryScope ); - assertEquals( "NaturalId Cache Hits", 0, stats.getNaturalIdCacheHitCount() ); - assertEquals( "NaturalId Cache Misses", 0, stats.getNaturalIdCacheMissCount() ); - assertEquals( "NaturalId Cache Puts", 2, stats.getNaturalIdCachePutCount() ); - assertEquals( "NaturalId Cache Queries", 0, stats.getNaturalIdQueryExecutionCount() ); + assertEquals( 0, stats.getNaturalIdCacheHitCount(), "NaturalId Cache Hits" ); + assertEquals( 0, stats.getNaturalIdCacheMissCount(), "NaturalId Cache Misses" ); + assertEquals( 2, stats.getNaturalIdCachePutCount(), "NaturalId Cache Puts" ); + assertEquals( 0, stats.getNaturalIdQueryExecutionCount(), "NaturalId Cache Queries" ); //Try NaturalIdLoadAccess after insert + factoryScope.inTransaction( (session) -> { + var france = session.find( State.class, 1 ); + var naturalIdLoader = session + .byNaturalId( Citizen.class ) + .using( "ssn", "1234" ) + .using( "state", france ); - Session s = openSession(); - Transaction tx = s.beginTransaction(); - State france = this.getState( s, "Ile de France" ); - NaturalIdLoadAccess naturalIdLoader = s.byNaturalId( Citizen.class ); - naturalIdLoader.using( "ssn", "1234" ).using( "state", france ); + //Not clearing naturalId caches, should be warm from entity loading + stats.clear(); - //Not clearing naturalId caches, should be warm from entity loading - stats.clear(); - - // first query - Citizen citizen = (Citizen)naturalIdLoader.load(); - assertNotNull( citizen ); - assertEquals( "NaturalId Cache Hits", 1, stats.getNaturalIdCacheHitCount() ); - assertEquals( "NaturalId Cache Misses", 0, stats.getNaturalIdCacheMissCount() ); - assertEquals( "NaturalId Cache Puts", 0, stats.getNaturalIdCachePutCount() ); - assertEquals( "NaturalId Cache Queries", 0, stats.getNaturalIdQueryExecutionCount() ); - - // cleanup - tx.rollback(); - s.close(); + // first query + assertNotNull( naturalIdLoader.load() ); + assertEquals( 1, stats.getNaturalIdCacheHitCount(), "NaturalId Cache Hits" ); + assertEquals( 0, stats.getNaturalIdCacheMissCount(), "NaturalId Cache Misses" ); + assertEquals( 0, stats.getNaturalIdCachePutCount(), "NaturalId Cache Puts" ); + assertEquals( 0, stats.getNaturalIdQueryExecutionCount(), "NaturalId Cache Queries" ); + } ); //Try NaturalIdLoadAccess + factoryScope.inTransaction( (session) -> { + cleanupCaches( factoryScope ); + stats.clear(); - s = openSession(); - tx = s.beginTransaction(); - - this.cleanupCache(); - stats.setStatisticsEnabled( true ); - stats.clear(); - - // first query - citizen = (Citizen) s.get( Citizen.class, citizen.getId() ); - assertNotNull( citizen ); - assertEquals( "NaturalId Cache Hits", 0, stats.getNaturalIdCacheHitCount() ); - assertEquals( "NaturalId Cache Misses", 0, stats.getNaturalIdCacheMissCount() ); - assertEquals( "NaturalId Cache Puts", 1, stats.getNaturalIdCachePutCount() ); - assertEquals( "NaturalId Cache Queries", 0, stats.getNaturalIdQueryExecutionCount() ); - - // cleanup - tx.rollback(); - s.close(); + // first query + assertThat( session.find( Citizen.class, 1 ) ).isNotNull(); + assertEquals( 0, stats.getNaturalIdCacheHitCount(), "NaturalId Cache Hits" ); + assertEquals( 0, stats.getNaturalIdCacheMissCount(), "NaturalId Cache Misses" ); + assertEquals( 1, stats.getNaturalIdCachePutCount(), "NaturalId Cache Puts" ); + assertEquals( 0, stats.getNaturalIdQueryExecutionCount(), "NaturalId Cache Queries" ); + } ); //Try NaturalIdLoadAccess after load - - s = openSession(); - tx = s.beginTransaction(); - france = this.getState( s, "Ile de France" ); - naturalIdLoader = s.byNaturalId( Citizen.class ); - naturalIdLoader.using( "ssn", "1234" ).using( "state", france ); - - //Not clearing naturalId caches, should be warm from entity loading - stats.setStatisticsEnabled( true ); - stats.clear(); - - // first query - citizen = (Citizen)naturalIdLoader.load(); - assertNotNull( citizen ); - assertEquals( "NaturalId Cache Hits", 1, stats.getNaturalIdCacheHitCount() ); - assertEquals( "NaturalId Cache Misses", 0, stats.getNaturalIdCacheMissCount() ); - assertEquals( "NaturalId Cache Puts", 0, stats.getNaturalIdCachePutCount() ); - assertEquals( "NaturalId Cache Queries", 0, stats.getNaturalIdQueryExecutionCount() ); - - // cleanup - tx.rollback(); - s.close(); + factoryScope.inTransaction( (session) -> { + var france = session.find( State.class, 1 ); + var naturalIdLoader = session.byNaturalId( Citizen.class ) + .using( "ssn", "1234" ) + .using( "state", france ); + + //Not clearing naturalId caches, should be warm from entity loading + stats.clear(); + + // first query + assertThat( naturalIdLoader.load() ).isNotNull(); + assertEquals( 1, stats.getNaturalIdCacheHitCount(), "NaturalId Cache Hits" ); + assertEquals( 0, stats.getNaturalIdCacheMissCount(), "NaturalId Cache Misses" ); + assertEquals( 0, stats.getNaturalIdCachePutCount(), "NaturalId Cache Puts" ); + assertEquals( 0, stats.getNaturalIdQueryExecutionCount(), "NaturalId Cache Queries" ); + } ); } @Test - public void testNaturalIdUncached() { - saveSomeCitizens(); + public void testNaturalIdUncached(SessionFactoryScope factoryScope) { + saveSomeCitizens( factoryScope ); - Session s = openSession(); - Transaction tx = s.beginTransaction(); - State france = this.getState( s, "Ile de France" ); - final NaturalIdLoadAccess naturalIdLoader = s.byNaturalId( Citizen.class ); - naturalIdLoader.using( "ssn", "1234" ).using( "state", france ); - - this.cleanupCache(); - - Statistics stats = sessionFactory().getStatistics(); + var stats = factoryScope.getSessionFactory().getStatistics(); stats.setStatisticsEnabled( true ); - stats.clear(); - assertEquals( - "Cache hits should be empty", 0, stats - .getNaturalIdCacheHitCount() - ); - - // first query - Citizen citizen = naturalIdLoader.load(); - assertNotNull( citizen ); - assertEquals( - "Cache hits should be empty", 0, stats - .getNaturalIdCacheHitCount() - ); - assertEquals( - "Query execution count should be one", 1, stats - .getNaturalIdQueryExecutionCount() - ); - - // query a second time - result should be cached in session - naturalIdLoader.load(); - assertEquals( - "Cache hits should be empty", 0, stats - .getNaturalIdCacheHitCount() - ); - assertEquals( - "Second query should not be a miss", 1, stats - .getNaturalIdCacheMissCount() - ); - assertEquals( - "Query execution count should be one", 1, stats - .getNaturalIdQueryExecutionCount() - ); - - // cleanup - tx.rollback(); - s.close(); - } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Citizen.class, State.class, - NaturalIdOnManyToOne.class - }; + factoryScope.inTransaction( (session) -> { + var france = session.find( State.class, 1 ); + var naturalIdLoader = session.byNaturalId( Citizen.class ) + .using( "ssn", "1234" ) + .using( "state", france ); + + cleanupCaches( factoryScope ); + stats.clear(); + + assertEquals( 0, stats.getNaturalIdCacheHitCount(), "Cache hits should be empty" ); + + // first query + Citizen citizen = naturalIdLoader.load(); + assertNotNull( citizen ); + assertEquals( 0, stats.getNaturalIdCacheHitCount(), "Cache hits should be empty" ); + assertEquals( 1, stats.getNaturalIdQueryExecutionCount(), "Query execution count should be one" ); + + // query a second time - result should be cached in session + naturalIdLoader.load(); + assertEquals( 0, stats.getNaturalIdCacheHitCount(), "Cache hits should be empty" ); + assertEquals( 1, stats.getNaturalIdCacheMissCount(), "Second query should not be a miss" ); + assertEquals( 1, stats.getNaturalIdQueryExecutionCount(), "Query execution count should be one" ); + } ); } - private void saveSomeCitizens() { - Citizen c1 = new Citizen(); - c1.setFirstname( "Emmanuel" ); - c1.setLastname( "Bernard" ); - c1.setSsn( "1234" ); - - State france = new State(); - france.setName( "Ile de France" ); - c1.setState( france ); - - Citizen c2 = new Citizen(); - c2.setFirstname( "Gavin" ); - c2.setLastname( "King" ); - c2.setSsn( "000" ); - State australia = new State(); - australia.setName( "Australia" ); - c2.setState( australia ); - - Session s = openSession(); - Transaction tx = s.beginTransaction(); - s.persist( australia ); - s.persist( france ); - s.persist( c1 ); - s.persist( c2 ); - tx.commit(); - s.close(); + private void saveSomeCitizens(SessionFactoryScope factoryScope) { + State france = new State( 1, "Ile de France" ); + Citizen c1 = new Citizen( 1, "Emmanuel", "Bernard", france, "1234" ); + + State australia = new State( 2, "Australia" ); + Citizen c2 = new Citizen( 2, "Gavin", "King", australia, "000" ); + + factoryScope.inTransaction( (session) -> { + session.persist( australia ); + session.persist( france ); + session.persist( c1 ); + session.persist( c2 ); + } ); } private State getState(Session s, String name) { @@ -373,9 +298,4 @@ private State getState(Session s, String name) { query.setCacheable( true ); return query.list().get( 0 ); } - - @Override - protected void configure(Configuration cfg) { - cfg.setProperty( USE_QUERY_CACHE, true ); - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/NaturalIdUniqueConstraintNameTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/NaturalIdUniqueConstraintNameTest.java index 0ebfeb780c86..5be303072725 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/NaturalIdUniqueConstraintNameTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/NaturalIdUniqueConstraintNameTest.java @@ -4,39 +4,34 @@ */ package org.hibernate.orm.test.annotations.naturalid; -import java.util.Map; - -import org.hibernate.annotations.NaturalId; -import org.hibernate.boot.Metadata; -import org.hibernate.boot.MetadataSources; -import org.hibernate.mapping.UniqueKey; - -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; - import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; import jakarta.persistence.UniqueConstraint; +import org.hibernate.annotations.NaturalId; +import org.hibernate.boot.MetadataSources; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.ServiceRegistryScope; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey("HHH-17132") -public class NaturalIdUniqueConstraintNameTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { +@ServiceRegistry +public class NaturalIdUniqueConstraintNameTest { + private Class[] getAnnotatedClasses() { return new Class[] { City1.class, City2.class }; } @Test - public void testNaturalIdUsesUniqueConstraintName() { - Metadata metadata = new MetadataSources( serviceRegistry() ) + public void testNaturalIdUsesUniqueConstraintName(ServiceRegistryScope registryScope) { + var metadata = new MetadataSources( registryScope.getRegistry() ) .addAnnotatedClasses( getAnnotatedClasses() ) .buildMetadata(); - Map uniqueKeys = metadata.getEntityBinding( City1.class.getName() ) + var uniqueKeys = metadata.getEntityBinding( City1.class.getName() ) .getTable() .getUniqueKeys(); @@ -44,17 +39,17 @@ public void testNaturalIdUsesUniqueConstraintName() { assertEquals( 1, uniqueKeys.size() ); // The unique key should use the name specified in UniqueConstraint. - UniqueKey uniqueKey = uniqueKeys.values().iterator().next(); + var uniqueKey = uniqueKeys.values().iterator().next(); assertEquals( "UK_zipCode_city", uniqueKey.getName() ); } @Test - public void testNaturalIdUsesExplicitColumns() { - Metadata metadata = new MetadataSources( serviceRegistry() ) + public void testNaturalIdUsesExplicitColumns(ServiceRegistryScope registryScope) { + var metadata = new MetadataSources( registryScope.getRegistry() ) .addAnnotatedClasses( getAnnotatedClasses() ) .buildMetadata(); - Map uniqueKeys = metadata.getEntityBinding( City2.class.getName() ) + var uniqueKeys = metadata.getEntityBinding( City2.class.getName() ) .getTable() .getUniqueKeys(); @@ -62,7 +57,7 @@ public void testNaturalIdUsesExplicitColumns() { assertEquals( 1, uniqueKeys.size() ); // The unique key should use the name specified in UniqueConstraint. - UniqueKey uniqueKey = uniqueKeys.values().iterator().next(); + var uniqueKey = uniqueKeys.values().iterator().next(); assertEquals( "zipCode", uniqueKey.getColumns().get( 0 ).getName() ); assertEquals( "city", uniqueKey.getColumns().get( 1 ).getName() ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/State.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/State.java index c21e882dc293..d2633fd67399 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/State.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/State.java @@ -4,7 +4,6 @@ */ package org.hibernate.orm.test.annotations.naturalid; import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; /** @@ -13,10 +12,17 @@ @Entity public class State { @Id - @GeneratedValue private Integer id; private String name; + public State() { + } + + public State(Integer id, String name) { + this.id = id; + this.name = name; + } + public Integer getId() { return id; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/cid/EmbeddedAndNaturalIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/cid/EmbeddedAndNaturalIdTest.java index 46d3fabb0fee..ec9dab76b108 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/cid/EmbeddedAndNaturalIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/cid/EmbeddedAndNaturalIdTest.java @@ -7,87 +7,66 @@ import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Root; - +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Donnchadh O Donnabhain */ -public class EmbeddedAndNaturalIdTest extends BaseCoreFunctionalTestCase { +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(annotatedClasses = {A.class, AId.class}) +@SessionFactory +public class EmbeddedAndNaturalIdTest { @JiraKey(value = "HHH-9333") @Test - public void testSave() { - A account = new A( new AId( 1 ), "testCode" ); - inTransaction( - session -> - session.persist( account ) - ); + public void testSave(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( session -> { + var account = new A( new AId( 1 ), "testCode" ); + session.persist( account ); + } ); } @JiraKey(value = "HHH-9333") @Test - public void testNaturalIdCriteria() { - inTransaction( - s -> { - A u = new A( new AId( 1 ), "testCode" ); - s.persist( u ); - } - ); + public void testNaturalIdCriteria(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + A u = new A( new AId( 1 ), "testCode" ); + session.persist( u ); + } ); - inTransaction( - s -> { - CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); - CriteriaQuery criteria = criteriaBuilder.createQuery( A.class ); - Root root = criteria.from( A.class ); - criteria.where( criteriaBuilder.equal( root.get( "shortCode" ), "testCode" ) ); - A u = s.createQuery( criteria ).uniqueResult(); -// u = ( A ) s.createCriteria( A.class ) -// .add( Restrictions.naturalId().set( "shortCode", "testCode" ) ) -// .uniqueResult(); - assertNotNull( u ); - } - ); + factoryScope.inTransaction( (session) -> { + CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); + CriteriaQuery criteria = criteriaBuilder.createQuery( A.class ); + Root root = criteria.from( A.class ); + criteria.where( criteriaBuilder.equal( root.get( "shortCode" ), "testCode" ) ); + A u = session.createQuery( criteria ).uniqueResult(); + assertNotNull( u ); + } ); } @JiraKey(value = "HHH-9333") @Test - public void testByNaturalId() { - inTransaction( - s -> { - A u = new A( new AId( 1 ), "testCode" ); - s.persist( u ); - } - ); - - inTransaction( - s -> { - A u = s.byNaturalId( A.class ).using( "shortCode", "testCode" ).load(); - assertNotNull( u ); - } - ); - } - - @After - public void tearDown() { - // clean up - inTransaction( - session -> - session.createQuery( "delete A" ).executeUpdate() + public void testByNaturalId(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + A u = new A( new AId( 1 ), "testCode" ); + session.persist( u ); + } ); - ); + factoryScope.inTransaction(s -> { + A u = s.byNaturalId( A.class ).using( "shortCode", "testCode" ).load(); + assertNotNull( u ); + } ); } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - A.class, - AId.class - }; + @AfterEach + public void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/boot/cfgXml/CfgXmlResourceNameClosingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/boot/cfgXml/CfgXmlResourceNameClosingTest.java index fb428db3a916..3eaedb22d489 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/boot/cfgXml/CfgXmlResourceNameClosingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/boot/cfgXml/CfgXmlResourceNameClosingTest.java @@ -4,25 +4,22 @@ */ package org.hibernate.orm.test.boot.cfgXml; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - import org.hibernate.boot.cfgxml.internal.ConfigLoader; -import org.hibernate.boot.registry.BootstrapServiceRegistry; import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; -import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl; - +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.jupiter.api.Test; -import org.junit.Test; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test that makes sure the input stream inside {@link ConfigLoader#loadConfigXmlResource(String)} @@ -30,31 +27,29 @@ * * @author Steve Ebersole */ +@BaseUnitTest @JiraKey( value = "HHH-10120" ) -public class CfgXmlResourceNameClosingTest extends BaseUnitTestCase { - private static class InputStreamWrapper extends InputStream { - private final InputStream wrapped; - private boolean wasClosed = false; - - public InputStreamWrapper(InputStream wrapped) { - this.wrapped = wrapped; - } - - @Override - public int read() throws IOException { - return wrapped.read(); +public class CfgXmlResourceNameClosingTest { + @Test + public void testStreamClosing() { + final var classLoaderService = new LocalClassLoaderServiceImpl(); + final var bootstrapServiceRegistry = new BootstrapServiceRegistryBuilder() + .applyClassLoaderService( classLoaderService ) + .build(); + final var serviceRegistry = ServiceRegistryUtil.serviceRegistryBuilder( bootstrapServiceRegistry ) + .configure( "org/hibernate/orm/test/boot/cfgXml/hibernate.cfg.xml" ) + .build(); + try { + assertThat( classLoaderService.openedStreams ).hasSize( 1 ); + for ( InputStreamWrapper openedStream : classLoaderService.openedStreams ) { + assertTrue( openedStream.wasClosed ); + } } - - @Override - public void close() throws IOException { - wrapped.close(); - wasClosed = true; - super.close(); + finally { + StandardServiceRegistryBuilder.destroy( serviceRegistry ); } - public boolean wasClosed() { - return wasClosed; - } + assertTrue( classLoaderService.stopped ); } private static class LocalClassLoaderServiceImpl extends ClassLoaderServiceImpl { @@ -85,25 +80,30 @@ public void stop() { } } - LocalClassLoaderServiceImpl classLoaderService = new LocalClassLoaderServiceImpl(); + private static class InputStreamWrapper extends InputStream { + private final InputStream wrapped; + private boolean wasClosed = false; - @Test - public void testStreamClosing() { - BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder() - .applyClassLoaderService( classLoaderService ) - .build(); - StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder( bsr ) - .configure( "org/hibernate/orm/test/boot/cfgXml/hibernate.cfg.xml" ) - .build(); - try { - for ( InputStreamWrapper openedStream : classLoaderService.openedStreams ) { - assertTrue( openedStream.wasClosed ); - } + public InputStreamWrapper(InputStream wrapped) { + this.wrapped = wrapped; } - finally { - StandardServiceRegistryBuilder.destroy( ssr ); + + @Override + public int read() throws IOException { + return wrapped.read(); } - assertTrue( classLoaderService.stopped ); + @Override + public void close() throws IOException { + wrapped.close(); + wasClosed = true; + super.close(); + } + + public boolean wasClosed() { + return wasClosed; + } } + + } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/deletetransient/DeleteTransientEntityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/deletetransient/DeleteTransientEntityTest.java index 420541bded73..bc59cf2fb252 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/deletetransient/DeleteTransientEntityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/deletetransient/DeleteTransientEntityTest.java @@ -24,11 +24,8 @@ /** * @author Steve Ebersole */ -@DomainModel( - xmlMappings = { - "org/hibernate/orm/test/deletetransient/Person.hbm.xml" - } -) +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(annotatedClasses = {Person.class, Address.class, Suite.class, Note.class}) @SessionFactory @BytecodeEnhanced @CustomEnhancementContext({ NoDirtyCheckingContext.class, DirtyCheckEnhancementContext.class }) @@ -36,167 +33,130 @@ public class DeleteTransientEntityTest { @AfterEach void tearDown(SessionFactoryScope scope) { - scope.getSessionFactory().getSchemaManager().truncate(); + scope.dropData(); } @Test public void testTransientEntityDeletionNoCascades(SessionFactoryScope scope) { - scope.inTransaction( - session -> { - session.remove( new Address() ); - } - ); + scope.inTransaction( session -> { + session.remove( new Address() ); + } ); } @Test public void testTransientEntityDeletionCascadingToTransientAssociation(SessionFactoryScope scope) { - scope.inTransaction( - session -> { - Person p = new Person(); - p.getAddresses().add( new Address() ); - session.persist( p ); - } - ); + scope.inTransaction( session -> { + Person p = new Person( 1, "steve" ); + p.getAddresses().add( new Address( 1, "123 Main St." ) ); + session.persist( p ); + } ); } @Test public void testTransientEntityDeleteCascadingToCircularity(SessionFactoryScope scope) { - scope.inTransaction( - session -> { - Person p1 = new Person(); - Person p2 = new Person(); - p1.getFriends().add( p2 ); - p2.getFriends().add( p1 ); - session.persist( p1 ); - } - ); + scope.inTransaction(session -> { + Person p1 = new Person( 1, "steve" ); + Person p2 = new Person( 2, "john" ); + p1.getFriends().add( p2 ); + p2.getFriends().add( p1 ); + session.persist( p1 ); + } ); } @Test public void testTransientEntityDeletionCascadingToDetachedAssociation(SessionFactoryScope scope) { - Address address = new Address(); - scope.inTransaction( - session -> { - address.setInfo( "123 Main St." ); - session.persist( address ); - } - ); - - scope.inTransaction( - session -> { - Person p = new Person(); - p.getAddresses().add( address ); - session.remove( p ); - } - ); - - scope.inTransaction( - session -> { - Long count = (Long) session.createQuery( "select count(*) from Address" ).list().get( 0 ); - assertEquals( 0, count.longValue(), "delete not cascaded properly across transient entity" ); - - } - ); + Address address = new Address( 1, "123 Main St." ); + + scope.inTransaction(session -> { + session.persist( address ); + } ); + + scope.inTransaction( session -> { + Person p = new Person( 1, "steve"); + p.getAddresses().add( address ); + session.remove( p ); + } ); + + scope.inTransaction(session -> { + var count = session.createQuery( "select count(*) from Address", Long.class ).uniqueResult(); + assertEquals( 0, count.longValue(), "delete not cascaded properly across transient entity" ); + } ); } @Test public void testTransientEntityDeletionCascadingToPersistentAssociation(SessionFactoryScope scope) { - Long id = scope.fromTransaction( - session -> { - Address address = new Address(); - address.setInfo( "123 Main St." ); - session.persist( address ); - return address.getId(); - } - ); - - scope.inTransaction( - session -> { - Address address = session.get( Address.class, id ); - Person p = new Person(); - p.getAddresses().add( address ); - session.remove( p ); - } - ); - - scope.inTransaction( - session -> { - Long count = (Long) session.createQuery( "select count(*) from Address" ).list().get( 0 ); - assertEquals( 0, count.longValue(), "delete not cascaded properly across transient entity" ); - } - ); + scope.inTransaction(session -> { + var address = new Address( 1, "123 Main St." ); + session.persist( address ); + } ); + + scope.inTransaction(session -> { + var address = session.find( Address.class, 1 ); + var p = new Person( 1, "steve"); + p.getAddresses().add( address ); + session.remove( p ); + } ); + + scope.inTransaction(session -> { + var count = session.createQuery( "select count(*) from Address", Long.class ).uniqueResult(); + assertEquals( 0, count.longValue(), "delete not cascaded properly across transient entity" ); + } ); } @Test - @SuppressWarnings({ "unchecked" }) public void testCascadeAllFromClearedPersistentAssnToTransientEntity(SessionFactoryScope scope) { - final Person p = new Person(); - Address address = new Address(); - scope.inTransaction( - session -> { - address.setInfo( "123 Main St." ); - p.getAddresses().add( address ); - session.persist( p ); - } - ); - - scope.inTransaction( - session -> { - Suite suite = new Suite(); - address.getSuites().add( suite ); - p.getAddresses().clear(); - session.merge( p ); - } - ); - - scope.inTransaction( - session -> { - Person person = session.get( p.getClass(), p.getId() ); - assertEquals( 0, person.getAddresses().size(), "persistent collection not cleared" ); - Long count = (Long) session.createQuery( "select count(*) from Address" ).list().get( 0 ); - assertEquals( 1, count.longValue() ); - count = (Long) session.createQuery( "select count(*) from Suite" ).list().get( 0 ); - assertEquals( 0, count.longValue() ); - } - ); + final Person p = new Person( 1, "steve" ); + Address address = new Address( 1, "123 Main St." ); + + scope.inTransaction(session -> { + p.getAddresses().add( address ); + session.persist( p ); + } ); + + scope.inTransaction(session -> { + Suite suite = new Suite(); + address.getSuites().add( suite ); + p.getAddresses().clear(); + session.merge( p ); + } ); + + scope.inTransaction(session -> { + Person person = session.find( p.getClass(), p.getId() ); + assertEquals( 0, person.getAddresses().size(), "persistent collection not cleared" ); + Long count = (Long) session.createQuery( "select count(*) from Address" ).list().get( 0 ); + assertEquals( 1, count.longValue() ); + count = (Long) session.createQuery( "select count(*) from Suite" ).list().get( 0 ); + assertEquals( 0, count.longValue() ); + } ); } @Test @SuppressWarnings({ "unchecked" }) public void testCascadeAllDeleteOrphanFromClearedPersistentAssnToTransientEntity(SessionFactoryScope scope) { - Address address = new Address(); - address.setInfo( "123 Main St." ); - Suite suite = new Suite(); + var address = new Address( 1, "123 Main St." ); + var suite = new Suite( 1, "Colorado" ); address.getSuites().add( suite ); - scope.inTransaction( - session -> { - - session.persist( address ); - } - ); - - scope.inTransaction( - session -> { - Note note = new Note(); - note.setDescription( "a description" ); - suite.getNotes().add( note ); - address.getSuites().clear(); - session.merge( address ); - } - ); - - - scope.inTransaction( - session -> { - Long count = (Long) session.createQuery( "select count(*) from Suite" ).list().get( 0 ); - assertEquals( - 0, - count.longValue(), - "all-delete-orphan not cascaded properly to cleared persistent collection entities" - ); - count = (Long) session.createQuery( "select count(*) from Note" ).list().get( 0 ); - assertEquals( 0, count.longValue() ); - } - ); + + scope.inTransaction(session -> { + session.persist( address ); + } ); + + scope.inTransaction( session -> { + Note note = new Note( 1, "a description" ); + suite.getNotes().add( note ); + address.getSuites().clear(); + session.merge( address ); + } ); + + scope.inTransaction(session -> { + Long count = (Long) session.createQuery( "select count(*) from Suite" ).list().get( 0 ); + assertEquals( + 0, + count.longValue(), + "all-delete-orphan not cascaded properly to cleared persistent collection entities" + ); + count = (Long) session.createQuery( "select count(*) from Note" ).list().get( 0 ); + assertEquals( 0, count.longValue() ); + } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/deletetransient/Address.java b/hibernate-core/src/test/java/org/hibernate/orm/test/deletetransient/Address.java index de39abf3f2cc..026299d7fa9f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/deletetransient/Address.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/deletetransient/Address.java @@ -3,31 +3,42 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.deletetransient; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; + import java.util.HashSet; import java.util.Set; /** - * todo: describe Address - * * @author Steve Ebersole */ +@Entity +@Table(name = "addresses") public class Address { - private Long id; + @Id + private Integer id; private String info; - private Set suites = new HashSet(); + @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) + @JoinColumn(name="address_fk") + private Set suites = new HashSet<>(); public Address() { } - public Address(String info) { + public Address(Integer id, String info) { + this.id = id; this.info = info; } - public Long getId() { + public Integer getId() { return id; } - public void setId(Long id) { + public void setId(Integer id) { this.id = id; } @@ -39,11 +50,11 @@ public void setInfo(String info) { this.info = info; } - public Set getSuites() { + public Set getSuites() { return suites; } - public void setSuites(Set suites) { + public void setSuites(Set suites) { this.suites = suites; } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/deletetransient/DeleteTransientEntityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/deletetransient/DeleteTransientEntityTest.java index 156d8c48ae5b..91651df5e92e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/deletetransient/DeleteTransientEntityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/deletetransient/DeleteTransientEntityTest.java @@ -4,191 +4,161 @@ */ package org.hibernate.orm.test.deletetransient; -import org.junit.Test; +import org.hibernate.internal.util.MutableObject; +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.jupiter.api.Assertions.assertEquals; /** * @author Steve Ebersole */ -public class DeleteTransientEntityTest extends BaseCoreFunctionalTestCase { - - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } - - @Override - public String[] getMappings() { - return new String[] { "deletetransient/Person.hbm.xml" }; - } - - @Override - protected boolean isCleanupTestDataRequired() { - return true; +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(annotatedClasses = {Person.class, Address.class, Suite.class, Note.class}) +@SessionFactory +public class DeleteTransientEntityTest { + @AfterEach + void dropTestData(SessionFactoryScope sessions) { + sessions.dropData(); } @Test - public void testTransientEntityDeletionNoCascades() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - s.remove( new Address() ); - t.commit(); - s.close(); + public void testTransientEntityDeletionNoCascades(SessionFactoryScope sessions) { + sessions.inTransaction( (session) -> { + session.remove( new Address() ); + } ); } @Test - @SuppressWarnings( {"unchecked"}) - public void testTransientEntityDeletionCascadingToTransientAssociation() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Person p = new Person(); - p.getAddresses().add( new Address() ); - s.remove( p ); - t.commit(); - s.close(); + public void testTransientEntityDeletionCascadingToTransientAssociation(SessionFactoryScope sessions) { + sessions.inTransaction( (session) -> { + Person p = new Person(); + p.getAddresses().add( new Address() ); + session.remove( p ); + } ); } @Test - @SuppressWarnings( {"unchecked"}) - public void testTransientEntityDeleteCascadingToCircularity() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Person p1 = new Person(); - Person p2 = new Person(); - p1.getFriends().add( p2 ); - p2.getFriends().add( p1 ); - s.remove( p1 ); - t.commit(); - s.close(); + public void testTransientEntityDeleteCascadingToCircularity(SessionFactoryScope sessions) { + sessions.inTransaction( (session) -> { + Person p1 = new Person(); + Person p2 = new Person(); + p1.getFriends().add( p2 ); + p2.getFriends().add( p1 ); + session.remove( p1 ); + } ); } @Test - @SuppressWarnings( {"unchecked"}) - public void testTransientEntityDeletionCascadingToDetachedAssociation() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Address address = new Address(); - address.setInfo( "123 Main St." ); - s.persist( address ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - Person p = new Person(); - p.getAddresses().add( address ); - s.remove( p ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - Long count = ( Long ) s.createQuery( "select count(*) from Address" ).list().get( 0 ); - assertEquals( "delete not cascaded properly across transient entity", 0, count.longValue() ); - t.commit(); - s.close(); + public void testTransientEntityDeletionCascadingToDetachedAssociation(SessionFactoryScope sessions) { + var address = sessions.fromTransaction( (session) -> { + Address created = new Address( 1, "123 Main St." ); + session.persist( created ); + return created; + } ); + + sessions.inTransaction( (session) -> { + Person p = new Person(); + p.getAddresses().add( address ); + session.remove( p ); + } ); + + sessions.inTransaction( (session) -> { + var count = session.createQuery( "select count(*) from Address", Long.class ).list().get( 0 ); + assertEquals( 0, count, "delete not cascaded properly across transient entity" ); + } ); } @Test - @SuppressWarnings( {"unchecked"}) - public void testTransientEntityDeletionCascadingToPersistentAssociation() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Address address = new Address(); - address.setInfo( "123 Main St." ); - s.persist( address ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - address = s.get( Address.class, address.getId() ); - Person p = new Person(); - p.getAddresses().add( address ); - s.remove( p ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - Long count = ( Long ) s.createQuery( "select count(*) from Address" ).list().get( 0 ); - assertEquals( "delete not cascaded properly across transient entity", 0, count.longValue() ); - t.commit(); - s.close(); + public void testTransientEntityDeletionCascadingToPersistentAssociation(SessionFactoryScope sessions) { + sessions.inTransaction( (session) -> { + Address address = new Address( 1, "123 Main St." ); + session.persist( address ); + } ); + + sessions.inTransaction( (session) -> { + var address = session.find( Address.class, 1 ); + Person p = new Person(); + p.getAddresses().add( address ); + session.remove( p ); + } ); + + sessions.inTransaction( (session) -> { + var count = session.createQuery( "select count(*) from Address", Long.class ).list().get( 0 ); + assertEquals( 0, count, "delete not cascaded properly across transient entity" ); + } ); } @Test - @SuppressWarnings( {"unchecked"}) - public void testCascadeAllFromClearedPersistentAssnToTransientEntity() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Person p = new Person(); - Address address = new Address(); - address.setInfo( "123 Main St." ); - p.getAddresses().add( address ); - s.persist( p ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - Suite suite = new Suite(); - address.getSuites().add( suite ); - p.getAddresses().clear(); - p = s.merge( p ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - p = ( Person ) s.get( p.getClass(), p.getId() ); - assertEquals( "persistent collection not cleared", 0, p.getAddresses().size() ); - Long count = ( Long ) s.createQuery( "select count(*) from Address" ).list().get( 0 ); - assertEquals( 1, count.longValue() ); - count = ( Long ) s.createQuery( "select count(*) from Suite" ).list().get( 0 ); - assertEquals( 0, count.longValue() ); - s.remove( p ); - t.commit(); - s.close(); + public void testCascadeAllFromClearedPersistentAssnToTransientEntity(SessionFactoryScope sessions) { + final MutableObject personRef = new MutableObject<>(); + final MutableObject
addressRef = new MutableObject<>(); + + sessions.inTransaction( (session) -> { + var person = new Person( 1, "steve" ); + var address = new Address( 1, "123 Main St." ); + person.getAddresses().add( address ); + session.persist( person ); + personRef.set( person ); + addressRef.set( address ); + } ); + + sessions.inTransaction( (session) -> { + var person = personRef.get(); + var address = addressRef.get(); + var suite = new Suite( 1, "Colorado" ); + address.getSuites().add( suite ); + person.getAddresses().clear(); + personRef.set( session.merge( person ) ); + } ); + + sessions.inTransaction( (session) -> { + var person = personRef.get(); + var address = addressRef.get(); + var suite = new Suite( 2, "Utah" ); + address.getSuites().add( suite ); + person.getAddresses().clear(); + personRef.set( session.merge( person ) ); + } ); + + sessions.inTransaction( (session) -> { + var person = session.find( Person.class, 1 ); + assertEquals( 0, person.getAddresses().size(), "persistent collection not cleared" ); + var count = session.createQuery( "select count(*) from Address", Long.class ).list().get( 0 ); + assertEquals( 1, count.longValue() ); + count = session.createQuery( "select count(*) from Suite", Long.class ).list().get( 0 ); + assertEquals( 0, count.longValue() ); + } ); } @Test @SuppressWarnings( {"unchecked"}) - public void testCascadeAllDeleteOrphanFromClearedPersistentAssnToTransientEntity() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Address address = new Address(); - address.setInfo( "123 Main St." ); - Suite suite = new Suite(); - address.getSuites().add( suite ); - s.persist( address ); - t.commit(); - s.close(); - - - s = openSession(); - t = s.beginTransaction(); - Note note = new Note(); - note.setDescription( "a description" ); - suite.getNotes().add( note ); - address.getSuites().clear(); - address = s.merge( address ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - Long count = ( Long ) s.createQuery( "select count(*) from Suite" ).list().get( 0 ); - assertEquals( "all-delete-orphan not cascaded properly to cleared persistent collection entities", 0, count.longValue() ); - count = ( Long ) s.createQuery( "select count(*) from Note" ).list().get( 0 ); - assertEquals( 0, count.longValue() ); - s.remove( address ); - t.commit(); - s.close(); + public void testCascadeAllDeleteOrphanFromClearedPersistentAssnToTransientEntity(SessionFactoryScope sessions) { + sessions.inTransaction( (session) -> { + var address = new Address( 1, "123 Main St." ); + var suite = new Suite( 1, "Colorado" ); + address.getSuites().add( suite ); + session.persist( address ); + } ); + + sessions.inTransaction( (session) -> { + var address = session.find( Address.class, 1 ); + var suite = session.find( Suite.class, 1 ); + var note = new Note( 1, "a description" ); + suite.getNotes().add( note ); + address.getSuites().clear(); + session.merge( address ); + } ); + + sessions.inTransaction( (session) -> { + var count = session.createQuery( "select count(*) from Suite", Long.class ).uniqueResult(); + assertEquals( 0, count.longValue(), + "all-delete-orphan not cascaded properly to cleared persistent collection entities" ); + count = session.createQuery( "select count(*) from Note", Long.class ).uniqueResult(); + assertEquals( 0, count.longValue() ); + } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/deletetransient/Note.java b/hibernate-core/src/test/java/org/hibernate/orm/test/deletetransient/Note.java index 5b743f169028..8ffe1baa6894 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/deletetransient/Note.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/deletetransient/Note.java @@ -4,27 +4,33 @@ */ package org.hibernate.orm.test.deletetransient; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; /** - * * @author Gail Badner */ +@Entity +@Table(name="notes") public class Note { - private Long id; + @Id + private Integer id; private String description; public Note() { } - public Note(String description) { + public Note(Integer id, String description) { + this.id = id; this.description = description; } - public Long getId() { + public Integer getId() { return id; } - public void setId(Long id) { + public void setId(Integer id) { this.id = id; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/deletetransient/Person.java b/hibernate-core/src/test/java/org/hibernate/orm/test/deletetransient/Person.java index d64c8e750f18..546f573542c5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/deletetransient/Person.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/deletetransient/Person.java @@ -3,34 +3,52 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.deletetransient; + +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; + import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Set; /** - * todo: describe Person - * * @author Steve Ebersole */ +@Entity +@Table(name = "persons") public class Person { - private Long id; + @Id + private Integer id; private String name; - private Set addresses = new HashSet(); - private Collection friends = new ArrayList(); + @OneToMany(cascade = CascadeType.ALL) + @JoinColumn(name = "person_fk") + private Set
addresses = new HashSet<>(); + @ManyToMany(cascade = CascadeType.ALL) + @JoinTable(name = "friends", + joinColumns = @JoinColumn(name = "fk1"), + inverseJoinColumns = @JoinColumn(name = "fk2")) + private Collection friends = new ArrayList<>(); public Person() { } - public Person(String name) { + public Person(Integer id, String name) { + this.id = id; this.name = name; } - public Long getId() { + public Integer getId() { return id; } - public void setId(Long id) { + public void setId(Integer id) { this.id = id; } @@ -42,19 +60,19 @@ public void setName(String name) { this.name = name; } - public Set getAddresses() { + public Set
getAddresses() { return addresses; } - public void setAddresses(Set addresses) { + public void setAddresses(Set
addresses) { this.addresses = addresses; } - public Collection getFriends() { + public Collection getFriends() { return friends; } - public void setFriends(Collection friends) { + public void setFriends(Collection friends) { this.friends = friends; } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/deletetransient/Suite.java b/hibernate-core/src/test/java/org/hibernate/orm/test/deletetransient/Suite.java index 153ac9e165be..98831395c9fd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/deletetransient/Suite.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/deletetransient/Suite.java @@ -3,6 +3,13 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.deletetransient; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; + import java.util.HashSet; import java.util.Set; @@ -10,23 +17,29 @@ * * @author Gail Badner */ +@Entity +@Table( name="suites") public class Suite { - private Long id; + @Id + private Integer id; private String location; - private Set notes = new HashSet(); + @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) + @JoinColumn(name="suite_fk") + private Set notes = new HashSet<>(); public Suite() { } - public Suite(String location) { + public Suite(Integer id, String location) { + this.id = id; this.location = location; } - public Long getId() { + public Integer getId() { return id; } - public void setId(Long id) { + public void setId(Integer id) { this.id = id; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/embeddable/MappedByEmbeddableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/embeddable/MappedByEmbeddableTest.java index 5ebdc5d33cfa..a90ea30e73ef 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/embeddable/MappedByEmbeddableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/embeddable/MappedByEmbeddableTest.java @@ -4,51 +4,52 @@ */ package org.hibernate.orm.test.embeddable; -import java.util.List; - -import org.hibernate.Session; -import org.hibernate.query.Query; - -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; - import jakarta.persistence.Basic; import jakarta.persistence.Embeddable; import jakarta.persistence.Embedded; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.OneToOne; +import org.hibernate.Session; +import org.hibernate.query.Query; +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.assertj.core.api.Assertions.assertThat; +import java.util.List; -public class MappedByEmbeddableTest extends BaseCoreFunctionalTestCase { +import static org.assertj.core.api.Assertions.assertThat; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Containing.class, Embed.class, Contained.class }; - } +@DomainModel(annotatedClasses = { + MappedByEmbeddableTest.Containing.class, + MappedByEmbeddableTest.Embed.class, + MappedByEmbeddableTest.Contained.class +}) +@SessionFactory +public class MappedByEmbeddableTest { @Test - public void smoke() { - inTransaction( session -> { + public void smoke(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( session -> { saveComposition( session, 1, "data - 1" ); saveComposition( session, 2, "data - 2" ); saveComposition( session, 3, "data - 3" ); } ); - inTransaction( session -> { + factoryScope.inTransaction( session -> { queryContaining( session, 1, "data - 1" ); queryContaining( session, 2, "data - 2" ); queryContaining( session, 3, "data - 3" ); } ); - inTransaction( session -> { + factoryScope.inTransaction( session -> { loadContaining( session, 1, 1 ); loadContaining( session, 2, 2 ); loadContaining( session, 3, 3 ); } ); - inTransaction( session -> { + factoryScope.inTransaction( session -> { Containing containing1 = session.getReference( Containing.class, 1 ); Containing containing2 = session.getReference( Containing.class, 2 ); @@ -68,19 +69,19 @@ public void smoke() { contained1.setContaining( containing2 ); } ); - inTransaction( session -> { + factoryScope.inTransaction( session -> { queryContaining( session, 2, "data - 1" ); queryContaining( session, 1, "data - 2" ); queryContaining( session, 3, "data - 3" ); } ); - inTransaction( session -> { + factoryScope.inTransaction( session -> { loadContaining( session, 2, 1 ); loadContaining( session, 1, 2 ); loadContaining( session, 3, 3 ); } ); - inTransaction( session -> { + factoryScope.inTransaction( session -> { Query query = session.createQuery( "select c from contained c", Contained.class ); List containeds = query.list(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/entityname/DuplicateEntityNameTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/entityname/DuplicateEntityNameTest.java index 0a979e766d03..ee99e3f5cf8c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/entityname/DuplicateEntityNameTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/entityname/DuplicateEntityNameTest.java @@ -7,45 +7,41 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; - import org.hibernate.DuplicateMappingException; - +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistry; 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.ServiceRegistryScope; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey( value = "HHH-13060" ) -public class DuplicateEntityNameTest extends BaseCoreFunctionalTestCase { - - protected Class[] getAnnotatedClasses() { - return new Class[] { - Purchase1.class, - Purchase2.class - }; - } - - @Override - protected void buildSessionFactory() { +@ServiceRegistry +public class DuplicateEntityNameTest { + @Test + void testIt(ServiceRegistryScope registryScope) { + final StandardServiceRegistry registry = registryScope.getRegistry(); try { - super.buildSessionFactory(); + new MetadataSources( registry ) + .addAnnotatedClasses( Purchase1.class, Purchase2.class ) + .buildMetadata(); fail("Should throw DuplicateMappingException"); } - catch (DuplicateMappingException e) { - assertEquals( "Entity classes [org.hibernate.orm.test.entityname.DuplicateEntityNameTest$Purchase1] and [org.hibernate.orm.test.entityname.DuplicateEntityNameTest$Purchase2] share the entity name 'Purchase' (entity names must be distinct)", e.getMessage() ); + catch (DuplicateMappingException expected) { + assertEquals( + "Entity classes [org.hibernate.orm.test.entityname.DuplicateEntityNameTest$Purchase1] and [org.hibernate.orm.test.entityname.DuplicateEntityNameTest$Purchase2] share the entity name 'Purchase' (entity names must be distinct)", + expected.getMessage() + ); } } - @Test - public void test() { - - } - @Entity(name = "Purchase") @Table(name="purchase_old") public static class Purchase1 { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/fetch/OneToOneOwnerByContainedEagerCyclesTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/fetch/OneToOneOwnerByContainedEagerCyclesTest.java index 333a55ed43cb..ffdb2f9d3a9c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/fetch/OneToOneOwnerByContainedEagerCyclesTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/fetch/OneToOneOwnerByContainedEagerCyclesTest.java @@ -4,34 +4,36 @@ */ package org.hibernate.orm.test.fetch; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; - -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; - -import org.junit.Test; - import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.OneToOne; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; - -public class OneToOneOwnerByContainedEagerCyclesTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Containing.class, Contained.class }; - } - - @Override - protected void configure(Configuration configuration) { - configuration.setProperty( AvailableSettings.MAX_FETCH_DEPTH, 2 ); +import static org.hibernate.cfg.FetchSettings.MAX_FETCH_DEPTH; + +@SuppressWarnings("JUnitMalformedDeclaration") +@ServiceRegistry(settings = @Setting(name=MAX_FETCH_DEPTH, value = "2")) +@DomainModel( annotatedClasses = { + OneToOneOwnerByContainedEagerCyclesTest.Containing.class, + OneToOneOwnerByContainedEagerCyclesTest.Contained.class +} ) +@SessionFactory +public class OneToOneOwnerByContainedEagerCyclesTest { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test - public void test() { - inTransaction( session -> { + public void test(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( session -> { Containing containing1 = new Containing(); containing1.setId( 1 ); @@ -74,8 +76,8 @@ public void test() { } ); // Test updating the value - inTransaction( session -> { - Contained contained = session.get( Contained.class, 5 ); + factoryScope.inTransaction( session -> { + Contained contained = session.find( Contained.class, 5 ); assertThat( contained ).isNotNull(); final Containing containing2 = contained.containing; assertThat( containing2 ).isNotNull(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/fetchprofiles/join/Course.java b/hibernate-core/src/test/java/org/hibernate/orm/test/fetchprofiles/join/Course.java index b92b8ded2ebf..0461b38a7acd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/fetchprofiles/join/Course.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/fetchprofiles/join/Course.java @@ -4,30 +4,28 @@ */ package org.hibernate.orm.test.fetchprofiles.join; - /** - * TODO : javadoc - * * @author Steve Ebersole */ public class Course { - private Long id; + private Integer id; private Code code; private String name; public Course() { } - public Course(Code code, String name) { + public Course(Integer id, Code code, String name) { + this.id = id; this.code = code; this.name = name; } - public Long getId() { + public Integer getId() { return id; } - public void setId(Long id) { + public void setId(Integer id) { this.id = id; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/fetchprofiles/join/CourseOffering.java b/hibernate-core/src/test/java/org/hibernate/orm/test/fetchprofiles/join/CourseOffering.java index b4f76bfa5aac..1be1d223f50b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/fetchprofiles/join/CourseOffering.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/fetchprofiles/join/CourseOffering.java @@ -7,31 +7,30 @@ import java.util.Set; /** - * TODO : javadoc - * * @author Steve Ebersole */ public class CourseOffering { - private Long id; + private Integer id; private Course course; private int semester; private int year; - private Set enrollments = new HashSet(); + private Set enrollments = new HashSet<>(); public CourseOffering() { } - public CourseOffering(Course course, int semester, int year) { + public CourseOffering(Integer id, Course course, int semester, int year) { + this.id = id; this.course = course; this.semester = semester; this.year = year; } - public Long getId() { + public Integer getId() { return id; } - public void setId(Long id) { + public void setId(Integer id) { this.id = id; } @@ -59,11 +58,11 @@ public void setYear(int year) { this.year = year; } - public Set getEnrollments() { + public Set getEnrollments() { return enrollments; } - public void setEnrollments(Set enrollments) { + public void setEnrollments(Set enrollments) { this.enrollments = enrollments; } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/fetchprofiles/join/Department.java b/hibernate-core/src/test/java/org/hibernate/orm/test/fetchprofiles/join/Department.java index f972e380dded..c55aaed2c27d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/fetchprofiles/join/Department.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/fetchprofiles/join/Department.java @@ -4,30 +4,28 @@ */ package org.hibernate.orm.test.fetchprofiles.join; - /** - * TODO : javadoc - * * @author Steve Ebersole */ public class Department { - private Long id; + private Integer id; private String code; private String name; public Department() { } - public Department(String code, String name) { + public Department(Integer id, String code, String name) { + this.id = id; this.code = code; this.name = name; } - public Long getId() { + public Integer getId() { return id; } - public void setId(Long id) { + public void setId(Integer id) { this.id = id; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/fetchprofiles/join/Enrollment.java b/hibernate-core/src/test/java/org/hibernate/orm/test/fetchprofiles/join/Enrollment.java index 6b8f2b3d580f..9dbb58a23014 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/fetchprofiles/join/Enrollment.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/fetchprofiles/join/Enrollment.java @@ -4,14 +4,11 @@ */ package org.hibernate.orm.test.fetchprofiles.join; - /** - * TODO : javadoc - * * @author Steve Ebersole */ public class Enrollment { - private Long id; + private Integer id; private CourseOffering offering; private Student student; private int finalGrade; @@ -19,16 +16,17 @@ public class Enrollment { public Enrollment() { } - public Enrollment(CourseOffering offering, Student student) { + public Enrollment(Integer id, CourseOffering offering, Student student) { + this.id = id; this.offering = offering; this.student = student; } - public Long getId() { + public Integer getId() { return id; } - public void setId(Long id) { + public void setId(Integer id) { this.id = id; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/fetchprofiles/join/JoinFetchProfileTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/fetchprofiles/join/JoinFetchProfileTest.java index dde954ad7e78..bac8f6f415e2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/fetchprofiles/join/JoinFetchProfileTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/fetchprofiles/join/JoinFetchProfileTest.java @@ -4,335 +4,217 @@ */ package org.hibernate.orm.test.fetchprofiles.join; -import java.util.List; import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; - import org.hibernate.Hibernate; -import org.hibernate.Session; import org.hibernate.UnknownProfileException; -import org.hibernate.cfg.Configuration; -import org.hibernate.cfg.Environment; -import org.hibernate.engine.spi.SessionImplementor; - -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.engine.spi.SessionFactoryImplementor; +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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import java.util.List; /** * Various tests related to join-style fetch profiles. * * @author Steve Ebersole */ -public class JoinFetchProfileTest extends BaseCoreFunctionalTestCase { - - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } - - @Override - public String[] getMappings() { - return new String[] { "fetchprofiles/join/Mappings.hbm.xml" }; - } - - public String getCacheConcurrencyStrategy() { - return null; - } - - public void configure(Configuration cfg) { - cfg.setProperty( Environment.GENERATE_STATISTICS, true ); - } - - @SuppressWarnings("unused") - private interface TestData { - Long getStudentId(); - - Long getDepartmentId(); - - Long getCourseId(); - - Long getSectionId(); - - Long getEnrollmentId(); - } - - private interface TestCode { - void perform(TestData data); - } - - @SuppressWarnings("unchecked") - private void performWithStandardData(TestCode testCode) { - final Department literatureDepartment = new Department( "lit", "Literature" ); - final Student me = new Student( "Steve" ); - final Course lit101 = new Course( new Course.Code( literatureDepartment, 101 ), "Introduction to Literature" ); - final CourseOffering section = new CourseOffering( lit101, 1, 2008 ); - final Enrollment enrollment = new Enrollment( section, me ); - inTransaction( - session -> { - session.persist( literatureDepartment ); - session.persist( lit101 ); - session.persist( section ); - session.persist( me ); - section.getEnrollments().add( enrollment ); - session.persist( enrollment ); - } - ); - - sessionFactory().getStatistics().clear(); - - testCode.perform( - new TestData() { - public Long getStudentId() { - return me.getId(); - } - - public Long getDepartmentId() { - return literatureDepartment.getId(); - } - - public Long getCourseId() { - return lit101.getId(); - } - - public Long getSectionId() { - return section.getId(); - } - - public Long getEnrollmentId() { - return enrollment.getId(); - } - } - ); - - inTransaction( - session -> { - session.remove( enrollment ); - session.remove( me ); - session.remove( enrollment.getOffering() ); - session.remove( enrollment.getOffering().getCourse() ); - session.remove( enrollment.getOffering().getCourse().getCode().getDepartment() ); - } - ); +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(xmlMappings = "mappings/fetchprofile/Mappings.hbm.xml") +@SessionFactory(generateStatistics = true) +public class JoinFetchProfileTest { + @BeforeEach + void createTestData(SessionFactoryScope sessions) { + final Department literatureDepartment = new Department( 1, "lit", "Literature" ); + final Student me = new Student( 1, "Steve" ); + final Course lit101 = new Course( 1, new Course.Code( literatureDepartment, 101 ), "Introduction to Literature" ); + final CourseOffering section = new CourseOffering( 1, lit101, 1, 2008 ); + final Enrollment enrollment = new Enrollment( 1, section, me ); + sessions.inTransaction( (session) -> { + session.persist( literatureDepartment ); + session.persist( lit101 ); + session.persist( section ); + session.persist( me ); + section.getEnrollments().add( enrollment ); + session.persist( enrollment ); + } ); + } + + @AfterEach + void dropTestsData(SessionFactoryScope sessions) { + sessions.dropData(); } @Test - public void testNormalLoading() { - performWithStandardData( - data -> - inTransaction( - session -> { - CourseOffering section = session.get( CourseOffering.class, data.getSectionId() ); - assertEquals( 1, sessionFactory().getStatistics().getEntityLoadCount() ); - assertEquals( 0, sessionFactory().getStatistics().getEntityFetchCount() ); - assertFalse( Hibernate.isInitialized( section.getCourse() ) ); - assertFalse( Hibernate.isInitialized( section.getEnrollments() ) ); - assertFalse( Hibernate.isInitialized( section.getCourse() - .getCode() - .getDepartment() ) ); - assertTrue( Hibernate.isInitialized( section.getCourse() ) ); - assertEquals( 1, sessionFactory().getStatistics().getEntityFetchCount() ); - } - ) - - ); + public void testNormalLoading(SessionFactoryScope sessions) { + var statistics = sessions.getSessionFactory().getStatistics(); + statistics.clear(); + + sessions.inTransaction( (session) -> { + CourseOffering section = session.get( CourseOffering.class, 1 ); + Assertions.assertEquals( 1, statistics.getEntityLoadCount() ); + Assertions.assertEquals( 0, statistics.getEntityFetchCount() ); + Assertions.assertFalse( Hibernate.isInitialized( section.getCourse() ) ); + Assertions.assertFalse( Hibernate.isInitialized( section.getEnrollments() ) ); + Assertions.assertFalse( Hibernate.isInitialized( section.getCourse() + .getCode() + .getDepartment() ) ); + Assertions.assertTrue( Hibernate.isInitialized( section.getCourse() ) ); + Assertions.assertEquals( 1, statistics.getEntityFetchCount() ); + } ); } @Test - public void testNormalCriteria() { - performWithStandardData( - data -> - inTransaction( - session -> { - CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); - CriteriaQuery criteria = criteriaBuilder.createQuery( CourseOffering.class ); - criteria.from( CourseOffering.class ); - CourseOffering section = session.createQuery( criteria ).uniqueResult(); -// CourseOffering section = ( CourseOffering ) session.createCriteria( CourseOffering.class ).uniqueResult(); - assertEquals( 1, sessionFactory().getStatistics().getEntityLoadCount() ); - assertEquals( 0, sessionFactory().getStatistics().getEntityFetchCount() ); - assertFalse( Hibernate.isInitialized( section.getCourse() ) ); - assertFalse( Hibernate.isInitialized( section.getEnrollments() ) ); - assertFalse( Hibernate.isInitialized( section.getCourse() - .getCode() - .getDepartment() ) ); - assertTrue( Hibernate.isInitialized( section.getCourse() ) ); - assertEquals( 1, sessionFactory().getStatistics().getEntityFetchCount() ); - } - ) - ); + public void testNormalCriteria(SessionFactoryScope sessions) { + var statistics = sessions.getSessionFactory().getStatistics(); + statistics.clear(); + + sessions.inTransaction( (session) -> { + CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); + CriteriaQuery criteria = criteriaBuilder.createQuery( CourseOffering.class ); + criteria.from( CourseOffering.class ); + CourseOffering section = session.createQuery( criteria ).uniqueResult(); + Assertions.assertEquals( 1, statistics.getEntityLoadCount() ); + Assertions.assertEquals( 0, statistics.getEntityFetchCount() ); + Assertions.assertFalse( Hibernate.isInitialized( section.getCourse() ) ); + Assertions.assertFalse( Hibernate.isInitialized( section.getEnrollments() ) ); + Assertions.assertFalse( Hibernate.isInitialized( section.getCourse() + .getCode() + .getDepartment() ) ); + Assertions.assertTrue( Hibernate.isInitialized( section.getCourse() ) ); + Assertions.assertEquals( 1, statistics.getEntityFetchCount() ); + } ); } @Test - public void testBasicFetchProfileOperation() { - assertTrue( - "fetch profile not parsed properly", - sessionFactory().containsFetchProfileDefinition( "enrollment.details" ) - ); - assertTrue( - "fetch profile not parsed properly", - sessionFactory().containsFetchProfileDefinition( "offering.details" ) - ); - assertTrue( - "fetch profile not parsed properly", - sessionFactory().containsFetchProfileDefinition( "course.details" ) - ); - Session s = openSession(); - SessionImplementor si = (SessionImplementor) s; - s.enableFetchProfile( "enrollment.details" ); - assertTrue( si.getLoadQueryInfluencers().hasEnabledFetchProfiles() ); - s.disableFetchProfile( "enrollment.details" ); - assertFalse( si.getLoadQueryInfluencers().hasEnabledFetchProfiles() ); - try { - s.enableFetchProfile( "never-gonna-get-it" ); - fail( "expecting failure on undefined fetch-profile" ); - } - catch (UnknownProfileException expected) { - } - s.close(); + public void testBasicFetchProfileOperation(SessionFactoryScope sessions) { + final SessionFactoryImplementor sessionFactory = sessions.getSessionFactory(); + + Assertions.assertTrue( sessionFactory.containsFetchProfileDefinition( "enrollment.details" ), + "fetch profile not parsed properly" ); + Assertions.assertTrue( sessionFactory.containsFetchProfileDefinition( "offering.details" ), + "fetch profile not parsed properly" ); + Assertions.assertTrue( sessionFactory.containsFetchProfileDefinition( "course.details" ), + "fetch profile not parsed properly" ); + + sessions.inTransaction( (session) -> { + session.enableFetchProfile( "enrollment.details" ); + Assertions.assertTrue( session.getLoadQueryInfluencers().hasEnabledFetchProfiles() ); + session.disableFetchProfile( "enrollment.details" ); + Assertions.assertFalse( session.getLoadQueryInfluencers().hasEnabledFetchProfiles() ); + try { + session.enableFetchProfile( "never-gonna-get-it" ); + Assertions.fail( "expecting failure on undefined fetch-profile" ); + } + catch (UnknownProfileException expected) { + } + } ); } @Test - public void testLoadManyToOneFetchProfile() { - performWithStandardData( - data -> - inTransaction( - session -> { - session.enableFetchProfile( "enrollment.details" ); - Enrollment enrollment = session.get( - Enrollment.class, - data.getEnrollmentId() - ); - assertEquals( - 3, - sessionFactory().getStatistics().getEntityLoadCount() - ); // enrollment + (section + student) - assertEquals( 0, sessionFactory().getStatistics().getEntityFetchCount() ); - assertTrue( Hibernate.isInitialized( enrollment.getOffering() ) ); - assertTrue( Hibernate.isInitialized( enrollment.getStudent() ) ); - assertEquals( 0, sessionFactory().getStatistics().getEntityFetchCount() ); - } - ) - ); + public void testLoadManyToOneFetchProfile(SessionFactoryScope sessions) { + var statistics = sessions.getSessionFactory().getStatistics(); + statistics.clear(); + + sessions.inTransaction( (session) -> { + session.enableFetchProfile( "enrollment.details" ); + Enrollment enrollment = session.find( Enrollment.class, 1 ); + // enrollment + (section + student) + Assertions.assertEquals( 3, statistics.getEntityLoadCount() ); + Assertions.assertEquals( 0, statistics.getEntityFetchCount() ); + Assertions.assertTrue( Hibernate.isInitialized( enrollment.getOffering() ) ); + Assertions.assertTrue( Hibernate.isInitialized( enrollment.getStudent() ) ); + Assertions.assertEquals( 0, statistics.getEntityFetchCount() ); + } ); } @Test - public void testCriteriaManyToOneFetchProfile() { - performWithStandardData( - data -> - inTransaction( - session -> { - session.enableFetchProfile( "enrollment.details" ); - CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); - CriteriaQuery criteria = criteriaBuilder.createQuery( Enrollment.class ); - criteria.from( Enrollment.class ); - Enrollment enrollment = session.createQuery( criteria ).uniqueResult(); -// Enrollment enrollment = ( Enrollment ) session.createCriteria( Enrollment.class ).uniqueResult(); - assertEquals( - 3, - sessionFactory().getStatistics().getEntityLoadCount() - ); // enrollment + (section + student) - assertEquals( 0, sessionFactory().getStatistics().getEntityFetchCount() ); - assertTrue( Hibernate.isInitialized( enrollment.getOffering() ) ); - assertTrue( Hibernate.isInitialized( enrollment.getStudent() ) ); - assertEquals( 0, sessionFactory().getStatistics().getEntityFetchCount() ); - - } - ) - - ); + public void testCriteriaManyToOneFetchProfile(SessionFactoryScope sessions) { + var statistics = sessions.getSessionFactory().getStatistics(); + statistics.clear(); + + sessions.inTransaction( (session) -> { + session.enableFetchProfile( "enrollment.details" ); + CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); + CriteriaQuery criteria = criteriaBuilder.createQuery( Enrollment.class ); + criteria.from( Enrollment.class ); + Enrollment enrollment = session.createQuery( criteria ).uniqueResult(); + // enrollment + (section + student) + Assertions.assertEquals( 3, statistics.getEntityLoadCount() ); + Assertions.assertEquals( 0, statistics.getEntityFetchCount() ); + Assertions.assertTrue( Hibernate.isInitialized( enrollment.getOffering() ) ); + Assertions.assertTrue( Hibernate.isInitialized( enrollment.getStudent() ) ); + Assertions.assertEquals( 0, statistics.getEntityFetchCount() ); + } ); } @Test - public void testLoadOneToManyFetchProfile() { - performWithStandardData( - data -> - inTransaction( - session -> { - session.enableFetchProfile( "offering.details" ); - CourseOffering section = session.get( - CourseOffering.class, - data.getSectionId() - ); - assertEquals( - 3, - sessionFactory().getStatistics().getEntityLoadCount() - ); // section + (enrollments + course) - assertEquals( 0, sessionFactory().getStatistics().getEntityFetchCount() ); - assertTrue( Hibernate.isInitialized( section.getEnrollments() ) ); - } - ) + public void testLoadOneToManyFetchProfile(SessionFactoryScope sessions) { + var statistics = sessions.getSessionFactory().getStatistics(); + statistics.clear(); - ); + sessions.inTransaction( (session) -> { + session.enableFetchProfile( "offering.details" ); + CourseOffering section = session.find( CourseOffering.class, 1 ); + // section + (enrollments + course) + Assertions.assertEquals( 3, statistics.getEntityLoadCount() ); + Assertions.assertEquals( 0, statistics.getEntityFetchCount() ); + Assertions.assertTrue( Hibernate.isInitialized( section.getEnrollments() ) ); + } ); } @Test - public void testLoadDeepFetchProfile() { - performWithStandardData( - data -> - inTransaction( - session -> { - // enable both enrollment and offering detail profiles; - // then loading the section/offering should fetch the enrollment - // which in turn should fetch student (+ offering). - session.enableFetchProfile( "offering.details" ); - session.enableFetchProfile( "enrollment.details" ); - CourseOffering section = session.get( - CourseOffering.class, - data.getSectionId() - ); - assertEquals( - 4, - sessionFactory().getStatistics().getEntityLoadCount() - ); // section + (course + enrollments + (student)) - assertEquals( 0, sessionFactory().getStatistics().getEntityFetchCount() ); - assertTrue( Hibernate.isInitialized( section.getEnrollments() ) ); - } - ) - - ); + public void testLoadDeepFetchProfile(SessionFactoryScope sessions) { + var statistics = sessions.getSessionFactory().getStatistics(); + statistics.clear(); + + sessions.inTransaction( (session) -> { + // enable both enrollment and offering detail profiles; + // then loading the section/offering should fetch the enrollment + // which in turn should fetch student (+ offering). + session.enableFetchProfile( "offering.details" ); + session.enableFetchProfile( "enrollment.details" ); + CourseOffering section = session.find( CourseOffering.class, 1 ); + // section + (course + enrollments + (student)) + Assertions.assertEquals( 4, statistics.getEntityLoadCount() ); + Assertions.assertEquals( 0, statistics.getEntityFetchCount() ); + Assertions.assertTrue( Hibernate.isInitialized( section.getEnrollments() ) ); + } ); } @Test - public void testLoadComponentDerefFetchProfile() { - performWithStandardData( - data -> - inTransaction( - session -> { - session.enableFetchProfile( "course.details" ); - Course course = session.get( Course.class, data.getCourseId() ); - assertEquals( - 2, - sessionFactory().getStatistics().getEntityLoadCount() - ); // course + department - assertEquals( 0, sessionFactory().getStatistics().getEntityFetchCount() ); - assertTrue( Hibernate.isInitialized( course.getCode().getDepartment() ) ); - } - ) + public void testLoadComponentDerefFetchProfile(SessionFactoryScope sessions) { + var statistics = sessions.getSessionFactory().getStatistics(); + statistics.clear(); - ); + sessions.inTransaction( (session) -> { + session.enableFetchProfile( "course.details" ); + Course course = session.find( Course.class, 1 ); + // course + department + Assertions.assertEquals( 2, statistics.getEntityLoadCount() ); + Assertions.assertEquals( 0, statistics.getEntityFetchCount() ); + Assertions.assertTrue( Hibernate.isInitialized( course.getCode().getDepartment() ) ); + } ); } @Test - public void testHQL() { - performWithStandardData( - data -> - inTransaction( - session -> { - session.enableFetchProfile( "offering.details" ); - session.enableFetchProfile( "enrollment.details" ); - List sections = session.createQuery( "from CourseOffering" ).list(); - int sectionCount = sections.size(); - assertEquals( "unexpected CourseOffering count", 1, sectionCount ); - assertEquals( 4, sessionFactory().getStatistics().getEntityLoadCount() ); - assertEquals( 0, sessionFactory().getStatistics().getEntityFetchCount() ); - } - ) - - ); + public void testHQL(SessionFactoryScope sessions) { + var statistics = sessions.getSessionFactory().getStatistics(); + statistics.clear(); + + sessions.inTransaction( (session) -> { + session.enableFetchProfile( "offering.details" ); + session.enableFetchProfile( "enrollment.details" ); + List sections = session.createQuery( "from CourseOffering" ).list(); + int sectionCount = sections.size(); + Assertions.assertEquals( 1, sectionCount, "unexpected CourseOffering count" ); + Assertions.assertEquals( 4, statistics.getEntityLoadCount() ); + Assertions.assertEquals( 0, statistics.getEntityFetchCount() ); + } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/fetchprofiles/join/Student.java b/hibernate-core/src/test/java/org/hibernate/orm/test/fetchprofiles/join/Student.java index de99934bf03d..a113cbe16352 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/fetchprofiles/join/Student.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/fetchprofiles/join/Student.java @@ -4,28 +4,26 @@ */ package org.hibernate.orm.test.fetchprofiles.join; - /** - * TODO : javadoc - * * @author Steve Ebersole */ public class Student { - private Long id; + private Integer id; private String name; public Student() { } - public Student(String name) { + public Student(Integer id, String name) { + this.id = id; this.name = name; } - public Long getId() { + public Integer getId() { return id; } - public void setId(Long id) { + public void setId(Integer id) { this.id = id; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/fetchstrategyhelper/FetchStrategyHelperTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/fetchstrategyhelper/FetchStrategyHelperTest.java index c9bd0c232ce1..d76434d69b22 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/fetchstrategyhelper/FetchStrategyHelperTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/fetchstrategyhelper/FetchStrategyHelperTest.java @@ -4,187 +4,207 @@ */ package org.hibernate.orm.test.fetchstrategyhelper; -import java.util.HashSet; -import java.util.Set; - +import jakarta.persistence.ElementCollection; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import org.hibernate.engine.FetchStyle; import org.hibernate.engine.FetchTiming; +import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.metamodel.mapping.internal.FetchOptionsHelper; import org.hibernate.persister.entity.AbstractEntityPersister; +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.AssociationType; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; - -import jakarta.persistence.ElementCollection; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.Id; -import jakarta.persistence.ManyToOne; -import jakarta.persistence.Table; - -import static org.junit.Assert.assertSame; +import java.util.HashSet; +import java.util.Set; /** * @author Gail Badner */ -public class FetchStrategyHelperTest extends BaseCoreFunctionalTestCase { - - +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(annotatedClasses = { + FetchStrategyHelperTest.AnEntity.class, + FetchStrategyHelperTest.OtherEntity.class +}) +@SessionFactory +public class FetchStrategyHelperTest { @Test - public void testManyToOneDefaultFetch() { - final AssociationType associationType = determineAssociationType( AnEntity.class, "otherEntityDefault" ); - final org.hibernate.FetchMode fetchMode = determineFetchMode( AnEntity.class, "otherEntityDefault" ); - assertSame( org.hibernate.FetchMode.JOIN, fetchMode ); + public void testManyToOneDefaultFetch(SessionFactoryScope factoryScope) { + final SessionFactoryImplementor sessionFactory = factoryScope.getSessionFactory(); + + final AssociationType associationType = determineAssociationType( AnEntity.class, "otherEntityDefault", sessionFactory ); + final org.hibernate.FetchMode fetchMode = determineFetchMode( AnEntity.class, "otherEntityDefault", sessionFactory ); + Assertions.assertSame( org.hibernate.FetchMode.JOIN, fetchMode ); final FetchStyle fetchStyle = FetchOptionsHelper.determineFetchStyleByMetadata( fetchMode, associationType, - sessionFactory() + sessionFactory ); - assertSame( FetchStyle.JOIN, fetchStyle ); + Assertions.assertSame( FetchStyle.JOIN, fetchStyle ); final FetchTiming fetchTiming = FetchOptionsHelper.determineFetchTiming( fetchStyle, associationType, - sessionFactory() + sessionFactory ); - assertSame( FetchTiming.IMMEDIATE, fetchTiming ); + Assertions.assertSame( FetchTiming.IMMEDIATE, fetchTiming ); } @Test - public void testManyToOneJoinFetch() { - final AssociationType associationType = determineAssociationType( AnEntity.class, "otherEntityJoin" ); - final org.hibernate.FetchMode fetchMode = determineFetchMode( AnEntity.class, "otherEntityJoin" ); - assertSame( org.hibernate.FetchMode.JOIN, fetchMode ); + public void testManyToOneJoinFetch(SessionFactoryScope factoryScope) { + final SessionFactoryImplementor sessionFactory = factoryScope.getSessionFactory(); + + final AssociationType associationType = determineAssociationType( AnEntity.class, "otherEntityJoin", sessionFactory ); + final org.hibernate.FetchMode fetchMode = determineFetchMode( AnEntity.class, "otherEntityJoin", sessionFactory ); + Assertions.assertSame( org.hibernate.FetchMode.JOIN, fetchMode ); final FetchStyle fetchStyle = FetchOptionsHelper.determineFetchStyleByMetadata( fetchMode, associationType, - sessionFactory() + sessionFactory ); - assertSame( FetchStyle.JOIN, fetchStyle ); + Assertions.assertSame( FetchStyle.JOIN, fetchStyle ); final FetchTiming fetchTiming = FetchOptionsHelper.determineFetchTiming( fetchStyle, associationType, - sessionFactory() + sessionFactory ); - assertSame( FetchTiming.IMMEDIATE, fetchTiming ); + Assertions.assertSame( FetchTiming.IMMEDIATE, fetchTiming ); } @Test - public void testManyToOneSelectFetch() { - final AssociationType associationType = determineAssociationType( AnEntity.class, "otherEntitySelect" ); - final org.hibernate.FetchMode fetchMode = determineFetchMode( AnEntity.class, "otherEntitySelect" ); - assertSame( org.hibernate.FetchMode.SELECT, fetchMode ); + public void testManyToOneSelectFetch(SessionFactoryScope factoryScope) { + final SessionFactoryImplementor sessionFactory = factoryScope.getSessionFactory(); + + final AssociationType associationType = determineAssociationType( AnEntity.class, "otherEntitySelect", sessionFactory ); + final org.hibernate.FetchMode fetchMode = determineFetchMode( AnEntity.class, "otherEntitySelect", sessionFactory ); + Assertions.assertSame( org.hibernate.FetchMode.SELECT, fetchMode ); final FetchStyle fetchStyle = FetchOptionsHelper.determineFetchStyleByMetadata( fetchMode, associationType, - sessionFactory() + sessionFactory ); - assertSame( FetchStyle.SELECT, fetchStyle ); + Assertions.assertSame( FetchStyle.SELECT, fetchStyle ); final FetchTiming fetchTiming = FetchOptionsHelper.determineFetchTiming( fetchStyle, associationType, - sessionFactory() + sessionFactory ); - assertSame( FetchTiming.DELAYED, fetchTiming ); + Assertions.assertSame( FetchTiming.DELAYED, fetchTiming ); } @Test - public void testCollectionDefaultFetch() { - final AssociationType associationType = determineAssociationType( AnEntity.class, "colorsDefault" ); - final org.hibernate.FetchMode fetchMode = determineFetchMode( AnEntity.class, "colorsDefault" ); - assertSame( org.hibernate.FetchMode.SELECT, fetchMode ); + public void testCollectionDefaultFetch(SessionFactoryScope factoryScope) { + final SessionFactoryImplementor sessionFactory = factoryScope.getSessionFactory(); + + final AssociationType associationType = determineAssociationType( AnEntity.class, "colorsDefault", sessionFactory ); + final org.hibernate.FetchMode fetchMode = determineFetchMode( AnEntity.class, "colorsDefault", sessionFactory ); + Assertions.assertSame( org.hibernate.FetchMode.SELECT, fetchMode ); final FetchStyle fetchStyle = FetchOptionsHelper.determineFetchStyleByMetadata( fetchMode, associationType, - sessionFactory() + sessionFactory ); - assertSame( FetchStyle.SELECT, fetchStyle ); + Assertions.assertSame( FetchStyle.SELECT, fetchStyle ); final FetchTiming fetchTiming = FetchOptionsHelper.determineFetchTiming( fetchStyle, associationType, - sessionFactory() + sessionFactory ); - assertSame( FetchTiming.DELAYED, fetchTiming ); + Assertions.assertSame( FetchTiming.DELAYED, fetchTiming ); } @Test - public void testCollectionJoinFetch() { - final AssociationType associationType = determineAssociationType( AnEntity.class, "colorsJoin" ); - final org.hibernate.FetchMode fetchMode = determineFetchMode( AnEntity.class, "colorsJoin" ); - assertSame( org.hibernate.FetchMode.JOIN, fetchMode ); + public void testCollectionJoinFetch(SessionFactoryScope factoryScope) { + final SessionFactoryImplementor sessionFactory = factoryScope.getSessionFactory(); + + final AssociationType associationType = determineAssociationType( AnEntity.class, "colorsJoin", sessionFactory ); + final org.hibernate.FetchMode fetchMode = determineFetchMode( AnEntity.class, "colorsJoin", sessionFactory ); + Assertions.assertSame( org.hibernate.FetchMode.JOIN, fetchMode ); final FetchStyle fetchStyle = FetchOptionsHelper.determineFetchStyleByMetadata( fetchMode, associationType, - sessionFactory() + sessionFactory ); - assertSame( FetchStyle.JOIN, fetchStyle ); + Assertions.assertSame( FetchStyle.JOIN, fetchStyle ); final FetchTiming fetchTiming = FetchOptionsHelper.determineFetchTiming( fetchStyle, associationType, - sessionFactory() + sessionFactory ); - assertSame( FetchTiming.IMMEDIATE, fetchTiming ); + Assertions.assertSame( FetchTiming.IMMEDIATE, fetchTiming ); } @Test - public void testCollectionSelectFetch() { - final AssociationType associationType = determineAssociationType( AnEntity.class, "colorsSelect" ); - final org.hibernate.FetchMode fetchMode = determineFetchMode( AnEntity.class, "colorsSelect" ); - assertSame( org.hibernate.FetchMode.SELECT, fetchMode ); + public void testCollectionSelectFetch(SessionFactoryScope factoryScope) { + final SessionFactoryImplementor sessionFactory = factoryScope.getSessionFactory(); + + final AssociationType associationType = determineAssociationType( AnEntity.class, "colorsSelect", sessionFactory ); + final org.hibernate.FetchMode fetchMode = determineFetchMode( AnEntity.class, "colorsSelect", sessionFactory ); + Assertions.assertSame( org.hibernate.FetchMode.SELECT, fetchMode ); final FetchStyle fetchStyle = FetchOptionsHelper.determineFetchStyleByMetadata( fetchMode, associationType, - sessionFactory() + sessionFactory ); - assertSame( FetchStyle.SELECT, fetchStyle ); + Assertions.assertSame( FetchStyle.SELECT, fetchStyle ); final FetchTiming fetchTiming = FetchOptionsHelper.determineFetchTiming( fetchStyle, associationType, - sessionFactory() + sessionFactory ); - assertSame( FetchTiming.DELAYED, fetchTiming ); + Assertions.assertSame( FetchTiming.DELAYED, fetchTiming ); } @Test - public void testCollectionSubselectFetch() { - final AssociationType associationType = determineAssociationType( AnEntity.class, "colorsSubselect" ); - final org.hibernate.FetchMode fetchMode = determineFetchMode( AnEntity.class, "colorsSubselect" ); - assertSame( org.hibernate.FetchMode.SELECT, fetchMode ); + public void testCollectionSubselectFetch(SessionFactoryScope factoryScope) { + final SessionFactoryImplementor sessionFactory = factoryScope.getSessionFactory(); + + final AssociationType associationType = determineAssociationType( AnEntity.class, "colorsSubselect", sessionFactory ); + final org.hibernate.FetchMode fetchMode = determineFetchMode( AnEntity.class, "colorsSubselect", sessionFactory ); + Assertions.assertSame( org.hibernate.FetchMode.SELECT, fetchMode ); final FetchStyle fetchStyle = FetchOptionsHelper.determineFetchStyleByMetadata( fetchMode, associationType, - sessionFactory() + sessionFactory ); - assertSame( FetchStyle.SUBSELECT, fetchStyle ); + Assertions.assertSame( FetchStyle.SUBSELECT, fetchStyle ); final FetchTiming fetchTiming = FetchOptionsHelper.determineFetchTiming( fetchStyle, associationType, - sessionFactory() + sessionFactory ); - assertSame( FetchTiming.DELAYED, fetchTiming ); + Assertions.assertSame( FetchTiming.DELAYED, fetchTiming ); } - private org.hibernate.FetchMode determineFetchMode(Class entityClass, String path) { + private org.hibernate.FetchMode determineFetchMode( + @SuppressWarnings("SameParameterValue") Class entityClass, + String path, + SessionFactoryImplementor sessionFactory) { AbstractEntityPersister entityPersister = (AbstractEntityPersister) - sessionFactory().getMappingMetamodel().getEntityDescriptor(entityClass.getName()); + sessionFactory.getMappingMetamodel().getEntityDescriptor(entityClass.getName()); + //noinspection removal int index = entityPersister.getPropertyIndex( path ); return entityPersister.getFetchMode( index ); } - private AssociationType determineAssociationType(Class entityClass, String path) { + private AssociationType determineAssociationType( + @SuppressWarnings("SameParameterValue") Class entityClass, + String path, + SessionFactoryImplementor sessionFactory) { AbstractEntityPersister entityPersister = (AbstractEntityPersister) - sessionFactory().getMappingMetamodel().getEntityDescriptor(entityClass.getName()); + sessionFactory.getMappingMetamodel().getEntityDescriptor(entityClass.getName()); + //noinspection removal int index = entityPersister.getPropertyIndex( path ); return (AssociationType) entityPersister.getSubclassPropertyType( index ); } - protected Class[] getAnnotatedClasses() { - return new Class[] { - AnEntity.class, - OtherEntity.class - }; - } @jakarta.persistence.Entity @Table(name="entity") public static class AnEntity { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/BulkManipulationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/BulkManipulationTest.java index b7aab70829db..935b72d3ed91 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/BulkManipulationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/BulkManipulationTest.java @@ -4,584 +4,474 @@ */ package org.hibernate.orm.test.hql; -import java.sql.ResultSet; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.TreeSet; - +import junit.framework.AssertionFailedError; import org.hibernate.QueryException; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.AvailableSettings; import org.hibernate.community.dialect.InformixDialect; import org.hibernate.dialect.AbstractTransactSQLDialect; import org.hibernate.dialect.CockroachDialect; import org.hibernate.dialect.H2Dialect; import org.hibernate.dialect.MySQLDialect; import org.hibernate.exception.ConstraintViolationException; +import org.hibernate.generator.Generator; import org.hibernate.id.BulkInsertionCapableIdentifierGenerator; -import org.hibernate.metamodel.CollectionClassification; import org.hibernate.persister.entity.EntityPersister; -import org.hibernate.query.Query; - -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; -import org.hibernate.testing.SkipForDialect; +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.generator.Generator; -import org.junit.Test; +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.Setting; +import org.hibernate.testing.orm.junit.SkipForDialect; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assumptions; -import junit.framework.AssertionFailedError; +import org.junit.jupiter.api.Test; + +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.TreeSet; +import static org.hibernate.cfg.MappingSettings.DEFAULT_LIST_SEMANTICS; 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; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests execution of bulk UPDATE/DELETE statements through the new AST parser. * * @author Steve Ebersole */ -public class BulkManipulationTest extends BaseCoreFunctionalTestCase { - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } - - @Override - public String[] getMappings() { - return new String[] { - "hql/Animal.hbm.xml", - "hql/Vehicle.hbm.xml", - "hql/KeyManyToOneEntity.hbm.xml", - "hql/Versions.hbm.xml", - "hql/FooBarCopy.hbm.xml", - "/org/hibernate/orm/test/legacy/Multi.hbm.xml", - "hql/EntityWithCrazyCompositeKey.hbm.xml", - "hql/SimpleEntityWithAssociation.hbm.xml", - "hql/BooleanLiteralEntity.hbm.xml", - "hql/CompositeIdEntity.hbm.xml" - }; - } - - protected Class[] getAnnotatedClasses() { - return new Class[] { Farm.class, Crop.class }; - } - - - @Override - protected void prepareBasicRegistryBuilder(StandardServiceRegistryBuilder builer) { - super.prepareBasicRegistryBuilder( builer ); - builer.applySetting( AvailableSettings.DEFAULT_LIST_SEMANTICS, CollectionClassification.BAG ); - } +@SuppressWarnings("JUnitMalformedDeclaration") +@ServiceRegistry(settings = @Setting(name=DEFAULT_LIST_SEMANTICS, value = "bag")) +@DomainModel( + annotatedClasses = { Farm.class, Crop.class }, + xmlMappings = { + "org/hibernate/orm/test/hql/Animal.hbm.xml", + "org/hibernate/orm/test/hql/Vehicle.hbm.xml", + "org/hibernate/orm/test/hql/KeyManyToOneEntity.hbm.xml", + "org/hibernate/orm/test/hql/Versions.hbm.xml", + "org/hibernate/orm/test/hql/FooBarCopy.hbm.xml", + "org/hibernate/orm/test/hql/EntityWithCrazyCompositeKey.hbm.xml", + "org/hibernate/orm/test/hql/SimpleEntityWithAssociation.hbm.xml", + "org/hibernate/orm/test/hql/BooleanLiteralEntity.hbm.xml", + "org/hibernate/orm/test/hql/CompositeIdEntity.hbm.xml", + "/org/hibernate/orm/test/legacy/Multi.hbm.xml" + } +) +@SessionFactory +public class BulkManipulationTest { - @Test - @SkipForDialect(value = CockroachDialect.class, comment = "https://github.com/cockroachdb/cockroach/issues/41943") - public void testUpdateWithSubquery() { - Session s = openSession(); - s.beginTransaction(); - - // just checking parsing and syntax... - s.createQuery( "update Human h set h.bodyWeight = h.bodyWeight + (select count(1) from IntegerVersioned)" ) - .executeUpdate(); - s.createQuery( - "update Human h set h.bodyWeight = h.bodyWeight + (select count(1) from IntegerVersioned) where h.description = 'abc'" ) - .executeUpdate(); - - s.getTransaction().commit(); - s.close(); + @AfterEach + void tearDown(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test - public void testDeleteNonExistentEntity() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - try { - s.createQuery( "delete NonExistentEntity" ).executeUpdate(); - fail( "no exception thrown" ); - } - catch (IllegalArgumentException e) { - assertTyping( QueryException.class, e.getCause() ); - } - catch (QueryException ignore) { - } - - t.commit(); - s.close(); + @SkipForDialect(dialectClass = CockroachDialect.class, + reason = "https://github.com/cockroachdb/cockroach/issues/41943") + public void testUpdateWithSubquery(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + // just checking parsing and syntax... + session.createQuery( "update Human h set h.bodyWeight = h.bodyWeight + (select count(1) from IntegerVersioned)" ) + .executeUpdate(); + session.createQuery( + "update Human h set h.bodyWeight = h.bodyWeight + (select count(1) from IntegerVersioned) where h.description = 'abc'" ) + .executeUpdate(); + } ); } @Test - public void testUpdateNonExistentEntity() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - try { - s.createQuery( "update NonExistentEntity e set e.someProp = ?" ).executeUpdate(); - fail( "no exception thrown" ); - } - catch (IllegalArgumentException e) { - assertTyping( QueryException.class, e.getCause() ); - } - catch (QueryException e) { - } - finally { - if ( s.getTransaction().isActive() ) { - s.getTransaction().rollback(); + public void testDeleteNonExistentEntity(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + try { + session.createQuery( "delete NonExistentEntity" ).executeUpdate(); + Assertions.fail( "no exception thrown" ); } - s.close(); - } + catch (IllegalArgumentException e) { + assertTyping( QueryException.class, e.getCause() ); + } + catch (QueryException ignore) { + } + } ); } @Test - @RequiresDialectFeature(DialectChecks.SupportsTemporaryTable.class) - public void testTempTableGenerationIsolation() throws Throwable { - Session s = openSession(); - s.beginTransaction(); - - Truck truck = new Truck(); - truck.setVin( "123t" ); - truck.setOwner( "Steve" ); - s.persist( truck ); - - // manually flush the session to ensure the insert happens - s.flush(); - - // now issue a bulk delete against Car which should force the temp table to be - // created. we need to test to ensure that this does not cause the transaction - // to be committed... - s.createQuery( "delete from Vehicle" ).executeUpdate(); - - s.getTransaction().rollback(); - s.close(); - - s = openSession(); - s.beginTransaction(); - List list = s.createQuery( "from Car" ).list(); - assertEquals( "temp table gen caused premature commit", 0, list.size() ); - s.createQuery( "delete from Car" ).executeUpdate(); - s.getTransaction().rollback(); - s.close(); + public void testUpdateNonExistentEntity(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + try { + session.createQuery( "update NonExistentEntity e set e.someProp = ?" ).executeUpdate(); + Assertions.fail( "no exception thrown" ); + } + catch (IllegalArgumentException e) { + assertTyping( QueryException.class, e.getCause() ); + } + catch (QueryException expected) { + } + } ); } @Test - public void testBooleanHandlingBaseline() { - TestData data = new TestData(); - data.prepare(); - - inTransaction( - s -> { - final String qryString = "select e from BooleanLiteralEntity e where e.yesNoBoolean = :p"; - final Query query = s.createQuery( qryString ).setParameter( "p", true ); - query.list(); - } - ); - - data.cleanup(); + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsTemporaryTable.class) + public void testTempTableGenerationIsolation(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + Truck truck = new Truck(); + truck.setVin( "123t" ); + truck.setOwner( "Steve" ); + session.persist( truck ); + + // manually flush the session to ensure the insert happens + session.flush(); + + // now issue a bulk delete against Car which should force the temp table to be + // created. we need to test to ensure that this does not cause the transaction + // to be committed... + session.createMutationQuery( "delete from Vehicle" ).executeUpdate(); + } ); + + factoryScope.inTransaction( (session) -> { + var list = session.createQuery( "from Car" ).list(); + assertEquals( 0, list.size(), "temp table gen caused premature commit" ); + } ); } @Test - public void testBooleanHandling() { + public void testBooleanHandling(SessionFactoryScope factoryScope) { TestData data = new TestData(); - data.prepare(); - - inTransaction( - s -> { - // currently, we need the three different binds because they are different underlying types... - int count = s.createQuery( - "update BooleanLiteralEntity set yesNoBoolean = :b1, trueFalseBoolean = :b2, zeroOneBoolean = :b3" ) - .setParameter( "b1", true ) - .setParameter( "b2", true ) - .setParameter( "b3", true ) - .executeUpdate(); - assertEquals( 1, count ); - BooleanLiteralEntity entity = (BooleanLiteralEntity) s.createQuery( "from BooleanLiteralEntity" ) - .uniqueResult(); - assertTrue( entity.isYesNoBoolean() ); - assertTrue( entity.isTrueFalseBoolean() ); - assertTrue( entity.isZeroOneBoolean() ); - s.clear(); - - count = s.createQuery( - "update BooleanLiteralEntity set yesNoBoolean = true, trueFalseBoolean = true, zeroOneBoolean = true" ) - .executeUpdate(); - assertEquals( 1, count ); - entity = (BooleanLiteralEntity) s.createQuery( "from BooleanLiteralEntity" ).uniqueResult(); - assertTrue( entity.isYesNoBoolean() ); - assertTrue( entity.isTrueFalseBoolean() ); - assertTrue( entity.isZeroOneBoolean() ); + data.prepare( factoryScope ); + + // baseline check... + factoryScope.inTransaction( (session) -> { + session.createQuery( "select e from BooleanLiteralEntity e where e.yesNoBoolean = :p" ) + .setParameter( "p", true ) + .list(); + } ); + + factoryScope.inTransaction( (session) -> { + // currently, we need the three different binds because they are different underlying types... + var hql = """ + update BooleanLiteralEntity + set yesNoBoolean = :b1, + trueFalseBoolean = :b2, + zeroOneBoolean = :b3 + """; + int count = session.createQuery( hql ) + .setParameter( "b1", true ) + .setParameter( "b2", true ) + .setParameter( "b3", true ) + .executeUpdate(); + assertEquals( 1, count ); + var entity = session.createQuery( "from BooleanLiteralEntity", BooleanLiteralEntity.class ).uniqueResult(); + assertTrue( entity.isYesNoBoolean() ); + assertTrue( entity.isTrueFalseBoolean() ); + assertTrue( entity.isZeroOneBoolean() ); + session.clear(); + + hql = """ + update BooleanLiteralEntity + set yesNoBoolean = true, + trueFalseBoolean = true, + zeroOneBoolean = true + """; + count = session.createQuery( hql ).executeUpdate(); + assertEquals( 1, count ); - } - ); + entity = session.createQuery( "from BooleanLiteralEntity", BooleanLiteralEntity.class ).uniqueResult(); + assertTrue( entity.isYesNoBoolean() ); + assertTrue( entity.isTrueFalseBoolean() ); + assertTrue( entity.isZeroOneBoolean() ); + } ); data.cleanup(); } @Test - public void testSimpleInsert() { + public void testSimpleInsert(SessionFactoryScope factoryScope) { TestData data = new TestData(); - data.prepare(); + data.prepare( factoryScope ); - Session s = openSession(); - Transaction t = s.beginTransaction(); - - s.createQuery( "insert into Pickup (id, vin, owner) select id, vin, owner from Car" ).executeUpdate(); - - t.commit(); - t = s.beginTransaction(); - - s.createQuery( "delete Vehicle" ).executeUpdate(); - - t.commit(); - s.close(); + factoryScope.inTransaction( (session) -> { + // Ensure this works by executing it + session.createQuery( "insert into Pickup (id, vin, owner) select id, vin, owner from Car" ).executeUpdate(); + } ); data.cleanup(); } @Test - public void testSelectWithNamedParamProjection() { - Session s = openSession(); - // Ensure this works by executing it - s.createQuery( "select :someParameter, id from Car" ).setParameter( "someParameter", 1 ).getResultList(); + public void testSelectWithNamedParamProjection(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + // Ensure this works by executing it + session.createQuery( "select :someParameter, id from Car" ).setParameter( "someParameter", 1 ).getResultList(); + } ); } @Test - public void testSimpleInsertWithNamedParam() { + public void testSimpleInsertWithNamedParam(SessionFactoryScope factoryScope) { TestData data = new TestData(); - data.prepare(); - - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Query q = s.createQuery( "insert into Pickup (id, owner, vin) select id, :owner, vin from Car" ); - q.setParameter( "owner", "owner" ); - - q.executeUpdate(); - - t.commit(); - t = s.beginTransaction(); + data.prepare( factoryScope ); - s.createQuery( "delete Vehicle" ).executeUpdate(); - - t.commit(); - s.close(); + factoryScope.inTransaction( (session) -> { + // Ensure this works by executing it + session.createQuery( "insert into Pickup (id, owner, vin) select id, :owner, vin from Car" ) + .setParameter( "owner", "owner" ) + .executeUpdate(); + } ); data.cleanup(); } @Test @JiraKey( value = "HHH-15161") - public void testInsertWithNullParamValue() { + public void testInsertWithNullParamValue(SessionFactoryScope factoryScope) { TestData data = new TestData(); - data.prepare(); - - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Query q = s.createQuery( "insert into Pickup (id, owner, vin) select id, :owner, vin from Car" ); - q.setParameter( "owner", null ); - - q.executeUpdate(); + data.prepare( factoryScope ); - t.commit(); - t = s.beginTransaction(); - - s.createQuery( "delete Vehicle" ).executeUpdate(); - - t.commit(); - s.close(); + factoryScope.inTransaction( (session) -> { + // Ensure this works by executing it + session.createQuery( "insert into Pickup (id, owner, vin) select id, :owner, vin from Car" ) + .setParameter( "owner", null ) + .executeUpdate(); + } ); data.cleanup(); } @Test @JiraKey( value = "HHH-15161") - @SkipForDialect(value = InformixDialect.class, - comment = "Informix does not allow 'union' in 'insert select'") - public void testInsertWithNullParamValueSetOperation() { + @SkipForDialect(dialectClass = InformixDialect.class, + reason = "Informix does not allow 'union' in 'insert select'") + public void testInsertWithNullParamValueSetOperation(SessionFactoryScope factoryScope) { TestData data = new TestData(); - data.prepare(); - - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Query q = s.createQuery( "insert into Pickup (id, owner, vin) (select id, :owner, vin from Car union all select id, :owner, vin from Car) order by 1 limit 1" ); - q.setParameter( "owner", null ); - - q.executeUpdate(); - - t.commit(); - t = s.beginTransaction(); - - s.createQuery( "delete Vehicle" ).executeUpdate(); - - t.commit(); - s.close(); + data.prepare( factoryScope ); + + factoryScope.inTransaction( (session) -> { + // Ensure this works by executing it + var hql = """ + insert into Pickup (id, owner, vin) + (select id, :owner, vin from Car union all select id, :owner, vin from Car) + order by 1 + limit 1 + """; + session.createQuery( hql ) + .setParameter( "owner", null ) + .executeUpdate(); + } ); data.cleanup(); } @Test - public void testInsertWithMultipleNamedParams() { + public void testInsertWithMultipleNamedParams(SessionFactoryScope factoryScope) { TestData data = new TestData(); - data.prepare(); - - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Query q = s.createQuery( "insert into Pickup (id, owner, vin) select :id, owner, :vin from Car" ); - q.setParameter( "id", 5l ); - q.setParameter( "vin", "some" ); + data.prepare( factoryScope ); - q.executeUpdate(); - - t.commit(); - t = s.beginTransaction(); - - s.createQuery( "delete Vehicle" ).executeUpdate(); - - t.commit(); - s.close(); + factoryScope.inTransaction( (session) -> { + // Ensure this works by executing it + session.createQuery( "insert into Pickup (id, owner, vin) select :id, owner, :vin from Car" ) + .setParameter( "id", 5l ) + .setParameter( "vin", "some" ) + .executeUpdate(); + } ); data.cleanup(); } @Test - public void testInsertWithSubqueriesAndNamedParams() { + public void testInsertWithSubqueriesAndNamedParams(SessionFactoryScope factoryScope) { TestData data = new TestData(); - data.prepare(); - - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Query q = s.createQuery( - "insert into Pickup (id, owner, vin) select :id, (select a.description from Animal a where a.description = :description), :vin from Car" ); - q.setParameter( "id", 5l ); - q.setParameter( "description", "Frog" ); - q.setParameter( "vin", "some" ); - - q.executeUpdate(); - - t.commit(); - t = s.beginTransaction(); - - Query q1 = s.createQuery( - "insert into Pickup (id, owner, vin) select :id, (select :description from Animal a where a.description = :description), :vin from Car" ); - q1.setParameter( "id", 10L ); - q1.setParameter( "description", "Frog" ); - q1.setParameter( "vin", "some" ); - q1.executeUpdate(); - - t.commit(); - t = s.beginTransaction(); - - s.createQuery( "delete Vehicle" ).executeUpdate(); + data.prepare( factoryScope ); + + factoryScope.inTransaction( (session) -> { + var hql = """ + insert into Pickup (id, owner, vin) + select :id, (select a.description from Animal a where a.description = :description), :vin + from Car + """; + session.createQuery( hql ) + .setParameter( "id", 5l ) + .setParameter( "description", "Frog" ) + .setParameter( "vin", "some" ) + .executeUpdate(); - t.commit(); - s.close(); + hql = """ + insert into Pickup (id, owner, vin) + select :id, + (select :description + from Animal a + where a.description = :description), + :vin + from Car + """; + session.createQuery( hql ) + .setParameter( "id", 10L ) + .setParameter( "description", "Frog" ) + .setParameter( "vin", "some" ) + .executeUpdate(); + } ); data.cleanup(); } @Test - public void testSimpleInsertTypeMismatchException() { - - Session s = openSession(); - try { - Query q = s.createQuery( "insert into Pickup (id, owner, vin) select id, :owner, id from Car" ); - fail( "Parameter type mismatch but no exception thrown" ); - } - catch (Throwable throwable) { - QueryException queryException = assertTyping( QueryException.class, throwable.getCause() ); - String m = queryException.getMessage(); - // Expected insert attribute type [java.lang.String] did not match Query selection type [java.lang.Long] at selection index [2] - int st = m.indexOf( "java.lang.String" ); - int lt = m.indexOf( "java.lang.Long" ); - assertTrue( "type causing error not reported", st > -1 ); - assertTrue( "type causing error not reported", lt > -1 ); - assertTrue( lt < st ); -// assertTrue( "wrong position of type error reported", m.indexOf( "index [2]" ) > -1 ); - } - finally { - s.close(); - } + public void testSimpleInsertTypeMismatchException(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + try { + var hql = "insert into Pickup (id, owner, vin) select id, :owner, id from Car"; + session.createQuery( hql ); + Assertions.fail( "Parameter type mismatch but no exception thrown" ); + } + catch (Throwable throwable) { + QueryException queryException = assertTyping( QueryException.class, throwable.getCause() ); + String m = queryException.getMessage(); + // Expected insert attribute type [java.lang.String] did not match Query selection type [java.lang.Long] at selection index [2] + int st = m.indexOf( "java.lang.String" ); + int lt = m.indexOf( "java.lang.Long" ); + assertTrue( st > -1, "type causing error not reported" ); + assertTrue( lt > -1, "type causing error not reported" ); + assertTrue( lt < st ); + } + } ); } @Test - public void testSimpleNativeSQLInsert() { + public void testSimpleNativeQueryManipulations(SessionFactoryScope factoryScope) { TestData data = new TestData(); - data.prepare(); - - Session s = openSession(); - Transaction t = s.beginTransaction(); - - List l = s.createQuery( "from Vehicle" ).list(); - assertEquals( l.size(), 4 ); - - s.createNativeQuery( "insert into Pickup (id, vin, owner) select id * 10, vin, owner from Car" ).executeUpdate(); - - l = s.createQuery( "from Vehicle" ).list(); - assertEquals( l.size(), 5 ); - - t.commit(); - t = s.beginTransaction(); - - int deleteCount = s.createNativeQuery( "delete from Truck" ).executeUpdate(); - assertEquals( 1, deleteCount ); - - l = s.createQuery( "from Vehicle" ).list(); - assertEquals( l.size(), 4 ); - - Car c = (Car) s.createQuery( "from Car where owner = 'Kirsten'" ).uniqueResult(); - c.setOwner( "NotKirsten" ); - assertEquals( 0, s.getNamedQuery( "native-delete-car" ).setParameter( 1, "Kirsten" ).executeUpdate() ); - assertEquals( 1, s.getNamedQuery( "native-delete-car" ).setParameter( 1, "NotKirsten" ).executeUpdate() ); - - - assertEquals( - 0, s.createNativeQuery( "delete from SUV where owner = :owner" ) - .setParameter( "owner", "NotThere" ) - .executeUpdate() - ); - assertEquals( - 1, s.createNativeQuery( "delete from SUV where owner = :owner" ) - .setParameter( "owner", "Joe" ) - .executeUpdate() - ); - s.createNativeQuery( "delete from Pickup" ).executeUpdate(); - - l = s.createQuery( "from Vehicle" ).list(); - assertEquals( l.size(), 0 ); - - - t.commit(); - s.close(); - + data.prepare( factoryScope ); + + // insert + factoryScope.inTransaction( (session) -> { + List l = session.createQuery( "from Vehicle" ).list(); + assertEquals( 4, l.size() ); + + var sql = "insert into Pickup (id, vin, owner) select id * 10, vin, owner from Car"; + session.createNativeQuery( sql ).executeUpdate(); + + l = session.createQuery( "from Vehicle" ).list(); + assertEquals( 5, l.size() ); + } ); + + // deletes + factoryScope.inTransaction( (session) -> { + int deleteCount = session.createNativeQuery( "delete from Truck" ).executeUpdate(); + assertEquals( 1, deleteCount ); + + List l = session.createQuery( "from Vehicle" ).list(); + assertEquals( 4, l.size() ); + + Car c = (Car) session.createQuery( "from Car where owner = 'Kirsten'" ).uniqueResult(); + c.setOwner( "NotKirsten" ); + assertEquals( 0, + session.getNamedQuery( "native-delete-car" ).setParameter( 1, "Kirsten" ).executeUpdate() ); + assertEquals( 1, + session.getNamedQuery( "native-delete-car" ).setParameter( 1, "NotKirsten" ).executeUpdate() ); + + assertEquals( 0, session.createNativeQuery( "delete from SUV where owner = :owner" ) + .setParameter( "owner", "NotThere" ) + .executeUpdate() ); + assertEquals( 1, session.createNativeQuery( "delete from SUV where owner = :owner" ) + .setParameter( "owner", "Joe" ) + .executeUpdate() ); + + session.createNativeQuery( "delete from Pickup" ).executeUpdate(); + l = session.createQuery( "from Vehicle" ).list(); + assertEquals( 0, l.size() ); + } ); data.cleanup(); } @Test - @RequiresDialectFeature( value = DialectChecks.SupportsTemporaryTableIdentity.class, comment = "The use of the native generator leads to using identity which also needs to be supported on temporary tables") - @SkipForDialect( value = CockroachDialect.class, comment = "See https://hibernate.atlassian.net/browse/HHH-19332") - public void testInsertWithManyToOne() { + @RequiresDialectFeature( feature = DialectFeatureChecks.SupportsTemporaryTableIdentity.class, + comment = "The use of the native generator leads to using identity which also needs to be supported on temporary tables") + @SkipForDialect( dialectClass = CockroachDialect.class, + reason = "See https://hibernate.atlassian.net/browse/HHH-19332") + public void testInsertWithManyToOne(SessionFactoryScope factoryScope) { // Make sure the env supports bulk inserts with generated ids... - Assumptions.assumeTrue( supportsBulkInsertIdGeneration( Animal.class ), "bulk id generation not supported" ); + Assumptions.assumeTrue( supportsBulkInsertIdGeneration( Animal.class, factoryScope ), + "bulk id generation not supported" ); TestData data = new TestData(); - data.prepare(); + data.prepare( factoryScope ); - Session s = openSession(); - Transaction t = s.beginTransaction(); - - s.createQuery( - "insert into Animal (description, bodyWeight, mother) select description, bodyWeight, mother from Human" ) - .executeUpdate(); - - t.commit(); - t = s.beginTransaction(); - - t.commit(); - s.close(); + factoryScope.inTransaction( (session) -> { + var hql = "insert into Animal (description, bodyWeight, mother) select description, bodyWeight, mother from Human"; + session.createQuery( hql ).executeUpdate(); + } ); data.cleanup(); } @Test - public void testInsertWithMismatchedTypes() { + public void testInsertWithMismatchedTypes(SessionFactoryScope factoryScope) { TestData data = new TestData(); - data.prepare(); - - Session s = openSession(); - Transaction t = s.beginTransaction(); - try { - s.createQuery( "insert into Pickup (owner, vin, id) select id, vin, owner from Car" ).executeUpdate(); - fail( "mismatched types did not error" ); - } - catch (IllegalArgumentException e) { - assertTyping( QueryException.class, e.getCause() ); - } - catch (QueryException e) { - // expected result - } - - t.commit(); - t = s.beginTransaction(); + data.prepare( factoryScope ); - s.createQuery( "delete Vehicle" ).executeUpdate(); - - t.commit(); - s.close(); + factoryScope.inTransaction( (session) -> { + try { + session.createQuery( "insert into Pickup (owner, vin, id) select id, vin, owner from Car" ).executeUpdate(); + Assertions.fail( "mismatched types did not error" ); + } + catch (IllegalArgumentException e) { + assertTyping( QueryException.class, e.getCause() ); + } + catch (QueryException e) { + // expected result + } + } ); data.cleanup(); } @Test - @SkipForDialect(value = CockroachDialect.class, comment = "https://github.com/cockroachdb/cockroach/issues/75101") - @SkipForDialect(value = AbstractTransactSQLDialect.class, comment = "T-SQL complains IDENTITY_INSERT is off when a value for an identity column is provided") - @RequiresDialectFeature(value = DialectChecks.SupportsTemporaryTableIdentity.class, comment = "The use of the native generator leads to using identity which also needs to be supported on temporary tables") - public void testInsertIntoSuperclassPropertiesFails() { + @SkipForDialect(dialectClass = CockroachDialect.class, + reason = "https://github.com/cockroachdb/cockroach/issues/75101") + @SkipForDialect(dialectClass = AbstractTransactSQLDialect.class, + reason = "T-SQL complains IDENTITY_INSERT is off when a value for an identity column is provided") + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsTemporaryTableIdentity.class, + comment = "The use of the native generator leads to using identity which also needs to be supported on temporary tables") + public void testInsertIntoSuperclassPropertiesFails(SessionFactoryScope factoryScope) { TestData data = new TestData(); - data.prepare(); - - Session s = openSession(); - Transaction t = s.beginTransaction(); - - s.createQuery( "insert into Human (id, bodyWeight, heightInches) select id * 10, bodyWeight, 180D from Cat" ).executeUpdate(); - List list = s.createNativeQuery( "select height_centimeters from Human" ).getResultList(); - assertEquals( 1, list.size() ); - assertEquals( 180, list.get( 0 ).doubleValue(), 0.01 ); - - t.commit(); - t = s.beginTransaction(); + data.prepare( factoryScope ); - s.createQuery( "delete Animal where mother is not null" ).executeUpdate(); - s.createQuery( "delete Animal where father is not null" ).executeUpdate(); - s.createQuery( "delete Animal" ).executeUpdate(); - - t.commit(); - s.close(); + factoryScope.inTransaction( (session) -> { + session.createQuery( "insert into Human (id, bodyWeight, heightInches) select id * 10, bodyWeight, 180D from Cat" ).executeUpdate(); + List list = session.createNativeQuery( "select height_centimeters from Human" ).getResultList(); + assertEquals( 1, list.size() ); + assertEquals( 180, list.get( 0 ).doubleValue(), 0.01 ); + } ); data.cleanup(); } @Test - @RequiresDialectFeature( value = DialectChecks.SupportsTemporaryTableIdentity.class, comment = "The use of the native generator leads to using identity which also needs to be supported on temporary tables") - public void testInsertAcrossMappedJoin() { + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsTemporaryTableIdentity.class, + comment = "The use of the native generator leads to using identity which also needs to be supported on temporary tables") + public void testInsertAcrossMappedJoin(SessionFactoryScope factoryScope) { // Make sure the env supports bulk inserts with generated ids... - Assumptions.assumeTrue( supportsBulkInsertIdGeneration( Joiner.class ), "bulk id generation not supported" ); + Assumptions.assumeTrue( supportsBulkInsertIdGeneration( Joiner.class, factoryScope ), + "bulk id generation not supported" ); TestData data = new TestData(); - data.prepare(); - - Session s = openSession(); - Transaction t = s.beginTransaction(); - - s.createQuery( "insert into Joiner (name, joinedName) select vin, owner from Car" ).executeUpdate(); - Joiner joiner = s.createQuery( "from Joiner where name = '123c'", Joiner.class ).uniqueResult(); - assertEquals( "Kirsten", joiner.getJoinedName() ); - - t.commit(); - t = s.beginTransaction(); - - s.createQuery( "delete Joiner" ).executeUpdate(); - s.createQuery( "delete Vehicle" ).executeUpdate(); + data.prepare( factoryScope ); - t.commit(); - s.close(); + factoryScope.inTransaction( (session) -> { + session.createQuery( "insert into Joiner (name, joinedName) select vin, owner from Car" ).executeUpdate(); + Joiner joiner = session.createQuery( "from Joiner where name = '123c'", Joiner.class ).uniqueResult(); + assertEquals( "Kirsten", joiner.getJoinedName() ); + } ); data.cleanup(); } - protected boolean supportsBulkInsertIdGeneration(Class entityClass) { - EntityPersister persister = sessionFactory() + protected boolean supportsBulkInsertIdGeneration(Class entityClass, SessionFactoryScope factoryScope) { + EntityPersister persister = factoryScope + .getSessionFactory() .getMappingMetamodel() .getEntityDescriptor(entityClass.getName()); Generator generator = persister.getGenerator(); @@ -590,297 +480,248 @@ protected boolean supportsBulkInsertIdGeneration(Class entityClass) { } @Test - public void testInsertWithGeneratedId() { + public void testInsertWithGeneratedId(SessionFactoryScope factoryScope) { // Make sure the env supports bulk inserts with generated ids... - Assumptions.assumeTrue( supportsBulkInsertIdGeneration( PettingZoo.class ), "bulk id generation not supported" ); + Assumptions.assumeTrue( supportsBulkInsertIdGeneration( PettingZoo.class, factoryScope ), + "bulk id generation not supported" ); // create a Zoo - Zoo zoo = new Zoo(); - zoo.setName( "zoo" ); - - Session s = openSession(); - Transaction t = s.beginTransaction(); - s.persist( zoo ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - int count = s.createQuery( "insert into PettingZoo (name) select name from Zoo" ).executeUpdate(); - t.commit(); - s.close(); - - assertEquals( "unexpected insertion count", 1, count ); - - s = openSession(); - t = s.beginTransaction(); - PettingZoo pz = (PettingZoo) s.createQuery( "from PettingZoo" ).uniqueResult(); - t.commit(); - s.close(); - - assertEquals( zoo.getName(), pz.getName() ); - assertTrue( !zoo.getId().equals( pz.getId() ) ); - - s = openSession(); - t = s.beginTransaction(); - s.createQuery( "delete Zoo" ).executeUpdate(); - t.commit(); - s.close(); + var zoo = factoryScope.fromTransaction( (session) -> { + var z = new Zoo( "zoo", null ); + session.persist( z ); + return z; + } ); + + factoryScope.inTransaction( (session) -> { + int count = session.createQuery( "insert into PettingZoo (name) select name from Zoo" ).executeUpdate(); + assertEquals( 1, count, "unexpected insertion count" ); + } ); + + factoryScope.inTransaction( (session) -> { + var pettingZoo = session.createQuery( "from PettingZoo", PettingZoo.class ).uniqueResult(); + assertEquals( zoo.getName(), pettingZoo.getName() ); + assertTrue( !zoo.getId().equals( pettingZoo.getId() ) ); + } ); } @Test - public void testInsertWithGeneratedVersionAndId() { + public void testInsertWithGeneratedVersionAndId(SessionFactoryScope factoryScope) { // Make sure the env supports bulk inserts with generated ids... - Assumptions.assumeTrue( supportsBulkInsertIdGeneration( IntegerVersioned.class ), "bulk id generation not supported" ); + Assumptions.assumeTrue( supportsBulkInsertIdGeneration( IntegerVersioned.class, factoryScope ), + "bulk id generation not supported" ); - Session s = openSession(); - Transaction t = s.beginTransaction(); + var initial = factoryScope.fromTransaction( (session) -> { + var entity = new IntegerVersioned( "int-vers" ); + session.persist( entity ); + session.createQuery( "select id, name, version from IntegerVersioned" ).list(); + return entity; + } ); - IntegerVersioned entity = new IntegerVersioned( "int-vers" ); - s.persist( entity ); - s.createQuery( "select id, name, version from IntegerVersioned" ).list(); - t.commit(); - s.close(); + Long initialId = initial.getId(); + int initialVersion = initial.getVersion(); - Long initialId = entity.getId(); - int initialVersion = entity.getVersion(); + factoryScope.inTransaction( (session) -> { + int count = session.createQuery( "insert into IntegerVersioned ( name ) select name from IntegerVersioned" ) + .executeUpdate(); + assertEquals( 1, count, "unexpected insertion count" ); + } ); - s = openSession(); - t = s.beginTransaction(); - int count = s.createQuery( "insert into IntegerVersioned ( name ) select name from IntegerVersioned" ) - .executeUpdate(); - t.commit(); - s.close(); - - assertEquals( "unexpected insertion count", 1, count ); - - s = openSession(); - t = s.beginTransaction(); - IntegerVersioned created = (IntegerVersioned) s.createQuery( "from IntegerVersioned where id <> :initialId" ) - .setParameter( "initialId", initialId.longValue() ) - .uniqueResult(); - t.commit(); - s.close(); - - assertEquals( "version was not seeded", initialVersion, created.getVersion() ); - - s = openSession(); - t = s.beginTransaction(); - s.createQuery( "delete IntegerVersioned" ).executeUpdate(); - t.commit(); - s.close(); + var queried = factoryScope.fromTransaction( (session) -> { + return session.createQuery( "from IntegerVersioned where id <> :initialId", IntegerVersioned.class ) + .setParameter( "initialId", initialId.longValue() ) + .uniqueResult(); + } ); + + assertEquals( initialVersion, queried.getVersion(), "version was not seeded" ); } @Test - public void testInsertWithGeneratedTimestampVersion() { + public void testInsertWithGeneratedTimestampVersion(SessionFactoryScope factoryScope) { // Make sure the env supports bulk inserts with generated ids... - Assumptions.assumeTrue( supportsBulkInsertIdGeneration( TimestampVersioned.class ), "bulk id generation not supported" ); - - Session s = openSession(); - Transaction t = s.beginTransaction(); - - TimestampVersioned entity = new TimestampVersioned( "int-vers" ); - s.persist( entity ); - s.createQuery( "select id, name, version from TimestampVersioned" ).list(); - t.commit(); - s.close(); - - Long initialId = entity.getId(); - //Date initialVersion = entity.getVersion(); - - s = openSession(); - t = s.beginTransaction(); - int count = s.createQuery( "insert into TimestampVersioned ( name ) select name from TimestampVersioned" ) - .executeUpdate(); - t.commit(); - s.close(); - - assertEquals( "unexpected insertion count", 1, count ); - - s = openSession(); - t = s.beginTransaction(); - TimestampVersioned created = (TimestampVersioned) s.createQuery( - "from TimestampVersioned where id <> :initialId" ) - .setParameter( "initialId", initialId.longValue() ) - .uniqueResult(); - t.commit(); - s.close(); - - assertNotNull( created.getVersion() ); - //assertEquals( "version was not seeded", initialVersion, created.getVersion() ); - - s = openSession(); - t = s.beginTransaction(); - s.createQuery( "delete TimestampVersioned" ).executeUpdate(); - t.commit(); - s.close(); + Assumptions.assumeTrue( supportsBulkInsertIdGeneration( TimestampVersioned.class, factoryScope ), + "bulk id generation not supported" ); + + var created = factoryScope.fromTransaction( (session) -> { + TimestampVersioned entity = new TimestampVersioned( "int-vers" ); + session.persist( entity ); + session.createQuery( "select id, name, version from TimestampVersioned" ).list(); + return entity; + } ); + + var initialId = created.getId(); + + factoryScope.inTransaction( (session) -> { + int count = session.createQuery( "insert into TimestampVersioned ( name ) select name from TimestampVersioned" ) + .executeUpdate(); + assertEquals( 1, count, "unexpected insertion count" ); + } ); + + + factoryScope.inTransaction( (session) -> { + final TimestampVersioned inserted = session.createQuery( + "from TimestampVersioned where id <> :initialId", TimestampVersioned.class ) + .setParameter( "initialId", initialId.longValue() ) + .uniqueResult(); + Assertions.assertNotNull( inserted.getVersion() ); + } ); } @Test - public void testInsertWithAssignedCompositeId() { - // this just checks that the query parser detects that we are explicitly inserting a composite id - Session s = openSession(); - s.beginTransaction(); - // intentionally reversing the order of the composite id properties to make sure that is supported too - s.createQuery( - "insert into CompositeIdEntity (key2, someProperty, key1) select a.key2, 'COPY', a.key1 from CompositeIdEntity a" ) - .executeUpdate(); - s.createQuery( "delete from CompositeIdEntity" ).executeUpdate(); - s.getTransaction().commit(); - s.close(); + public void testInsertWithAssignedCompositeId(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + // this just checks that the query parser detects that we are explicitly inserting a composite id + // intentionally reversing the order of the composite id properties to make sure that is supported too + session.createQuery( + "insert into CompositeIdEntity (key2, someProperty, key1) select a.key2, 'COPY', a.key1 from CompositeIdEntity a" ) + .executeUpdate(); + } ); } @Test - @RequiresDialectFeature( value = DialectChecks.SupportsTemporaryTableIdentity.class, comment = "The use of the native generator leads to using identity which also needs to be supported on temporary tables") - @SkipForDialect( value = CockroachDialect.class, comment = "See https://hibernate.atlassian.net/browse/HHH-19332") - public void testInsertWithSelectListUsingJoins() { + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsTemporaryTableIdentity.class, + comment = "The use of the native generator leads to using identity which also needs to be supported on temporary tables") + @SkipForDialect(dialectClass = CockroachDialect.class, + reason = "See https://hibernate.atlassian.net/browse/HHH-19332") + public void testInsertWithSelectListUsingJoins(SessionFactoryScope factoryScope) { // Make sure the env supports bulk inserts with generated ids... - Assumptions.assumeTrue( supportsBulkInsertIdGeneration( Animal.class ), "bulk id generation not supported" ); - - // this is just checking parsing and syntax... - Session s = openSession(); - s.beginTransaction(); - s.createQuery( - "insert into Animal (description, bodyWeight) select h.description, h.bodyWeight from Human h where h.mother.mother is not null" ) - .executeUpdate(); - s.createQuery( - "insert into Animal (description, bodyWeight) select h.description, h.bodyWeight from Human h join h.mother m where m.mother is not null" ) - .executeUpdate(); - s.createQuery( "delete from Animal" ).executeUpdate(); - s.getTransaction().commit(); - s.close(); + Assumptions.assumeTrue( supportsBulkInsertIdGeneration( Animal.class, factoryScope ), + "bulk id generation not supported" ); + + factoryScope.inTransaction( (session) -> { + // this is just checking parsing and syntax... + var hql = """ + insert into Animal (description, bodyWeight) + select h.description, h.bodyWeight + from Human h + where h.mother.mother is not null + """; + session.createQuery( hql ).executeUpdate(); + hql = """ + insert into Animal (description, bodyWeight) + select h.description, h.bodyWeight + from Human h + join h.mother m + where m.mother is not null + """; + session.createQuery( hql ).executeUpdate(); + } ); } @Test - public void testIncorrectSyntax() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - try { - s.createQuery( "update Human set Human.description = 'xyz' where Human.id = 1 and Human.description is null" ); - fail( "expected failure" ); - } - catch (IllegalArgumentException e) { - assertTyping( QueryException.class, e.getCause() ); - } - catch (QueryException expected) { - // ignore : expected behavior - } - t.commit(); - s.close(); + public void testIncorrectSyntax(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + try { + var hql = "update Human set Human.description = 'xyz' where Human.id = 1 and Human.description is null"; + session.createQuery( hql ).executeUpdate(); + Assertions.fail( "expected failure" ); + } + catch (IllegalArgumentException e) { + assertTyping( QueryException.class, e.getCause() ); + } + catch (QueryException expected) { + // ignore : expected behavior + } + } ); } @SuppressWarnings("unchecked") @Test - public void testUpdateWithWhereExistsSubquery() { - // multi-table ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Session s = openSession(); - Transaction t = s.beginTransaction(); - Human joe = new Human(); - joe.setName( new Name( "Joe", 'Q', "Public" ) ); - s.persist( joe ); - Human doll = new Human(); - doll.setName( new Name( "Kyu", 'P', "Doll" ) ); - doll.setFriends( new ArrayList() ); - doll.getFriends().add( joe ); - s.persist( doll ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - String updateQryString = "update Human h " + - "set h.description = 'updated' " + - "where exists (" + - " select f.id " + - " from h.friends f " + - " where f.name.last = 'Public' " + - ")"; - int count = s.createQuery( updateQryString ).executeUpdate(); - assertEquals( 1, count ); - s.remove( doll ); - s.remove( joe ); - t.commit(); - s.close(); - - // single-table (one-to-many & many-to-many) ~~~~~~~~~~~~~~~~~~~~~~~~~~ - s = openSession(); - t = s.beginTransaction(); - SimpleEntityWithAssociation entity = new SimpleEntityWithAssociation(); - SimpleEntityWithAssociation other = new SimpleEntityWithAssociation(); - entity.setName( "main" ); - other.setName( "many-to-many-association" ); - entity.getManyToManyAssociatedEntities().add( other ); - entity.addAssociation( "one-to-many-association" ); - s.persist( entity ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - // one-to-many test - updateQryString = "update SimpleEntityWithAssociation e " + - "set e.name = 'updated' " + - "where exists (" + - " select a.id " + - " from e.associatedEntities a " + - " where a.name = 'one-to-many-association' " + - ")"; - count = s.createQuery( updateQryString ).executeUpdate(); - assertEquals( 1, count ); - // many-to-many test - if ( getDialect().supportsSubqueryOnMutatingTable() ) { - updateQryString = "update SimpleEntityWithAssociation e " + - "set e.name = 'updated' " + - "where exists (" + - " select a.id " + - " from e.manyToManyAssociatedEntities a " + - " where a.name = 'many-to-many-association' " + - ")"; - count = s.createQuery( updateQryString ).executeUpdate(); + public void testUpdateWithWhereExistsSubquery(SessionFactoryScope factoryScope) { + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // multi-table + factoryScope.inTransaction( (session) -> { + var joe = new Human(); + joe.setName( new Name( "Joe", 'Q', "Public" ) ); + session.persist( joe ); + var doll = new Human(); + doll.setName( new Name( "Kyu", 'P', "Doll" ) ); + doll.setFriends( new ArrayList() ); + doll.getFriends().add( joe ); + session.persist( doll ); + } ); + factoryScope.inTransaction( (session) -> { + var hql = """ + update Human h + set h.description = 'updated' + where exists ( + select f.id + from h.friends f + where f.name.last = 'Public' + ) + """; + int count = session.createQuery( hql ).executeUpdate(); assertEquals( 1, count ); - } - s.remove( entity.getManyToManyAssociatedEntities().iterator().next() ); - s.remove( entity ); - t.commit(); - s.close(); + } ); + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // single-table (one-to-many & many-to-many) + factoryScope.inTransaction( (session) -> { + var entity = new SimpleEntityWithAssociation(); + var other = new SimpleEntityWithAssociation(); + entity.setName( "main" ); + other.setName( "many-to-many-association" ); + entity.getManyToManyAssociatedEntities().add( other ); + entity.addAssociation( "one-to-many-association" ); + session.persist( entity ); + } ); + + factoryScope.inTransaction( (session) -> { + var hql = """ + update SimpleEntityWithAssociation e \ + set e.name = 'updated' \ + where exists (\ + select a.id \ + from e.associatedEntities a \ + where a.name = 'one-to-many-association' \ + )"""; + var count = session.createQuery( hql ).executeUpdate(); + assertEquals( 1, count ); + + // one-to-many test + // many-to-many test + if ( session.getDialect().supportsSubqueryOnMutatingTable() ) { + hql = """ + update SimpleEntityWithAssociation e \ + set e.name = 'updated' \ + where exists (\ + select a.id \ + from e.manyToManyAssociatedEntities a \ + where a.name = 'many-to-many-association' \ + )"""; + count = session.createQuery( hql ).executeUpdate(); + assertEquals( 1, count ); + } + } ); } @Test - public void testIncrementCounterVersion() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - IntegerVersioned entity = new IntegerVersioned( "int-vers" ); - s.persist( entity ); - t.commit(); - s.close(); + public void testIncrementCounterVersion(SessionFactoryScope factoryScope) { + var entity = factoryScope.fromTransaction( (session) -> { + var created = new IntegerVersioned( "int-vers" ); + session.persist( created ); + return created; + } ); int initialVersion = entity.getVersion(); - s = openSession(); - t = s.beginTransaction(); - int count = s.createQuery( "update versioned IntegerVersioned set name = name" ).executeUpdate(); - assertEquals( "incorrect exec count", 1, count ); - t.commit(); - - t = s.beginTransaction(); - entity = (IntegerVersioned) s.getReference( IntegerVersioned.class, entity.getId() ); - assertEquals( "version not incremented", initialVersion + 1, entity.getVersion() ); + factoryScope.inTransaction( (session) -> { + int count = session.createQuery( "update versioned IntegerVersioned set name = name" ).executeUpdate(); + assertEquals( 1, count, "incorrect exec count" ); + } ); - s.remove( entity ); - t.commit(); - s.close(); + factoryScope.inTransaction( (session) -> { + var loaded = session.getReference( IntegerVersioned.class, entity.getId() ); + assertEquals( initialVersion + 1, loaded.getVersion(), "version not incremented" ); + } ); } @Test - public void testIncrementTimestampVersion() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - TimestampVersioned entity = new TimestampVersioned( "ts-vers" ); - s.persist( entity ); - t.commit(); - s.close(); + public void testIncrementTimestampVersion(SessionFactoryScope factoryScope) { + var entity = factoryScope.fromTransaction( (session) -> { + var created = new TimestampVersioned( "ts-vers" ); + session.persist( created ); + return created; + } ); Date initialVersion = entity.getVersion(); @@ -888,702 +729,582 @@ public void testIncrementTimestampVersion() { try { wait( 1500 ); } - catch (InterruptedException ie) { + catch (InterruptedException ignored) { } } - s = openSession(); - t = s.beginTransaction(); - int count = s.createQuery( "update versioned TimestampVersioned set name = name" ).executeUpdate(); - assertEquals( "incorrect exec count", 1, count ); - t.commit(); - - t = s.beginTransaction(); - entity = (TimestampVersioned) s.getReference( TimestampVersioned.class, entity.getId() ); - assertTrue( "version not incremented", entity.getVersion().after( initialVersion ) ); + factoryScope.inTransaction( (session) -> { + int count = session.createQuery( "update versioned TimestampVersioned set name = name" ).executeUpdate(); + assertEquals( 1, count, "incorrect exec count" ); + } ); - s.remove( entity ); - t.commit(); - s.close(); + factoryScope.inTransaction( (session) -> { + var updated = session.getReference( TimestampVersioned.class, entity.getId() ); + assertTrue( updated.getVersion().after( initialVersion ), "version not incremented" ); + } ); } @Test - public void testUpdateOnComponent() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Human human = new Human(); - human.setName( new Name( "Stevee", 'X', "Ebersole" ) ); - - s.persist( human ); - s.flush(); - - t.commit(); - - String correctName = "Steve"; - - t = s.beginTransaction(); - - int count = s.createQuery( "update Human set name.first = :correction where id = :id" ) - .setParameter( "correction", correctName ) - .setParameter( "id", human.getId().longValue() ) - .executeUpdate(); - - assertEquals( "Incorrect update count", 1, count ); - - t.commit(); - - t = s.beginTransaction(); - - s.refresh( human ); - - assertEquals( "Update did not execute properly", correctName, human.getName().getFirst() ); - - s.createQuery( "delete Human" ).executeUpdate(); - t.commit(); + public void testUpdateOnComponent(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + var human = new Human(); + human.setName( new Name( "Stevee", 'X', "Ebersole" ) ); + session.persist( human ); + session.flush(); + + String correctName = "Steve"; + int count = session.createQuery( "update Human set name.first = :correction where id = :id" ) + .setParameter( "correction", correctName ) + .setParameter( "id", human.getId() ) + .executeUpdate(); + assertEquals( 1, count, + "Incorrect update count" ); - s.close(); + session.refresh( human ); + assertEquals( correctName, human.getName().getFirst(), + "Update did not execute properly" ); + } ); } @Test - @RequiresDialectFeature(DialectChecks.SupportsTemporaryTable.class) - public void testUpdateOnManyToOne() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - s.createQuery( "update Animal a set a.mother = null where a.id = 2" ).executeUpdate(); - if ( !( getDialect() instanceof MySQLDialect ) ) { - // MySQL does not support (even un-correlated) subqueries against the update-mutating table - s.createQuery( "update Animal a set a.mother = (from Animal where id = 1) where a.id = 2" ).executeUpdate(); - } - - t.commit(); - s.close(); + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsTemporaryTable.class) + public void testUpdateOnManyToOne(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + session.createQuery( "update Animal a set a.mother = null where a.id = 2" ).executeUpdate(); + if ( !( session.getDialect() instanceof MySQLDialect ) ) { + // MySQL does not support (even un-correlated) subqueries against the update-mutating table + session.createQuery( "update Animal a set a.mother = (from Animal where id = 1) where a.id = 2" ).executeUpdate(); + } + } ); } @Test - public void testUpdateOnImplicitJoinFails() { - inTransaction( - s -> { - try { - s.createQuery( "update Human set mother.name.initial = :initial" ).setParameter( - "initial", - 'F' - ).executeUpdate(); - fail( "update allowed across implicit join" ); - } - catch (IllegalArgumentException e) { - assertTyping( QueryException.class, e.getCause() ); - } - catch (QueryException e) { - } - } - ); + public void testUpdateOnImplicitJoinFails(SessionFactoryScope factoryScope) { + factoryScope.inTransaction(session -> { + try { + session.createQuery( "update Human set mother.name.initial = :initial" ).setParameter( + "initial", + 'F' + ).executeUpdate(); + Assertions.fail( "update allowed across implicit join" ); + } + catch (IllegalArgumentException e) { + assertTyping( QueryException.class, e.getCause() ); + } + catch (QueryException expected) { + } + } ); } @Test - public void testUpdateOnDiscriminatorSubclass() { + public void testUpdateOnDiscriminatorSubclass(SessionFactoryScope factoryScope) { TestData data = new TestData(); - data.prepare(); + data.prepare( factoryScope ); - Session s = openSession(); - Transaction t = s.beginTransaction(); + factoryScope.inTransaction( (session) -> { + int count = session.createQuery( "update PettingZoo set name = name" ).executeUpdate(); + assertEquals( 1, count, "Incorrect discrim subclass update count" ); - int count = s.createQuery( "update PettingZoo set name = name" ).executeUpdate(); - assertEquals( "Incorrect discrim subclass update count", 1, count ); + session.getTransaction().rollback(); + session.getTransaction().begin(); - t.rollback(); - t = s.beginTransaction(); - - count = s.createQuery( "update PettingZoo pz set pz.name = pz.name where pz.id = :id" ) - .setParameter( "id", data.pettingZoo.getId().longValue() ) - .executeUpdate(); - assertEquals( "Incorrect discrim subclass update count", 1, count ); - - t.rollback(); - t = s.beginTransaction(); + count = session.createQuery( "update PettingZoo pz set pz.name = pz.name where pz.id = :id" ) + .setParameter( "id", data.pettingZoo.getId() ) + .executeUpdate(); + assertEquals( 1, count, "Incorrect discrim subclass update count" ); - count = s.createQuery( "update Zoo as z set z.name = z.name" ).executeUpdate(); - assertEquals( "Incorrect discrim subclass update count", 2, count ); + session.getTransaction().rollback(); + session.getTransaction().begin(); - t.rollback(); - t = s.beginTransaction(); + count = session.createQuery( "update Zoo as z set z.name = z.name" ).executeUpdate(); + assertEquals( 2, count, "Incorrect discrim subclass update count" ); - // TODO : not so sure this should be allowed. Seems to me that if they specify an alias, - // property-refs should be required to be qualified. - count = s.createQuery( "update Zoo as z set name = name where id = :id" ) - .setParameter( "id", data.zoo.getId().longValue() ) - .executeUpdate(); - assertEquals( "Incorrect discrim subclass update count", 1, count ); + session.getTransaction().rollback(); + session.getTransaction().begin(); - t.commit(); - s.close(); + // TODO : not so sure this should be allowed. + // Seems to me that if they specify an alias, property-refs should be required to be qualified. + count = session.createQuery( "update Zoo as z set name = name where id = :id" ) + .setParameter( "id", data.zoo.getId().longValue() ) + .executeUpdate(); + assertEquals( 1, count, "Incorrect discrim subclass update count" ); + } ); data.cleanup(); } @Test - public void testUpdateOnAnimal() { + public void testUpdateOnAnimal(SessionFactoryScope factoryScope) { TestData data = new TestData(); - data.prepare(); - - Session s = openSession(); - Transaction t = s.beginTransaction(); - int count = s.createQuery( "update Animal set description = description where description = :desc" ) - .setParameter( "desc", data.frog.getDescription() ) - .executeUpdate(); - assertEquals( "Incorrect entity-updated count", 1, count ); - - count = s.createQuery( "update Animal set description = :newDesc where description = :desc" ) - .setParameter( "desc", data.polliwog.getDescription() ) - .setParameter( "newDesc", "Tadpole" ) - .executeUpdate(); - assertEquals( "Incorrect entity-updated count", 1, count ); - - Animal tadpole = (Animal) s.getReference( Animal.class, data.polliwog.getId() ); - assertEquals( "Update did not take effect", "Tadpole", tadpole.getDescription() ); - - count = s.createQuery( "update Animal set bodyWeight = bodyWeight + :w1 + :w2" ) - .setParameter( "w1", 1 ) - .setParameter( "w2", 2 ) - .executeUpdate(); - assertEquals( "incorrect count on 'complex' update assignment", count, 6 ); - - if ( !( getDialect() instanceof MySQLDialect ) ) { - // MySQL does not support (even un-correlated) subqueries against the update-mutating table - s.createQuery( "update Animal set bodyWeight = ( select max(bodyWeight) from Animal )" ) + data.prepare( factoryScope ); + + factoryScope.inTransaction( (session) -> { + int count = session.createQuery( "update Animal set description = description where description = :desc" ) + .setParameter( "desc", data.frog.getDescription() ) .executeUpdate(); - } + assertEquals( 1, count, "Incorrect entity-updated count" ); + + count = session.createQuery( "update Animal set description = :newDesc where description = :desc" ) + .setParameter( "desc", data.polliwog.getDescription() ) + .setParameter( "newDesc", "Tadpole" ) + .executeUpdate(); + assertEquals( 1, count, "Incorrect entity-updated count" ); - t.commit(); - s.close(); + var tadpole = session.getReference( Animal.class, data.polliwog.getId() ); + assertEquals( "Tadpole", tadpole.getDescription(), "Update did not take effect" ); + + count = session.createQuery( "update Animal set bodyWeight = bodyWeight + :w1 + :w2" ) + .setParameter( "w1", 1 ) + .setParameter( "w2", 2 ) + .executeUpdate(); + assertEquals( 6, count, "incorrect count on 'complex' update assignment" ); + + if ( !( session.getDialect() instanceof MySQLDialect ) ) { + // MySQL does not support (even un-correlated) subqueries against the update-mutating table + session.createQuery( "update Animal set bodyWeight = ( select max(bodyWeight) from Animal )" ) + .executeUpdate(); + } + } ); data.cleanup(); } @Test - public void testUpdateOnMammal() { + public void testUpdateOnMammal(SessionFactoryScope factoryScope) { TestData data = new TestData(); - data.prepare(); + data.prepare( factoryScope ); - Session s = openSession(); - Transaction t = s.beginTransaction(); + factoryScope.inTransaction( (session) -> { + int count = session.createQuery( "update Mammal set description = description" ).executeUpdate(); + assertEquals( 2, count, "incorrect update count against 'middle' of joined-subclass hierarchy" ); - int count = s.createQuery( "update Mammal set description = description" ).executeUpdate(); - assertEquals( "incorrect update count against 'middle' of joined-subclass hierarchy", 2, count ); - - count = s.createQuery( "update Mammal set bodyWeight = 25" ).executeUpdate(); - assertEquals( "incorrect update count against 'middle' of joined-subclass hierarchy", 2, count ); - - if ( !( getDialect() instanceof MySQLDialect ) ) { - // MySQL does not support (even un-correlated) subqueries against the update-mutating table - count = s.createQuery( "update Mammal set bodyWeight = ( select max(bodyWeight) from Animal )" ) - .executeUpdate(); - assertEquals( "incorrect update count against 'middle' of joined-subclass hierarchy", 2, count ); - } + count = session.createQuery( "update Mammal set bodyWeight = 25" ).executeUpdate(); + assertEquals( 2, count, "incorrect update count against 'middle' of joined-subclass hierarchy" ); - t.commit(); - s.close(); + if ( !( session.getDialect() instanceof MySQLDialect ) ) { + // MySQL does not support (even un-correlated) subqueries against the update-mutating table + count = session.createQuery( "update Mammal set bodyWeight = ( select max(bodyWeight) from Animal )" ) + .executeUpdate(); + assertEquals( 2, count, + "incorrect update count against 'middle' of joined-subclass hierarchy" ); + } + } ); data.cleanup(); } @Test - public void testUpdateSetNullUnionSubclass() { + public void testUpdateSetNullUnionSubclass(SessionFactoryScope factoryScope) { TestData data = new TestData(); - data.prepare(); - - // These should reach out into *all* subclass tables... - Session s = openSession(); - Transaction t = s.beginTransaction(); + data.prepare( factoryScope ); - int count = s.createQuery( "update Vehicle set owner = 'Steve'" ).executeUpdate(); - assertEquals( "incorrect restricted update count", 4, count ); - count = s.createQuery( "update Vehicle set owner = null where owner = 'Steve'" ).executeUpdate(); - assertEquals( "incorrect restricted update count", 4, count ); + factoryScope.inTransaction( (session) -> { + // These should reach out into *all* subclass tables... + int count = session.createQuery( "update Vehicle set owner = 'Steve'" ).executeUpdate(); + assertEquals( 4, count, "incorrect restricted update count" ); + count = session.createQuery( "update Vehicle set owner = null where owner = 'Steve'" ).executeUpdate(); + assertEquals( 4, count, "incorrect restricted update count" ); - try { - count = s.createQuery( "delete Vehicle where owner is null" ).executeUpdate(); - assertEquals( "incorrect restricted delete count", 4, count ); - } - catch (AssertionFailedError afe) { - if ( H2Dialect.class.isInstance( getDialect() ) ) { - // http://groups.google.com/group/h2-database/t/5548ff9fd3abdb7 - // this is fixed in H2 1.2.140 - count = s.createQuery( "delete Vehicle" ).executeUpdate(); - assertEquals( "incorrect count", 4, count ); + try { + count = session.createQuery( "delete Vehicle where owner is null" ).executeUpdate(); + assertEquals( 4, count, "incorrect restricted delete count" ); } - else { - throw afe; + catch (AssertionFailedError afe) { + if ( H2Dialect.class.isInstance( session.getDialect() ) ) { + // http://groups.google.com/group/h2-database/t/5548ff9fd3abdb7 + // this is fixed in H2 1.2.140 + count = session.createQuery( "delete Vehicle" ).executeUpdate(); + assertEquals( 4, count, "incorrect count" ); + } + else { + throw afe; + } } - } - - t.commit(); - s.close(); + } ); data.cleanup(); } @Test - public void testUpdateSetNullOnDiscriminatorSubclass() { + public void testUpdateSetNullOnDiscriminatorSubclass(SessionFactoryScope factoryScope) { TestData data = new TestData(); - data.prepare(); + data.prepare( factoryScope ); - Session s = openSession(); - Transaction t = s.beginTransaction(); + factoryScope.inTransaction( (session) -> { + int count = session.createQuery( "update PettingZoo set address.city = null" ).executeUpdate(); + assertEquals( 1, count, "Incorrect discrim subclass delete count" ); - int count = s.createQuery( "update PettingZoo set address.city = null" ).executeUpdate(); - assertEquals( "Incorrect discrim subclass delete count", 1, count ); - count = s.createQuery( "delete Zoo where address.city is null" ).executeUpdate(); - assertEquals( "Incorrect discrim subclass delete count", 1, count ); + count = session.createQuery( "delete Zoo where address.city is null" ).executeUpdate(); + assertEquals( 1, count, "Incorrect discrim subclass delete count" ); - count = s.createQuery( "update Zoo set address.city = null" ).executeUpdate(); - assertEquals( "Incorrect discrim subclass delete count", 1, count ); - count = s.createQuery( "delete Zoo where address.city is null" ).executeUpdate(); - assertEquals( "Incorrect discrim subclass delete count", 1, count ); + count = session.createQuery( "update Zoo set address.city = null" ).executeUpdate(); + assertEquals( 1, count, "Incorrect discrim subclass delete count" ); - t.commit(); - s.close(); + count = session.createQuery( "delete Zoo where address.city is null" ).executeUpdate(); + assertEquals( 1, count, "Incorrect discrim subclass delete count" ); + + } ); data.cleanup(); } @Test - public void testUpdateSetNullOnJoinedSubclass() { + public void testUpdateSetNullOnJoinedSubclass(SessionFactoryScope factoryScope) { TestData data = new TestData(); - data.prepare(); - - Session s = openSession(); - Transaction t = s.beginTransaction(); + data.prepare( factoryScope ); - int count = s.createQuery( "update Mammal set bodyWeight = null" ).executeUpdate(); - assertEquals( "Incorrect deletion count on joined subclass", 2, count ); + factoryScope.inTransaction( (session) -> { + int count = session.createQuery( "update Mammal set bodyWeight = null" ).executeUpdate(); + assertEquals( 2, count, "Incorrect deletion count on joined subclass" ); - count = s.createQuery( "delete Animal where bodyWeight is null" ).executeUpdate(); - assertEquals( "Incorrect deletion count on joined subclass", 2, count ); - - t.commit(); - s.close(); + count = session.createQuery( "delete Animal where bodyWeight is null" ).executeUpdate(); + assertEquals( 2, count, "Incorrect deletion count on joined subclass" ); + } ); data.cleanup(); } @Test - public void testDeleteWithSubquery() { + public void testDeleteWithSubquery(SessionFactoryScope factoryScope) { // setup the test data... - Session s = openSession(); - s.beginTransaction(); - SimpleEntityWithAssociation owner = new SimpleEntityWithAssociation( "myEntity-1" ); - owner.addAssociation( "assoc-1" ); - owner.addAssociation( "assoc-2" ); - owner.addAssociation( "assoc-3" ); - s.persist( owner ); - SimpleEntityWithAssociation owner2 = new SimpleEntityWithAssociation( "myEntity-2" ); - owner2.addAssociation( "assoc-1" ); - owner2.addAssociation( "assoc-2" ); - owner2.addAssociation( "assoc-3" ); - owner2.addAssociation( "assoc-4" ); - s.persist( owner2 ); - SimpleEntityWithAssociation owner3 = new SimpleEntityWithAssociation( "myEntity-3" ); - s.persist( owner3 ); - s.getTransaction().commit(); - s.close(); + factoryScope.inTransaction( (session) -> { + SimpleEntityWithAssociation owner = new SimpleEntityWithAssociation( "myEntity-1" ); + owner.addAssociation( "assoc-1" ); + owner.addAssociation( "assoc-2" ); + owner.addAssociation( "assoc-3" ); + session.persist( owner ); + SimpleEntityWithAssociation owner2 = new SimpleEntityWithAssociation( "myEntity-2" ); + owner2.addAssociation( "assoc-1" ); + owner2.addAssociation( "assoc-2" ); + owner2.addAssociation( "assoc-3" ); + owner2.addAssociation( "assoc-4" ); + session.persist( owner2 ); + SimpleEntityWithAssociation owner3 = new SimpleEntityWithAssociation( "myEntity-3" ); + session.persist( owner3 ); + } ); // now try the bulk delete - s = openSession(); - s.beginTransaction(); - int count = s.createQuery( - "delete SimpleEntityWithAssociation e where size( e.associatedEntities ) = 0 and e.name like '%'" ) - .executeUpdate(); - assertEquals( "incorrect delete count", 1, count ); - s.getTransaction().commit(); - s.close(); - - // finally, clean up - s = openSession(); - s.beginTransaction(); - s.createQuery( "delete SimpleAssociatedEntity" ).executeUpdate(); - s.createQuery( "delete SimpleEntityWithAssociation" ).executeUpdate(); - s.getTransaction().commit(); - s.close(); + factoryScope.inTransaction( (session) -> { + var queryString = """ + delete SimpleEntityWithAssociation e + where size( e.associatedEntities ) = 0 + and e.name like '%' + """; + int count = session.createMutationQuery( queryString ).executeUpdate(); + assertEquals( 1, count, "incorrect delete count" ); + } ); } @Test - @RequiresDialectFeature( - value = DialectChecks.HasSelfReferentialForeignKeyBugCheck.class, + @RequiresDialectFeature(feature = DialectFeatureChecks.HasSelfReferentialForeignKeyBugCheck.class, comment = "self referential FK bug" ) - public void testSimpleDeleteOnAnimal() { + public void testSimpleDeleteOnAnimal(SessionFactoryScope factoryScope) { TestData data = new TestData(); - data.prepare(); - - Session s = openSession(); - Transaction t = s.beginTransaction(); + data.prepare( factoryScope ); - int count = s.createQuery( "delete from Animal as a where a.id = :id" ) - .setParameter( "id", data.polliwog.getId().longValue() ) - .executeUpdate(); - assertEquals( "Incorrect delete count", 1, count ); + factoryScope.inTransaction( (session) -> { + int count = session.createQuery( "delete from Animal as a where a.id = :id" ) + .setParameter( "id", data.polliwog.getId().longValue() ) + .executeUpdate(); + assertEquals( 1, count, "Incorrect delete count" ); - count = s.createQuery( "delete Animal where id = :id" ) - .setParameter( "id", data.catepillar.getId().longValue() ) - .executeUpdate(); - assertEquals( "incorrect delete count", 1, count ); + count = session.createQuery( "delete Animal where id = :id" ) + .setParameter( "id", data.catepillar.getId().longValue() ) + .executeUpdate(); + assertEquals( 1, count, "incorrect delete count" ); - if ( getDialect().supportsSubqueryOnMutatingTable() ) { - count = s.createQuery( "delete from User u where u not in (select u from User u)" ).executeUpdate(); - assertEquals( 0, count ); - } + if ( session.getDialect().supportsSubqueryOnMutatingTable() ) { + count = session.createQuery( "delete from User u where u not in (select u from User u)" ).executeUpdate(); + assertEquals( 0, count ); + } - count = s.createQuery( "delete Animal a" ).executeUpdate(); - assertEquals( "Incorrect delete count", 4, count ); + count = session.createQuery( "delete Animal a" ).executeUpdate(); + assertEquals( 4, count, "Incorrect delete count" ); - List list = s.createQuery( "select a from Animal as a" ).list(); - assertTrue( "table not empty", list.isEmpty() ); + List list = session.createQuery( "select a from Animal as a" ).list(); + assertTrue( list.isEmpty(), "table not empty" ); + } ); - t.commit(); - s.close(); data.cleanup(); } @Test - public void testDeleteOnDiscriminatorSubclass() { + public void testDeleteOnDiscriminatorSubclass(SessionFactoryScope factoryScope) { TestData data = new TestData(); - data.prepare(); - - Session s = openSession(); - Transaction t = s.beginTransaction(); + data.prepare( factoryScope ); - int count = s.createQuery( "delete PettingZoo" ).executeUpdate(); - assertEquals( "Incorrect discrim subclass delete count", 1, count ); + factoryScope.inTransaction( (session) -> { + int count = session.createQuery( "delete PettingZoo" ).executeUpdate(); + assertEquals( 1, count, "Incorrect discrim subclass delete count" ); - count = s.createQuery( "delete Zoo" ).executeUpdate(); - assertEquals( "Incorrect discrim subclass delete count", 1, count ); - - t.commit(); - s.close(); + count = session.createQuery( "delete Zoo" ).executeUpdate(); + assertEquals( 1, count, "Incorrect discrim subclass delete count" ); + } ); data.cleanup(); } @Test - public void testDeleteOnJoinedSubclass() { + public void testDeleteOnJoinedSubclass(SessionFactoryScope factoryScope) { TestData data = new TestData(); - data.prepare(); - - Session s = openSession(); - Transaction t = s.beginTransaction(); + data.prepare( factoryScope); - int count = s.createQuery( "delete Mammal where bodyWeight > 150" ).executeUpdate(); - assertEquals( "Incorrect deletion count on joined subclass", 1, count ); + factoryScope.inTransaction( (session) -> { + int count = session.createQuery( "delete Mammal where bodyWeight > 150" ).executeUpdate(); + assertEquals( 1, count, "Incorrect deletion count on joined subclass" ); - count = s.createQuery( "delete Mammal" ).executeUpdate(); - assertEquals( "Incorrect deletion count on joined subclass", 1, count ); + count = session.createQuery( "delete Mammal" ).executeUpdate(); + assertEquals( 1, count, "Incorrect deletion count on joined subclass" ); - count = s.createQuery( "delete SubMulti" ).executeUpdate(); - assertEquals( "Incorrect deletion count on joined subclass", 0, count ); - - t.commit(); - s.close(); + count = session.createQuery( "delete SubMulti" ).executeUpdate(); + assertEquals( 0, count, "Incorrect deletion count on joined subclass" ); + } ); data.cleanup(); } @Test - public void testDeleteOnMappedJoin() { + public void testDeleteOnMappedJoin(SessionFactoryScope factoryScope) { TestData data = new TestData(); - data.prepare(); - - inTransaction( - s -> { - int count = s.createQuery( "delete Joiner where joinedName = :joinedName" ).setParameter( - "joinedName", - "joined-name" - ).executeUpdate(); - assertEquals( "Incorrect deletion count on joined subclass", 1, count ); - } - ); + data.prepare( factoryScope ); + + factoryScope.inTransaction( (session) -> { + int count = session.createQuery( "delete Joiner where joinedName = :joinedName" ) + .setParameter( "joinedName", "joined-name" ) + .executeUpdate(); + assertEquals( 1, count, "Incorrect deletion count on joined subclass" ); + } ); data.cleanup(); } @Test - public void testDeleteUnionSubclassAbstractRoot() { + public void testDeleteUnionSubclassAbstractRoot(SessionFactoryScope factoryScope) { TestData data = new TestData(); - data.prepare(); + data.prepare( factoryScope); // These should reach out into *all* subclass tables... - inTransaction( - s -> { - int count = s.createQuery( "delete Vehicle where owner = :owner" ) - .setParameter( "owner", "Steve" ) - .executeUpdate(); - assertEquals( "incorrect restricted update count", 1, count ); - - count = s.createQuery( "delete Vehicle" ).executeUpdate(); - assertEquals( "incorrect update count", 3, count ); + factoryScope.inTransaction( (session) -> { + int count = session.createQuery( "delete Vehicle where owner = :owner" ) + .setParameter( "owner", "Steve" ) + .executeUpdate(); + assertEquals( 1, count, "incorrect restricted update count" ); - } - ); + count = session.createQuery( "delete Vehicle" ).executeUpdate(); + assertEquals( 3, count, "incorrect update count" ); + } ); data.cleanup(); } @Test - public void testDeleteUnionSubclassConcreteSubclass() { + public void testDeleteUnionSubclassConcreteSubclass(SessionFactoryScope factoryScope) { TestData data = new TestData(); - data.prepare(); + data.prepare( factoryScope ); // These should only affect the given table - inTransaction( - s -> { - int count = s.createQuery( "delete Truck where owner = :owner" ) - .setParameter( "owner", "Steve" ) - .executeUpdate(); - assertEquals( "incorrect restricted update count", 1, count ); - - count = s.createQuery( "delete Truck" ).executeUpdate(); - assertEquals( "incorrect update count", 2, count ); - } - ); + factoryScope.inTransaction( (session) -> { + int count = session.createQuery( "delete Truck where owner = :owner" ) + .setParameter( "owner", "Steve" ) + .executeUpdate(); + assertEquals( 1, count, "incorrect restricted update count" ); + + count = session.createQuery( "delete Truck" ).executeUpdate(); + assertEquals( 2, count, "incorrect update count" ); + } ); data.cleanup(); } @Test - public void testDeleteUnionSubclassLeafSubclass() { + public void testDeleteUnionSubclassLeafSubclass(SessionFactoryScope factoryScope) { TestData data = new TestData(); - data.prepare(); + data.prepare( factoryScope ); // These should only affect the given table - inTransaction( - s -> { - int count = s.createQuery( "delete Car where owner = :owner" ) - .setParameter( "owner", "Kirsten" ) - .executeUpdate(); - assertEquals( "incorrect restricted update count", 1, count ); - - count = s.createQuery( "delete Car" ).executeUpdate(); - assertEquals( "incorrect update count", 0, count ); - } - ); + factoryScope.inTransaction( (session) -> { + int count = session.createQuery( "delete Car where owner = :owner" ) + .setParameter( "owner", "Kirsten" ) + .executeUpdate(); + assertEquals( 1, count, "incorrect restricted update count" ); + + count = session.createQuery( "delete Car" ).executeUpdate(); + assertEquals( 0, count, "incorrect update count" ); + } ); data.cleanup(); } @Test - @RequiresDialectFeature(DialectChecks.SupportsTemporaryTable.class) - public void testDeleteWithMetadataWhereFragments() { - inTransaction( - s -> { - // Note: we are just checking the syntax here... - s.createQuery( "delete from Bar" ).executeUpdate(); - s.createQuery( "delete from Bar where barString = 's'" ).executeUpdate(); - - } - ); + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsTemporaryTable.class) + public void testDeleteWithMetadataWhereFragments(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + // Note: we are just checking the syntax here... + session.createQuery( "delete from Bar" ).executeUpdate(); + session.createQuery( "delete from Bar where barString = 's'" ).executeUpdate(); + } ); } @Test - public void testDeleteRestrictedOnManyToOne() { + public void testDeleteRestrictedOnManyToOne(SessionFactoryScope factoryScope) { TestData data = new TestData(); - data.prepare(); - - inTransaction( - s -> { - int count = s.createQuery( "delete Animal where mother = :mother" ) - .setParameter( "mother", data.butterfly ) - .executeUpdate(); - assertEquals( 1, count ); - } - ); + data.prepare( factoryScope ); + + factoryScope.inTransaction( (s) -> { + int count = s.createQuery( "delete Animal where mother = :mother" ) + .setParameter( "mother", data.butterfly ) + .executeUpdate(); + assertEquals( 1, count ); + } ); data.cleanup(); } @Test - public void testDeleteSyntaxWithCompositeId() { - inTransaction( - s -> { - s.createQuery( "delete EntityWithCrazyCompositeKey where id.id = 1 and id.otherId = 2" ) - .executeUpdate(); - s.createQuery( "delete from EntityWithCrazyCompositeKey where id.id = 1 and id.otherId = 2" ) - .executeUpdate(); - s.createQuery( "delete from EntityWithCrazyCompositeKey e where e.id.id = 1 and e.id.otherId = 2" ) - .executeUpdate(); - } - ); + public void testDeleteSyntaxWithCompositeId(SessionFactoryScope factoryScope) { + factoryScope.inTransaction((session) -> { + session.createQuery( "delete EntityWithCrazyCompositeKey where id.id = 1 and id.otherId = 2" ) + .executeUpdate(); + session.createQuery( "delete from EntityWithCrazyCompositeKey where id.id = 1 and id.otherId = 2" ) + .executeUpdate(); + session.createQuery( "delete from EntityWithCrazyCompositeKey e where e.id.id = 1 and e.id.otherId = 2" ) + .executeUpdate(); + } ); } @Test @JiraKey(value = "HHH-8476") - public void testManyToManyBulkDelete() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Farm farm1 = new Farm(); - farm1.setName( "farm1" ); - Crop crop = new Crop(); - crop.setName( "crop1" ); - farm1.setCrops( new ArrayList() ); - farm1.getCrops().add( crop ); - s.persist( farm1 ); - - Farm farm2 = new Farm(); - farm2.setName( "farm2" ); - farm2.setCrops( new ArrayList() ); - farm2.getCrops().add( crop ); - s.persist( farm2 ); - - s.flush(); - - try { - s.createQuery( "delete from Farm f where f.name='farm1'" ).executeUpdate(); - assertEquals( s.createQuery( "from Farm" ).list().size(), 1 ); - s.createQuery( "delete from Farm" ).executeUpdate(); - assertEquals( s.createQuery( "from Farm" ).list().size(), 0 ); - } - catch (ConstraintViolationException cve) { - fail( "The join table was not cleared prior to the bulk delete." ); - } - finally { - t.rollback(); - s.close(); - } + public void testManyToManyBulkDelete(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + var farm1 = new Farm(); + farm1.setName( "farm1" ); + var crop = new Crop(); + crop.setName( "crop1" ); + farm1.setCrops( new ArrayList() ); + farm1.getCrops().add( crop ); + session.persist( farm1 ); + + var farm2 = new Farm(); + farm2.setName( "farm2" ); + farm2.setCrops( new ArrayList() ); + farm2.getCrops().add( crop ); + session.persist( farm2 ); + + session.flush(); + + try { + session.createQuery( "delete from Farm f where f.name='farm1'" ).executeUpdate(); + assertEquals( 1, session.createQuery( "from Farm" ).list().size() ); + session.createQuery( "delete from Farm" ).executeUpdate(); + assertEquals( 0, session.createQuery( "from Farm" ).list().size() ); + } + catch (ConstraintViolationException cve) { + Assertions.fail( "The join table was not cleared prior to the bulk delete." ); + } + } ); } @Test @JiraKey(value = "HHH-1917") - public void testManyToManyBulkDeleteMultiTable() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Human friend = new Human(); - friend.setName( new Name( "Bob", 'B', "Bobbert" ) ); - s.persist( friend ); - - Human brett = new Human(); - brett.setName( new Name( "Brett", 'E', "Meyer" ) ); - brett.setFriends( new ArrayList() ); - brett.getFriends().add( friend ); - s.persist( brett ); - - s.flush(); - - try { - // multitable (joined subclass) - s.createQuery( "delete from Human" ).executeUpdate(); - assertEquals( s.createQuery( "from Human" ).list().size(), 0 ); - } - catch (ConstraintViolationException cve) { - fail( "The join table was not cleared prior to the bulk delete." ); - } - finally { - t.rollback(); - s.close(); - } + public void testManyToManyBulkDeleteMultiTable(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + var friend = new Human(); + friend.setName( new Name( "Bob", 'B', "Bobbert" ) ); + session.persist( friend ); + + var brett = new Human(); + brett.setName( new Name( "Brett", 'E', "Meyer" ) ); + brett.setFriends( new ArrayList() ); + brett.getFriends().add( friend ); + session.persist( brett ); + + session.flush(); + + try { + // multitable (joined subclass) + session.createQuery( "delete from Human" ).executeUpdate(); + assertEquals( 0, session.createQuery( "from Human" ).list().size() ); + } + catch (ConstraintViolationException cve) { + Assertions.fail( "The join table was not cleared prior to the bulk delete." ); + } + } ); } @Test - public void testBulkDeleteOfEntityWithElementCollection() { + public void testBulkDeleteOfEntityWithElementCollection(SessionFactoryScope factoryScope) { // set up test data - inTransaction( - s -> { - Farm farm = new Farm(); - farm.setName( "Old McDonald Farm 'o the Earth" ); - farm.setAccreditations( new HashSet<>() ); - farm.getAccreditations().add( Farm.Accreditation.ORGANIC ); - farm.getAccreditations().add( Farm.Accreditation.SUSTAINABLE ); - s.persist( farm ); - } - ); + factoryScope.inTransaction((session) -> { + var farm = new Farm(); + farm.setName( "Old McDonald Farm 'o the Earth" ); + farm.setAccreditations( new HashSet<>() ); + farm.getAccreditations().add( Farm.Accreditation.ORGANIC ); + farm.getAccreditations().add( Farm.Accreditation.SUSTAINABLE ); + session.persist( farm ); + } ); // assertion that accreditations collection table got populated - inTransaction( - s -> - s.doWork( - connection -> { - final Statement statement = connection.createStatement(); - final ResultSet resultSet = statement.executeQuery( - "select count(*) from farm_accreditations" ); - assertTrue( resultSet.next() ); - final int count = resultSet.getInt( 1 ); - assertEquals( 2, count ); - } - ) - - ); + factoryScope.inTransaction( (session) -> session.doWork( (connection) -> { + final Statement statement = connection.createStatement(); + final ResultSet resultSet = statement.executeQuery( + "select count(*) from farm_accreditations" ); + assertTrue( resultSet.next() ); + final int count = resultSet.getInt( 1 ); + assertEquals( 2, count ); + } ) ); // do delete - inTransaction( - s -> s.createQuery( "delete Farm" ).executeUpdate() - ); + factoryScope.inTransaction( (session) -> session.createQuery( "delete Farm" ).executeUpdate() ); // assertion that accreditations collection table got cleaned up // if they didn't, the delete should have caused a constraint error, but just to be sure... - inTransaction( - s -> s.doWork( - connection -> { - final Statement statement = connection.createStatement(); - final ResultSet resultSet = statement.executeQuery( - "select count(*) from farm_accreditations" ); - assertTrue( resultSet.next() ); - final int count = resultSet.getInt( 1 ); - assertEquals( 0, count ); - } - ) - ); + factoryScope.inTransaction((s) -> s.doWork( (connection) -> { + final Statement statement = connection.createStatement(); + final ResultSet resultSet = statement.executeQuery( + "select count(*) from farm_accreditations" ); + assertTrue( resultSet.next() ); + final int count = resultSet.getInt( 1 ); + assertEquals( 0, count ); + } ) ); } @Test - public void testBulkDeleteOfMultiTableEntityWithElementCollection() { + public void testBulkDeleteOfMultiTableEntityWithElementCollection(SessionFactoryScope factoryScope) { // set up test data - inTransaction( - s -> { - Human human = new Human(); - human.setNickNames( new TreeSet() ); - human.getNickNames().add( "Johnny" ); - s.persist( human ); - } - ); + factoryScope.inTransaction( (s) -> { + var human = new Human(); + human.setNickNames( new TreeSet() ); + human.getNickNames().add( "Johnny" ); + s.persist( human ); + } ); // assertion that nickname collection table got populated - inTransaction( - s -> s.doWork( - connection -> { - final Statement statement = connection.createStatement(); - final ResultSet resultSet = statement.executeQuery( "select count(*) from human_nick_names" ); - assertTrue( resultSet.next() ); - final int count = resultSet.getInt( 1 ); - assertEquals( 1, count ); - } - ) - ); + factoryScope.inTransaction((s) -> s.doWork( (connection) -> { + final Statement statement = connection.createStatement(); + final ResultSet resultSet = statement.executeQuery( "select count(*) from human_nick_names" ); + assertTrue( resultSet.next() ); + final int count = resultSet.getInt( 1 ); + assertEquals( 1, count ); + } ) ); // do delete - inTransaction( - s -> s.createQuery( "delete Human" ).executeUpdate() - ); + factoryScope.inTransaction(s -> s.createQuery( "delete Human" ).executeUpdate() ); // assertion that nickname collection table got cleaned up // if they didn't, the delete should have caused a constraint error, but just to be sure... - inTransaction( - s -> s.doWork( - connection -> { - final Statement statement = connection.createStatement(); - final ResultSet resultSet = statement.executeQuery( "select count(*) from human_nick_names" ); - assertTrue( resultSet.next() ); - final int count = resultSet.getInt( 1 ); - assertEquals( 0, count ); - } - ) - ); + factoryScope.inTransaction( s -> s.doWork( (connection) -> { + final Statement statement = connection.createStatement(); + final ResultSet resultSet = statement.executeQuery( "select count(*) from human_nick_names" ); + assertTrue( resultSet.next() ); + final int count = resultSet.getInt( 1 ); + assertEquals( 0, count ); + } ) ); } - private class TestData { - + private static class TestData { private Animal polliwog; private Animal catepillar; private Animal frog; @@ -1592,112 +1313,98 @@ private class TestData { private Zoo zoo; private Zoo pettingZoo; - private void prepare() { - inTransaction( - s -> { - polliwog = new Animal(); - polliwog.setBodyWeight( 12 ); - polliwog.setDescription( "Polliwog" ); - - catepillar = new Animal(); - catepillar.setBodyWeight( 10 ); - catepillar.setDescription( "Catepillar" ); - - frog = new Animal(); - frog.setBodyWeight( 34 ); - frog.setDescription( "Frog" ); - - polliwog.setFather( frog ); - frog.addOffspring( polliwog ); - - butterfly = new Animal(); - butterfly.setBodyWeight( 9 ); - butterfly.setDescription( "Butterfly" ); - - catepillar.setMother( butterfly ); - butterfly.addOffspring( catepillar ); - - s.persist( frog ); - s.persist( polliwog ); - s.persist( butterfly ); - s.persist( catepillar ); - - Dog dog = new Dog(); - dog.setBodyWeight( 200 ); - dog.setDescription( "dog" ); - s.persist( dog ); - - Cat cat = new Cat(); - cat.setBodyWeight( 100 ); - cat.setDescription( "cat" ); - s.persist( cat ); - - zoo = new Zoo(); - zoo.setName( "Zoo" ); - Address add = new Address(); - add.setCity( "MEL" ); - add.setCountry( "AU" ); - add.setStreet( "Main st" ); - add.setPostalCode( "3000" ); - zoo.setAddress( add ); - - pettingZoo = new PettingZoo(); - pettingZoo.setName( "Petting Zoo" ); - Address addr = new Address(); - addr.setCity( "Sydney" ); - addr.setCountry( "AU" ); - addr.setStreet( "High st" ); - addr.setPostalCode( "2000" ); - pettingZoo.setAddress( addr ); - - s.persist( zoo ); - s.persist( pettingZoo ); - - Joiner joiner = new Joiner(); - joiner.setJoinedName( "joined-name" ); - joiner.setName( "name" ); - s.persist( joiner ); - - Car car = new Car(); - car.setVin( "123c" ); - car.setOwner( "Kirsten" ); - s.persist( car ); - - Truck truck = new Truck(); - truck.setVin( "123t" ); - truck.setOwner( "Steve" ); - s.persist( truck ); - - SUV suv = new SUV(); - suv.setVin( "123s" ); - suv.setOwner( "Joe" ); - s.persist( suv ); - - Pickup pickup = new Pickup(); - pickup.setVin( "123p" ); - pickup.setOwner( "Cecelia" ); - s.persist( pickup ); - - BooleanLiteralEntity bool = new BooleanLiteralEntity(); - s.persist( bool ); - } - ); + private void prepare(SessionFactoryScope factoryScope) { + factoryScope.inTransaction(s -> { + polliwog = new Animal(); + polliwog.setBodyWeight( 12 ); + polliwog.setDescription( "Polliwog" ); + + catepillar = new Animal(); + catepillar.setBodyWeight( 10 ); + catepillar.setDescription( "Catepillar" ); + + frog = new Animal(); + frog.setBodyWeight( 34 ); + frog.setDescription( "Frog" ); + + polliwog.setFather( frog ); + frog.addOffspring( polliwog ); + + butterfly = new Animal(); + butterfly.setBodyWeight( 9 ); + butterfly.setDescription( "Butterfly" ); + + catepillar.setMother( butterfly ); + butterfly.addOffspring( catepillar ); + + s.persist( frog ); + s.persist( polliwog ); + s.persist( butterfly ); + s.persist( catepillar ); + + Dog dog = new Dog(); + dog.setBodyWeight( 200 ); + dog.setDescription( "dog" ); + s.persist( dog ); + + Cat cat = new Cat(); + cat.setBodyWeight( 100 ); + cat.setDescription( "cat" ); + s.persist( cat ); + + zoo = new Zoo(); + zoo.setName( "Zoo" ); + Address add = new Address(); + add.setCity( "MEL" ); + add.setCountry( "AU" ); + add.setStreet( "Main st" ); + add.setPostalCode( "3000" ); + zoo.setAddress( add ); + + pettingZoo = new PettingZoo(); + pettingZoo.setName( "Petting Zoo" ); + Address addr = new Address(); + addr.setCity( "Sydney" ); + addr.setCountry( "AU" ); + addr.setStreet( "High st" ); + addr.setPostalCode( "2000" ); + pettingZoo.setAddress( addr ); + + s.persist( zoo ); + s.persist( pettingZoo ); + + Joiner joiner = new Joiner(); + joiner.setJoinedName( "joined-name" ); + joiner.setName( "name" ); + s.persist( joiner ); + + Car car = new Car(); + car.setVin( "123c" ); + car.setOwner( "Kirsten" ); + s.persist( car ); + + Truck truck = new Truck(); + truck.setVin( "123t" ); + truck.setOwner( "Steve" ); + s.persist( truck ); + + SUV suv = new SUV(); + suv.setVin( "123s" ); + suv.setOwner( "Joe" ); + s.persist( suv ); + + Pickup pickup = new Pickup(); + pickup.setVin( "123p" ); + pickup.setOwner( "Cecelia" ); + s.persist( pickup ); + + BooleanLiteralEntity bool = new BooleanLiteralEntity(); + s.persist( bool ); + } ); } private void cleanup() { - inTransaction( - s -> { - // workaround awesome HSQLDB "feature" - s.createQuery( "delete from Animal where mother is not null or father is not null" ) - .executeUpdate(); - s.createQuery( "delete from Animal" ).executeUpdate(); - s.createQuery( "delete from Zoo" ).executeUpdate(); - s.createQuery( "delete from Joiner" ).executeUpdate(); - s.createQuery( "delete from Vehicle" ).executeUpdate(); - s.createQuery( "delete from BooleanLiteralEntity" ).executeUpdate(); - - } - ); + // do nothing - rely on the AfterEach callback to drop data } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/DB297SubStringFunctionsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/DB297SubStringFunctionsTest.java index de546f13b3b5..d7d4e71d748a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/DB297SubStringFunctionsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/DB297SubStringFunctionsTest.java @@ -7,144 +7,114 @@ import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; - import org.hibernate.QueryException; -import org.hibernate.cfg.Configuration; -import org.hibernate.cfg.Environment; import org.hibernate.dialect.DB2Dialect; -import org.hibernate.resource.jdbc.spi.StatementInspector; - -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.jdbc.SQLStatementInspector; +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.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.fail; -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; /** * DB2 has 2 functions for getting a substring: "substr" and "substring" * * @author Gail Badner */ +@SuppressWarnings("JUnitMalformedDeclaration") @RequiresDialect(DB2Dialect.class) -public class DB297SubStringFunctionsTest extends BaseCoreFunctionalTestCase { - private static final MostRecentStatementInspector mostRecentStatementInspector = new MostRecentStatementInspector(); - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - AnEntity.class - }; +@DomainModel(annotatedClasses = DB297SubStringFunctionsTest.AnEntity.class) +@SessionFactory(useCollectingStatementInspector = true) +public class DB297SubStringFunctionsTest { + @BeforeEach + void createTestData(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + AnEntity anEntity = new AnEntity(); + anEntity.description = "A very long, boring description."; + session.persist( anEntity ); + } ); } - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - configuration.getProperties().put( Environment.STATEMENT_INSPECTOR, mostRecentStatementInspector ); - } - - @Before - public void setup() { - AnEntity anEntity = new AnEntity(); - anEntity.description = "A very long, boring description."; - - doInHibernate( - this::sessionFactory, session -> { - session.persist( anEntity ); - } - ); - } - - @After - public void cleanup() { - doInHibernate( - this::sessionFactory, session -> { - session.createQuery( "delete from AnEntity" ).executeUpdate(); - } - ); + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test @JiraKey( value = "HHH-11957") - public void testSubstringWithStringUnits() { - - mostRecentStatementInspector.clear(); - - doInHibernate( - this::sessionFactory, session -> { - String value = session.createQuery( - "select substring( e.description, 21, 11, sql('octets') ) from AnEntity e", - String.class - ).uniqueResult(); - assertEquals( "description", value ); - } - ); - - assertTrue( mostRecentStatementInspector.mostRecentSql.contains( "substring(" ) ); - assertTrue( mostRecentStatementInspector.mostRecentSql.contains( "octets" ) ); + public void testSubstringWithStringUnits(SessionFactoryScope factoryScope) { + final SQLStatementInspector sqlCollector = factoryScope.getCollectingStatementInspector(); + sqlCollector.clear(); + + factoryScope.inTransaction( (session) -> { + String value = session.createQuery( + "select substring( e.description, 21, 11, sql('octets') ) from AnEntity e", + String.class + ).uniqueResult(); + assertThat( value ).isEqualTo( "description" ); + } ); + + assertThat( sqlCollector.getSqlQueries() ).hasSize( 1 ); + assertThat( sqlCollector.getSqlQueries().get( 0 ) ).contains( "substring(" ); + assertThat( sqlCollector.getSqlQueries().get( 0 ) ).contains( "octets" ); } @Test @JiraKey( value = "HHH-11957") - public void testSubstringWithoutStringUnits() { - - mostRecentStatementInspector.clear(); - - doInHibernate( - this::sessionFactory, session -> { - String value = session.createQuery( - "select substring( e.description, 21, 11 ) from AnEntity e", - String.class - ).uniqueResult(); - assertEquals( "description", value ); - } - ); - assertTrue( mostRecentStatementInspector.mostRecentSql.contains( "substring(" ) ); + public void testSubstringWithoutStringUnits(SessionFactoryScope factoryScope) { + final SQLStatementInspector sqlCollector = factoryScope.getCollectingStatementInspector(); + sqlCollector.clear(); + + factoryScope.inTransaction( (session) -> { + String value = session.createQuery( + "select substring( e.description, 21, 11 ) from AnEntity e", + String.class + ).uniqueResult(); + assertThat( value ).isEqualTo( "description" ); + } ); + assertThat( sqlCollector.getSqlQueries() ).hasSize( 1 ); + assertThat( sqlCollector.getSqlQueries().get( 0 ) ).contains( "substring(" ); } @Test @JiraKey( value = "HHH-11957") - public void testSubstrWithStringUnits() { - - try { - doInHibernate( - this::sessionFactory, session -> { - String value = session.createQuery( - "select substr( e.description, 21, 11, sql('octets') ) from AnEntity e", - String.class - ).uniqueResult(); - assertEquals( "description", value ); - } - ); - fail( "Should have failed because substr cannot be used with string units." ); - } - catch (IllegalArgumentException expected) { - assertTrue( QueryException.class.isInstance( expected.getCause() ) ); - } + public void testSubstrWithStringUnits(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + try { + session.createQuery( + "select substr( e.description, 21, 11, sql('octets') ) from AnEntity e", + String.class + ).uniqueResult(); + fail( "Should have failed because substr cannot be used with string units." ); + } + catch (IllegalArgumentException expected) { + assertThat( expected.getCause() ).isInstanceOf( QueryException.class ); + } + } ); } @Test @JiraKey( value = "HHH-11957") - public void testSubstrWithoutStringUnits() { - - mostRecentStatementInspector.clear(); - - doInHibernate( - this::sessionFactory, session -> { - String value = session.createQuery( - "select substr( e.description, 21, 11 ) from AnEntity e", - String.class - ).uniqueResult(); - assertEquals( "description", value ); - } - ); - assertTrue( mostRecentStatementInspector.mostRecentSql.contains( "substr(" ) ); + public void testSubstrWithoutStringUnits(SessionFactoryScope factoryScope) { + final SQLStatementInspector sqlCollector = factoryScope.getCollectingStatementInspector(); + sqlCollector.clear(); + + factoryScope.inTransaction( (session) -> { + String value = session.createQuery( + "select substr( e.description, 21, 11 ) from AnEntity e", + String.class + ).uniqueResult(); + assertThat( value ).isEqualTo( "description" ); + } ); + assertThat( sqlCollector.getSqlQueries() ).hasSize( 1 ); + assertThat( sqlCollector.getSqlQueries().get( 0 ) ).contains( "substring(" ); } @Entity(name="AnEntity") @@ -155,15 +125,4 @@ public static class AnEntity { private String description; } - private static class MostRecentStatementInspector implements StatementInspector { - private String mostRecentSql; - - public String inspect(String sql) { - mostRecentSql = sql; - return sql; - } - private void clear() { - mostRecentSql = null; - } - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/DeleteAllWithTablePerClassAndDefaultSchemaTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/DeleteAllWithTablePerClassAndDefaultSchemaTest.java index 819c886209ac..9e93ca87174f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/DeleteAllWithTablePerClassAndDefaultSchemaTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/DeleteAllWithTablePerClassAndDefaultSchemaTest.java @@ -4,40 +4,39 @@ */ package org.hibernate.orm.test.hql; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; -import org.hibernate.dialect.PostgreSQLDialect; - -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Before; -import org.junit.Test; - import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Inheritance; import jakarta.persistence.InheritanceType; +import org.hibernate.dialect.PostgreSQLDialect; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.hibernate.cfg.MappingSettings.DEFAULT_SCHEMA; +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey(value = "HHH-15022") @RequiresDialect(PostgreSQLDialect.class) -public class DeleteAllWithTablePerClassAndDefaultSchemaTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { SuperEntity.class, SubEntity1.class, SubEntity2.class }; - } - - @Override - protected void configure(Configuration configuration) { - configuration.setProperty( AvailableSettings.DEFAULT_SCHEMA, "public" ); - } - - @Before - public void setUp() { - inTransaction( session -> { +@ServiceRegistry(settings = @Setting(name=DEFAULT_SCHEMA, value = "public")) +@DomainModel(annotatedClasses = { + DeleteAllWithTablePerClassAndDefaultSchemaTest.SuperEntity.class, + DeleteAllWithTablePerClassAndDefaultSchemaTest.SubEntity1.class, + DeleteAllWithTablePerClassAndDefaultSchemaTest.SubEntity2.class +}) +@SessionFactory +public class DeleteAllWithTablePerClassAndDefaultSchemaTest { + @BeforeEach + public void createTestData(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( session -> { SuperEntity entity1 = new SubEntity1( 1L, "super1", "sub1" ); SuperEntity entity2 = new SubEntity2( 2L, "super2", "sub2" ); session.persist( entity1 ); @@ -45,16 +44,21 @@ public void setUp() { } ); } + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); + } + @Test - public void testDeleteAll() { - inTransaction( session -> { + public void testDeleteAll(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( session -> { assertThat( session.createQuery( "select count(*) from superent", Long.class ).uniqueResult() ) .isEqualTo( 2L ); } ); - inTransaction( session -> { + factoryScope.inTransaction( session -> { session.createMutationQuery( "delete from subent1" ).executeUpdate(); } ); - inTransaction( session -> { + factoryScope.inTransaction( session -> { assertThat( session.createQuery( "select count(*) from superent", Long.class ).uniqueResult() ) .isEqualTo( 1L ); } ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/DeleteQuerySubqueryReferencingTargetPropertyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/DeleteQuerySubqueryReferencingTargetPropertyTest.java index 74e1c56f52c2..7b99ee1326a7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/DeleteQuerySubqueryReferencingTargetPropertyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/DeleteQuerySubqueryReferencingTargetPropertyTest.java @@ -12,26 +12,31 @@ import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Assert; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import static org.junit.jupiter.api.Assertions.assertEquals; +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey(value = "HHH-12492") -public class DeleteQuerySubqueryReferencingTargetPropertyTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Root.class, Detail.class }; +@DomainModel(annotatedClasses = { + DeleteQuerySubqueryReferencingTargetPropertyTest.Root.class, + DeleteQuerySubqueryReferencingTargetPropertyTest.Detail.class +}) +@SessionFactory +public class DeleteQuerySubqueryReferencingTargetPropertyTest { + @AfterEach + void tearDown(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test - public void testSubQueryReferencingTargetProperty() { - // prepare - doInJPA( this::entityManagerFactory, entityManager -> { + public void testSubQueryReferencingTargetProperty(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (entityManager) -> { Root m1 = new Root(); entityManager.persist( m1 ); Detail d11 = new Detail( m1 ); @@ -43,7 +48,7 @@ public void testSubQueryReferencingTargetProperty() { entityManager.persist( m2 ); } ); - doInJPA( this::entityManagerFactory, entityManager -> { + factoryScope.inTransaction( (entityManager) -> { // depending on the generated ids above this delete removes all Roots or nothing // removal of all Roots results in foreign key constraint violation // removal of nothing is incorrect since 2nd Root does not have any details @@ -58,7 +63,7 @@ public void testSubQueryReferencingTargetProperty() { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery query = builder.createQuery( Root.class ); query.select( query.from( Root.class ) ); - Assert.assertEquals( 1, entityManager.createQuery( query ).getResultList().size() ); + assertEquals( 1, entityManager.createQuery( query ).getResultList().size() ); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/DeleteWithSubqueryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/DeleteWithSubqueryTest.java index 89a5fabfa958..d381fd348af7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/DeleteWithSubqueryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/DeleteWithSubqueryTest.java @@ -4,58 +4,72 @@ */ package org.hibernate.orm.test.hql; -import org.hibernate.Session; import org.hibernate.dialect.MySQLDialect; import org.hibernate.orm.test.annotations.query.Attrset; import org.hibernate.orm.test.annotations.query.Attrvalue; import org.hibernate.orm.test.annotations.query.Employee; import org.hibernate.orm.test.annotations.query.Employeegroup; -import org.hibernate.testing.SkipForDialect; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.SkipForDialect; +import org.junit.jupiter.api.Test; /** * @author Steve Ebersole */ -public class DeleteWithSubqueryTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Attrset.class, - Attrvalue.class, - Employee.class, - Employeegroup.class, - Panel.class, - TrtPanel.class - }; - } +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(annotatedClasses = { + Attrset.class, + Attrvalue.class, + Employee.class, + Employeegroup.class, + Panel.class, + TrtPanel.class +}) +@SessionFactory +public class DeleteWithSubqueryTest { @Test @JiraKey( value = "HHH-8318" ) - @SkipForDialect( value = MySQLDialect.class, comment = "Cannot use Attrvalue in the delete and from clauses simultaneously." ) - public void testDeleteMemberOf() { - final String qry = "delete Attrvalue aval where aval.id in ( " - + "select val2.id from Employee e, Employeegroup eg, Attrset aset, Attrvalue val2 " - + "where eg.id = e.employeegroup.id " + "and aset.id = e.attrset.id " - + "and val2 member of aset.attrvalues)"; - Session s = openSession(); - s.getTransaction().begin(); - s.createQuery( qry ).executeUpdate(); - s.getTransaction().commit(); - s.close(); + @SkipForDialect(dialectClass = MySQLDialect.class, + reason = "Cannot use Attrvalue in the delete and from clauses simultaneously." ) + public void testDeleteMemberOf(SessionFactoryScope factoryScope) { + final String qry = """ + delete Attrvalue aval + where aval.id in ( + select val2.id + from Employee e, + Employeegroup eg, + Attrset aset, + Attrvalue val2 + where eg.id = e.employeegroup.id + and aset.id = e.attrset.id + and val2 member of aset.attrvalues + ) + """; + factoryScope.inTransaction( session -> { + session.createQuery( qry ).executeUpdate(); + } ); } @Test @JiraKey( value = "HHH-8447" ) - public void testDeleteMultipleWhereIns() { - Session s = openSession(); - s.getTransaction().begin(); - s.createQuery("DELETE FROM Panel panelEntity WHERE " + - " panelEntity.clientId IN ( SELECT trtPanel.clientId FROM TrtPanel trtPanel ) " + - " AND panelEntity.deltaStamp NOT IN ( SELECT trtPanel.deltaStamp FROM TrtPanel trtPanel )").executeUpdate(); - s.getTransaction().commit(); - s.close(); + public void testDeleteMultipleWhereIns(SessionFactoryScope factoryScope) { + var hql = """ + DELETE FROM Panel panelEntity + WHERE panelEntity.clientId IN ( + SELECT trtPanel.clientId + FROM TrtPanel trtPanel + ) + AND panelEntity.deltaStamp NOT IN ( + SELECT trtPanel.deltaStamp + FROM TrtPanel trtPanel + ) + """; + factoryScope.inTransaction( session -> { + session.createQuery( hql ).executeUpdate(); + } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/FunctionNameAsColumnTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/FunctionNameAsColumnTest.java index 0da1c254ceb7..83ca1a2cdc4e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/FunctionNameAsColumnTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/FunctionNameAsColumnTest.java @@ -4,238 +4,204 @@ */ package org.hibernate.orm.test.hql; -import java.util.List; - import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.JoinType; import jakarta.persistence.criteria.Root; - import org.hibernate.Hibernate; -import org.hibernate.Session; -import org.hibernate.cfg.Configuration; -import org.hibernate.cfg.Environment; import org.hibernate.community.dialect.InformixDialect; import org.hibernate.dialect.PostgresPlusDialect; import org.hibernate.dialect.SybaseASEDialect; - -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.hibernate.internal.util.MutableObject; +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.hibernate.testing.orm.junit.SkipForDialect; -import org.junit.After; -import org.junit.Assume; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.hibernate.cfg.CacheSettings.USE_QUERY_CACHE; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests HQL and Criteria queries using DB columns having the same name as registered functions. * * @author Gail Badner */ +@SuppressWarnings("JUnitMalformedDeclaration") @SkipForDialect(dialectClass = SybaseASEDialect.class, reason = "HHH-6426") @SkipForDialect(dialectClass = PostgresPlusDialect.class, reason = "Almost all of the tests result in 'ambiguous column' errors.") -public class FunctionNameAsColumnTest extends BaseCoreFunctionalTestCase { - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } - @Override - public String[] getMappings() { - return new String[] { - "hql/FunctionNamesAsColumns.hbm.xml" - }; - } - - @Override - public void configure(Configuration cfg) { - super.configure( cfg ); - cfg.setProperty( Environment.USE_QUERY_CACHE, false ); +@ServiceRegistry(settings = @Setting(name = USE_QUERY_CACHE, value = "false")) +@DomainModel(xmlMappings = "org/hibernate/orm/test/hql/FunctionNamesAsColumns.hbm.xml") +@SessionFactory +public class FunctionNameAsColumnTest { + + @AfterEach + public void cleanup(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test - public void testGetOneColumnSameNameAsArgFunctionHQL() { - inTransaction( - s -> { - EntityWithArgFunctionAsColumn e = new EntityWithArgFunctionAsColumn(); - e.setLower( 3 ); - e.setUpper( " abc " ); - s.persist( e ); - } - ); - - inTransaction( - s -> { - EntityWithArgFunctionAsColumn e = (EntityWithArgFunctionAsColumn) s.createQuery( - "from EntityWithArgFunctionAsColumn" ).uniqueResult(); - assertEquals( 3, e.getLower() ); - assertEquals( " abc ", e.getUpper() ); - } - ); + public void testGetOneColumnSameNameAsArgFunctionHQL(SessionFactoryScope sessionFactory) { + sessionFactory.inTransaction( s -> { + EntityWithArgFunctionAsColumn e = new EntityWithArgFunctionAsColumn(); + e.setLower( 3 ); + e.setUpper( " abc " ); + s.persist( e ); + } ); + + sessionFactory.inTransaction(s -> { + EntityWithArgFunctionAsColumn e = (EntityWithArgFunctionAsColumn) s.createQuery( + "from EntityWithArgFunctionAsColumn" ).uniqueResult(); + assertEquals( 3, e.getLower() ); + assertEquals( " abc ", e.getUpper() ); + } ); } @Test - public void testGetOneColumnSameNameAsArgFunctionCriteria() { - inTransaction( - s -> { - EntityWithArgFunctionAsColumn e = new EntityWithArgFunctionAsColumn(); - e.setLower( 3 ); - e.setUpper( " abc " ); - s.persist( e ); - } - ); - - inTransaction( - s -> { - CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); - CriteriaQuery criteria = criteriaBuilder.createQuery( - EntityWithArgFunctionAsColumn.class ); - criteria.from( EntityWithArgFunctionAsColumn.class ); - - EntityWithArgFunctionAsColumn e = s.createQuery( criteria ).uniqueResult(); - -// e = ( EntityWithArgFunctionAsColumn ) s.createCriteria( EntityWithArgFunctionAsColumn.class ).uniqueResult(); - assertEquals( 3, e.getLower() ); - assertEquals( " abc ", e.getUpper() ); - } - ); + public void testGetOneColumnSameNameAsArgFunctionCriteria(SessionFactoryScope sessionFactory) { + sessionFactory.inTransaction(s -> { + EntityWithArgFunctionAsColumn e = new EntityWithArgFunctionAsColumn(); + e.setLower( 3 ); + e.setUpper( " abc " ); + s.persist( e ); + } ); + + sessionFactory.inTransaction(s -> { + CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); + CriteriaQuery criteria = criteriaBuilder.createQuery( + EntityWithArgFunctionAsColumn.class ); + criteria.from( EntityWithArgFunctionAsColumn.class ); + + EntityWithArgFunctionAsColumn e = s.createQuery( criteria ).uniqueResult(); + + assertEquals( 3, e.getLower() ); + assertEquals( " abc ", e.getUpper() ); + } ); } @Test - public void testGetMultiColumnSameNameAsArgFunctionHQL() { - inTransaction( - s -> { - EntityWithArgFunctionAsColumn e1 = new EntityWithArgFunctionAsColumn(); - e1.setLower( 3 ); - e1.setUpper( " abc " ); - EntityWithArgFunctionAsColumn e2 = new EntityWithArgFunctionAsColumn(); - e2.setLower( 999 ); - e2.setUpper( " xyz " ); - EntityWithFunctionAsColumnHolder holder1 = new EntityWithFunctionAsColumnHolder(); - holder1.getEntityWithArgFunctionAsColumns().add( e1 ); - EntityWithFunctionAsColumnHolder holder2 = new EntityWithFunctionAsColumnHolder(); - holder2.getEntityWithArgFunctionAsColumns().add( e2 ); - holder1.setNextHolder( holder2 ); - s.persist( holder1 ); - } - ); - - inTransaction( - s -> { - EntityWithFunctionAsColumnHolder holder1 = (EntityWithFunctionAsColumnHolder) s.createQuery( - "from EntityWithFunctionAsColumnHolder h left join fetch h.entityWithArgFunctionAsColumns " + - "left join fetch h.nextHolder left join fetch h.nextHolder.entityWithArgFunctionAsColumns " + - "where h.nextHolder is not null" ) - .uniqueResult(); - assertTrue( Hibernate.isInitialized( holder1.getEntityWithArgFunctionAsColumns() ) ); - assertTrue( Hibernate.isInitialized( holder1.getNextHolder() ) ); - assertTrue( Hibernate.isInitialized( holder1.getNextHolder().getEntityWithArgFunctionAsColumns() ) ); - assertEquals( 1, holder1.getEntityWithArgFunctionAsColumns().size() ); - EntityWithArgFunctionAsColumn e1 = (EntityWithArgFunctionAsColumn) holder1.getEntityWithArgFunctionAsColumns().iterator().next(); - assertEquals( 3, e1.getLower() ); - assertEquals( " abc ", e1.getUpper() ); - assertEquals( 1, holder1.getNextHolder().getEntityWithArgFunctionAsColumns().size() ); - EntityWithArgFunctionAsColumn e2 = (EntityWithArgFunctionAsColumn) ( holder1.getNextHolder() ).getEntityWithArgFunctionAsColumns() - .iterator() - .next(); - assertEquals( 999, e2.getLower() ); - assertEquals( " xyz ", e2.getUpper() ); - } - ); + public void testGetMultiColumnSameNameAsArgFunctionHQL(SessionFactoryScope sessionFactory) { + sessionFactory.inTransaction(s -> { + EntityWithArgFunctionAsColumn e1 = new EntityWithArgFunctionAsColumn(); + e1.setLower( 3 ); + e1.setUpper( " abc " ); + EntityWithArgFunctionAsColumn e2 = new EntityWithArgFunctionAsColumn(); + e2.setLower( 999 ); + e2.setUpper( " xyz " ); + EntityWithFunctionAsColumnHolder holder1 = new EntityWithFunctionAsColumnHolder(); + holder1.getEntityWithArgFunctionAsColumns().add( e1 ); + EntityWithFunctionAsColumnHolder holder2 = new EntityWithFunctionAsColumnHolder(); + holder2.getEntityWithArgFunctionAsColumns().add( e2 ); + holder1.setNextHolder( holder2 ); + s.persist( holder1 ); + } ); + + sessionFactory.inTransaction(s -> { + EntityWithFunctionAsColumnHolder holder1 = (EntityWithFunctionAsColumnHolder) s.createQuery( + "from EntityWithFunctionAsColumnHolder h left join fetch h.entityWithArgFunctionAsColumns " + + "left join fetch h.nextHolder left join fetch h.nextHolder.entityWithArgFunctionAsColumns " + + "where h.nextHolder is not null" ) + .uniqueResult(); + assertTrue( Hibernate.isInitialized( holder1.getEntityWithArgFunctionAsColumns() ) ); + assertTrue( Hibernate.isInitialized( holder1.getNextHolder() ) ); + assertTrue( Hibernate.isInitialized( holder1.getNextHolder().getEntityWithArgFunctionAsColumns() ) ); + assertEquals( 1, holder1.getEntityWithArgFunctionAsColumns().size() ); + EntityWithArgFunctionAsColumn e1 = (EntityWithArgFunctionAsColumn) holder1.getEntityWithArgFunctionAsColumns().iterator().next(); + assertEquals( 3, e1.getLower() ); + assertEquals( " abc ", e1.getUpper() ); + assertEquals( 1, holder1.getNextHolder().getEntityWithArgFunctionAsColumns().size() ); + EntityWithArgFunctionAsColumn e2 = (EntityWithArgFunctionAsColumn) ( holder1.getNextHolder() ).getEntityWithArgFunctionAsColumns() + .iterator() + .next(); + assertEquals( 999, e2.getLower() ); + assertEquals( " xyz ", e2.getUpper() ); + } ); } @Test - public void testGetMultiColumnSameNameAsArgFunctionCriteria() { - inTransaction( - s -> { - EntityWithArgFunctionAsColumn e1 = new EntityWithArgFunctionAsColumn(); - e1.setLower( 3 ); - e1.setUpper( " abc " ); - EntityWithArgFunctionAsColumn e2 = new EntityWithArgFunctionAsColumn(); - e2.setLower( 999 ); - e2.setUpper( " xyz " ); - EntityWithFunctionAsColumnHolder holder1 = new EntityWithFunctionAsColumnHolder(); - holder1.getEntityWithArgFunctionAsColumns().add( e1 ); - EntityWithFunctionAsColumnHolder holder2 = new EntityWithFunctionAsColumnHolder(); - holder2.getEntityWithArgFunctionAsColumns().add( e2 ); - holder1.setNextHolder( holder2 ); - s.persist( holder1 ); - } - ); - - inTransaction( - s -> { - CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); - CriteriaQuery criteria = criteriaBuilder.createQuery( - EntityWithFunctionAsColumnHolder.class ); - Root root = criteria.from( EntityWithFunctionAsColumnHolder.class ); - root.fetch( "entityWithArgFunctionAsColumns", JoinType.LEFT ); - root.fetch( "nextHolder", JoinType.LEFT ) - .fetch( "entityWithArgFunctionAsColumns", JoinType.LEFT ); - criteria.where( criteriaBuilder.isNotNull( root.get( "nextHolder" ) ) ); - - EntityWithFunctionAsColumnHolder holder1 = s.createQuery( criteria ).uniqueResult(); - -// holder1 = ( EntityWithFunctionAsColumnHolder ) s.createCriteria( EntityWithFunctionAsColumnHolder.class ) -// .add( Restrictions.isNotNull( "nextHolder" )) -// .setFetchMode( "entityWithArgFunctionAsColumns", FetchMode.JOIN ) -// .setFetchMode( "nextHolder", FetchMode.JOIN ) -// .setFetchMode( "nextHolder.entityWithArgFunctionAsColumns", FetchMode.JOIN ) -// .uniqueResult(); - assertTrue( Hibernate.isInitialized( holder1.getEntityWithArgFunctionAsColumns() ) ); - assertTrue( Hibernate.isInitialized( holder1.getNextHolder() ) ); - assertTrue( Hibernate.isInitialized( holder1.getNextHolder().getEntityWithArgFunctionAsColumns() ) ); - assertEquals( 1, holder1.getEntityWithArgFunctionAsColumns().size() ); - EntityWithArgFunctionAsColumn e1 = (EntityWithArgFunctionAsColumn) holder1.getEntityWithArgFunctionAsColumns().iterator().next(); - assertEquals( 3, e1.getLower() ); - assertEquals( " abc ", e1.getUpper() ); - assertEquals( 1, holder1.getNextHolder().getEntityWithArgFunctionAsColumns().size() ); - EntityWithArgFunctionAsColumn e2 = (EntityWithArgFunctionAsColumn) ( holder1.getNextHolder() ).getEntityWithArgFunctionAsColumns() - .iterator() - .next(); - assertEquals( 999, e2.getLower() ); - assertEquals( " xyz ", e2.getUpper() ); - } - ); + public void testGetMultiColumnSameNameAsArgFunctionCriteria(SessionFactoryScope factoryScope) { + factoryScope.inTransaction(s -> { + EntityWithArgFunctionAsColumn e1 = new EntityWithArgFunctionAsColumn(); + e1.setLower( 3 ); + e1.setUpper( " abc " ); + EntityWithArgFunctionAsColumn e2 = new EntityWithArgFunctionAsColumn(); + e2.setLower( 999 ); + e2.setUpper( " xyz " ); + EntityWithFunctionAsColumnHolder holder1 = new EntityWithFunctionAsColumnHolder(); + holder1.getEntityWithArgFunctionAsColumns().add( e1 ); + EntityWithFunctionAsColumnHolder holder2 = new EntityWithFunctionAsColumnHolder(); + holder2.getEntityWithArgFunctionAsColumns().add( e2 ); + holder1.setNextHolder( holder2 ); + s.persist( holder1 ); + } ); + + factoryScope.inTransaction( s -> { + CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); + CriteriaQuery criteria = criteriaBuilder.createQuery( + EntityWithFunctionAsColumnHolder.class ); + Root root = criteria.from( EntityWithFunctionAsColumnHolder.class ); + root.fetch( "entityWithArgFunctionAsColumns", JoinType.LEFT ); + root.fetch( "nextHolder", JoinType.LEFT ) + .fetch( "entityWithArgFunctionAsColumns", JoinType.LEFT ); + criteria.where( criteriaBuilder.isNotNull( root.get( "nextHolder" ) ) ); + + EntityWithFunctionAsColumnHolder holder1 = s.createQuery( criteria ).uniqueResult(); + + assertTrue( Hibernate.isInitialized( holder1.getEntityWithArgFunctionAsColumns() ) ); + assertTrue( Hibernate.isInitialized( holder1.getNextHolder() ) ); + assertTrue( Hibernate.isInitialized( holder1.getNextHolder().getEntityWithArgFunctionAsColumns() ) ); + assertEquals( 1, holder1.getEntityWithArgFunctionAsColumns().size() ); + EntityWithArgFunctionAsColumn e1 = (EntityWithArgFunctionAsColumn) holder1.getEntityWithArgFunctionAsColumns().iterator().next(); + assertEquals( 3, e1.getLower() ); + assertEquals( " abc ", e1.getUpper() ); + assertEquals( 1, holder1.getNextHolder().getEntityWithArgFunctionAsColumns().size() ); + EntityWithArgFunctionAsColumn e2 = (EntityWithArgFunctionAsColumn) ( holder1.getNextHolder() ).getEntityWithArgFunctionAsColumns() + .iterator() + .next(); + assertEquals( 999, e2.getLower() ); + assertEquals( " xyz ", e2.getUpper() ); + } ); } @Test @SkipForDialect(dialectClass = InformixDialect.class, reason = "Ambiguous column") - public void testGetMultiColumnSameNameAsNoArgFunctionHQL() { - Assume.assumeFalse( - "current_date requires () but test is for noarg function that does not require ()", - sessionFactory().getJdbcServices().getDialect().currentDate().contains( "(" ) - ); - - inTransaction( - s -> { - EntityWithNoArgFunctionAsColumn e1 = new EntityWithNoArgFunctionAsColumn(); - e1.setCurrentDate( "blah blah blah" ); - EntityWithNoArgFunctionAsColumn e2 = new EntityWithNoArgFunctionAsColumn(); - e2.setCurrentDate( "yadda yadda yadda" ); - EntityWithFunctionAsColumnHolder holder1 = new EntityWithFunctionAsColumnHolder(); - holder1.getEntityWithNoArgFunctionAsColumns().add( e1 ); - EntityWithFunctionAsColumnHolder holder2 = new EntityWithFunctionAsColumnHolder(); - holder2.getEntityWithNoArgFunctionAsColumns().add( e2 ); - holder1.setNextHolder( holder2 ); - s.persist( holder1 ); - } - ); - - Session s = openSession(); - try { - EntityWithFunctionAsColumnHolder holder1 = (EntityWithFunctionAsColumnHolder) s.createQuery( - "from EntityWithFunctionAsColumnHolder h left join fetch h.entityWithNoArgFunctionAsColumns " + - "left join fetch h.nextHolder left join fetch h.nextHolder.entityWithNoArgFunctionAsColumns " + - "where h.nextHolder is not null" ) - .uniqueResult(); + public void testGetMultiColumnSameNameAsNoArgFunctionHQL(SessionFactoryScope factoryScope) { + Assumptions.assumeFalse( dialectUsesParenForCurrentDate( factoryScope ), + "current_date requires () but test is for noarg function that does not require ()" ); + + factoryScope.inTransaction(s -> { + EntityWithNoArgFunctionAsColumn e1 = new EntityWithNoArgFunctionAsColumn(); + e1.setCurrentDate( "blah blah blah" ); + EntityWithNoArgFunctionAsColumn e2 = new EntityWithNoArgFunctionAsColumn(); + e2.setCurrentDate( "yadda yadda yadda" ); + EntityWithFunctionAsColumnHolder holder1 = new EntityWithFunctionAsColumnHolder(); + holder1.getEntityWithNoArgFunctionAsColumns().add( e1 ); + EntityWithFunctionAsColumnHolder holder2 = new EntityWithFunctionAsColumnHolder(); + holder2.getEntityWithNoArgFunctionAsColumns().add( e2 ); + holder1.setNextHolder( holder2 ); + s.persist( holder1 ); + } ); + + factoryScope.inTransaction( s -> { + var hql = """ + from EntityWithFunctionAsColumnHolder h + left join fetch h.entityWithNoArgFunctionAsColumns + left join fetch h.nextHolder + left join fetch h.nextHolder.entityWithNoArgFunctionAsColumns + where h.nextHolder is not null + """; + var holder1 = s.createQuery( hql, EntityWithFunctionAsColumnHolder.class ).uniqueResult(); assertTrue( Hibernate.isInitialized( holder1.getEntityWithNoArgFunctionAsColumns() ) ); assertTrue( Hibernate.isInitialized( holder1.getNextHolder() ) ); assertTrue( Hibernate.isInitialized( holder1.getNextHolder().getEntityWithNoArgFunctionAsColumns() ) ); assertEquals( 1, holder1.getEntityWithNoArgFunctionAsColumns().size() ); - s.close(); EntityWithNoArgFunctionAsColumn e1 = (EntityWithNoArgFunctionAsColumn) holder1.getEntityWithNoArgFunctionAsColumns().iterator().next(); assertEquals( "blah blah blah", e1.getCurrentDate() ); @@ -244,142 +210,98 @@ public void testGetMultiColumnSameNameAsNoArgFunctionHQL() { .iterator() .next(); assertEquals( "yadda yadda yadda", e2.getCurrentDate() ); - }catch (Exception e){ - if (s.getTransaction().isActive()){ - s.getTransaction().rollback(); - } - throw e; - }finally { - if(s.isOpen()) { - s.close(); - } - } + } ); } @Test @SkipForDialect(dialectClass = InformixDialect.class, reason = "Ambiguous column") - public void testGetMultiColumnSameNameAsNoArgFunctionCriteria() { - Assume.assumeFalse( - "current_date requires () but test is for noarg function that does not require ()", - sessionFactory().getJdbcServices().getDialect().currentDate().contains( "(" ) - ); - - EntityWithFunctionAsColumnHolder holder1 = new EntityWithFunctionAsColumnHolder(); - EntityWithFunctionAsColumnHolder holder2 = new EntityWithFunctionAsColumnHolder(); - - inTransaction( - s -> { - EntityWithNoArgFunctionAsColumn e1 = new EntityWithNoArgFunctionAsColumn(); - e1.setCurrentDate( "blah blah blah" ); - EntityWithNoArgFunctionAsColumn e2 = new EntityWithNoArgFunctionAsColumn(); - e2.setCurrentDate( "yadda yadda yadda" ); - holder1.getEntityWithNoArgFunctionAsColumns().add( e1 ); - holder2.getEntityWithNoArgFunctionAsColumns().add( e2 ); - holder1.setNextHolder( holder2 ); - s.persist( holder1 ); - } - ); - - inTransaction( - s -> { - CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); - CriteriaQuery criteria = criteriaBuilder.createQuery( - EntityWithFunctionAsColumnHolder.class ); - Root root = criteria.from( EntityWithFunctionAsColumnHolder.class ); - root.fetch( "entityWithNoArgFunctionAsColumns", JoinType.LEFT ); - root.fetch( "nextHolder", JoinType.LEFT ) - .fetch( "entityWithNoArgFunctionAsColumns", JoinType.LEFT ); - criteria.where( criteriaBuilder.isNotNull( root.get( "nextHolder" ) ) ); - EntityWithFunctionAsColumnHolder holder = s.createQuery( criteria ).uniqueResult(); -// holder1 = ( EntityWithFunctionAsColumnHolder ) s.createCriteria( EntityWithFunctionAsColumnHolder.class ) -// .add( Restrictions.isNotNull( "nextHolder" )) -// .setFetchMode( "entityWithNoArgFunctionAsColumns", FetchMode.JOIN ) -// .setFetchMode( "nextHolder", FetchMode.JOIN ) -// .setFetchMode( "nextHolder.entityWithNoArgFunctionAsColumns", FetchMode.JOIN ) -// .uniqueResult(); - assertTrue( Hibernate.isInitialized( holder.getEntityWithNoArgFunctionAsColumns() ) ); - assertTrue( Hibernate.isInitialized( holder.getNextHolder() ) ); - assertTrue( Hibernate.isInitialized( holder.getNextHolder() - .getEntityWithNoArgFunctionAsColumns() ) ); - assertEquals( 1, holder.getEntityWithNoArgFunctionAsColumns().size() ); - EntityWithNoArgFunctionAsColumn e1 = (EntityWithNoArgFunctionAsColumn) holder.getEntityWithNoArgFunctionAsColumns() - .iterator() - .next(); - assertEquals( "blah blah blah", e1.getCurrentDate() ); - assertEquals( 1, holder.getNextHolder().getEntityWithNoArgFunctionAsColumns().size() ); - EntityWithNoArgFunctionAsColumn e2 = (EntityWithNoArgFunctionAsColumn) ( holder.getNextHolder() ).getEntityWithNoArgFunctionAsColumns() - .iterator() - .next(); - assertEquals( "yadda yadda yadda", e2.getCurrentDate() ); - - } - ); + public void testGetMultiColumnSameNameAsNoArgFunctionCriteria(SessionFactoryScope factoryScope) { + Assumptions.assumeFalse( dialectUsesParenForCurrentDate( factoryScope ), + "current_date requires () but test is for noarg function that does not require ()" ); + + factoryScope.inTransaction( s -> { + EntityWithFunctionAsColumnHolder holder1 = new EntityWithFunctionAsColumnHolder(); + EntityWithFunctionAsColumnHolder holder2 = new EntityWithFunctionAsColumnHolder(); + + EntityWithNoArgFunctionAsColumn e1 = new EntityWithNoArgFunctionAsColumn(); + e1.setCurrentDate( "blah blah blah" ); + EntityWithNoArgFunctionAsColumn e2 = new EntityWithNoArgFunctionAsColumn(); + e2.setCurrentDate( "yadda yadda yadda" ); + holder1.getEntityWithNoArgFunctionAsColumns().add( e1 ); + holder2.getEntityWithNoArgFunctionAsColumns().add( e2 ); + holder1.setNextHolder( holder2 ); + s.persist( holder1 ); + } ); + + factoryScope.inTransaction(s -> { + CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); + CriteriaQuery criteria = criteriaBuilder.createQuery( + EntityWithFunctionAsColumnHolder.class ); + Root root = criteria.from( EntityWithFunctionAsColumnHolder.class ); + root.fetch( "entityWithNoArgFunctionAsColumns", JoinType.LEFT ); + root.fetch( "nextHolder", JoinType.LEFT ) + .fetch( "entityWithNoArgFunctionAsColumns", JoinType.LEFT ); + criteria.where( criteriaBuilder.isNotNull( root.get( "nextHolder" ) ) ); + EntityWithFunctionAsColumnHolder holder = s.createQuery( criteria ).uniqueResult(); + + assertTrue( Hibernate.isInitialized( holder.getEntityWithNoArgFunctionAsColumns() ) ); + assertTrue( Hibernate.isInitialized( holder.getNextHolder() ) ); + assertTrue( Hibernate.isInitialized( holder.getNextHolder() + .getEntityWithNoArgFunctionAsColumns() ) ); + assertEquals( 1, holder.getEntityWithNoArgFunctionAsColumns().size() ); + EntityWithNoArgFunctionAsColumn e1 = (EntityWithNoArgFunctionAsColumn) holder.getEntityWithNoArgFunctionAsColumns() + .iterator() + .next(); + assertEquals( "blah blah blah", e1.getCurrentDate() ); + assertEquals( 1, holder.getNextHolder().getEntityWithNoArgFunctionAsColumns().size() ); + EntityWithNoArgFunctionAsColumn e2 = (EntityWithNoArgFunctionAsColumn) ( holder.getNextHolder() ).getEntityWithNoArgFunctionAsColumns() + .iterator() + .next(); + assertEquals( "yadda yadda yadda", e2.getCurrentDate() ); + } ); } @Test - public void testNoArgFcnAndColumnSameNameAsNoArgFunctionHQL() { - Assume.assumeFalse( - "current_date requires () but test is for noarg function that does not require ()", - sessionFactory().getJdbcServices().getDialect().currentDate().contains( "(" ) - ); - - EntityWithNoArgFunctionAsColumn e1 = new EntityWithNoArgFunctionAsColumn(); - EntityWithNoArgFunctionAsColumn e2 = new EntityWithNoArgFunctionAsColumn(); - - inTransaction( - s -> { - e1.setCurrentDate( "blah blah blah" ); - e2.setCurrentDate( "yadda yadda yadda" ); - EntityWithFunctionAsColumnHolder holder1 = new EntityWithFunctionAsColumnHolder(); - holder1.getEntityWithNoArgFunctionAsColumns().add( e1 ); - EntityWithFunctionAsColumnHolder holder2 = new EntityWithFunctionAsColumnHolder(); - holder2.getEntityWithNoArgFunctionAsColumns().add( e2 ); - holder1.setNextHolder( holder2 ); - s.persist( holder1 ); - } - ); - - inTransaction( - s -> { - List results = s.createQuery( - "select str(current_date), currentDate from EntityWithNoArgFunctionAsColumn" - ).list(); - assertEquals( 2, results.size() ); - assertEquals( ( (Object[]) results.get( 0 ) )[0], ( (Object[]) results.get( 1 ) )[0] ); - assertTrue( !( (Object[]) results.get( 0 ) )[0].equals( ( (Object[]) results.get( 0 ) )[1] ) ); - assertTrue( !( (Object[]) results.get( 1 ) )[0].equals( ( (Object[]) results.get( 1 ) )[1] ) ); - assertTrue( ( (Object[]) results.get( 0 ) )[1].equals( e1.getCurrentDate() ) || - ( (Object[]) results.get( 0 ) )[1].equals( e2.getCurrentDate() ) ); - assertTrue( ( (Object[]) results.get( 1 ) )[1].equals( e1.getCurrentDate() ) || - ( (Object[]) results.get( 1 ) )[1].equals( e2.getCurrentDate() ) ); - assertFalse( ( (Object[]) results.get( 0 ) )[1].equals( ( (Object[]) results.get( 1 ) )[1] ) ); - - } - ); + public void testNoArgFcnAndColumnSameNameAsNoArgFunctionHQL(SessionFactoryScope factoryScope) { + Assumptions.assumeFalse( dialectUsesParenForCurrentDate( factoryScope ), + "current_date requires () but test is for noarg function that does not require ()" ); + + MutableObject e1Ref = new MutableObject<>(); + MutableObject e2Ref = new MutableObject<>(); + + factoryScope.inTransaction( (s) -> { + EntityWithNoArgFunctionAsColumn e1 = new EntityWithNoArgFunctionAsColumn(); + EntityWithNoArgFunctionAsColumn e2 = new EntityWithNoArgFunctionAsColumn(); + + e1Ref.set( e1 ); + e2Ref.set( e2 ); + + e1.setCurrentDate( "blah blah blah" ); + e2.setCurrentDate( "yadda yadda yadda" ); + EntityWithFunctionAsColumnHolder holder1 = new EntityWithFunctionAsColumnHolder(); + holder1.getEntityWithNoArgFunctionAsColumns().add( e1 ); + EntityWithFunctionAsColumnHolder holder2 = new EntityWithFunctionAsColumnHolder(); + holder2.getEntityWithNoArgFunctionAsColumns().add( e2 ); + holder1.setNextHolder( holder2 ); + s.persist( holder1 ); + } ); + + factoryScope.inTransaction(s -> { + var hql = "select str(current_date), currentDate from EntityWithNoArgFunctionAsColumn"; + var results = s.createQuery( hql ).list(); + assertEquals( 2, results.size() ); + assertEquals( ( (Object[]) results.get( 0 ) )[0], ( (Object[]) results.get( 1 ) )[0] ); + assertNotEquals( ((Object[]) results.get( 0 ))[0], ((Object[]) results.get( 0 ))[1] ); + assertNotEquals( ((Object[]) results.get( 1 ))[0], ((Object[]) results.get( 1 ))[1] ); + assertTrue( ( (Object[]) results.get( 0 ) )[1].equals( e1Ref.get().getCurrentDate() ) || + ( (Object[]) results.get( 0 ) )[1].equals( e2Ref.get().getCurrentDate() ) ); + assertTrue( ( (Object[]) results.get( 1 ) )[1].equals( e1Ref.get().getCurrentDate() ) || + ( (Object[]) results.get( 1 ) )[1].equals( e2Ref.get().getCurrentDate() ) ); + assertNotEquals( ((Object[]) results.get( 0 ))[1], ((Object[]) results.get( 1 ))[1] ); + } ); } - @After - public void cleanup() { - inTransaction( - s -> { - s.createQuery( "delete from EntityWithArgFunctionAsColumn" ).executeUpdate(); - - } - ); - - inTransaction( - s -> { - s.createQuery( "delete from EntityWithNoArgFunctionAsColumn" ).executeUpdate(); - - } - ); - - inTransaction( - s -> { - s.createQuery( "delete from EntityWithFunctionAsColumnHolder where nextHolder is not null" ) - .executeUpdate(); - s.createQuery( "delete from EntityWithFunctionAsColumnHolder" ).executeUpdate(); - } - ); + private static boolean dialectUsesParenForCurrentDate(SessionFactoryScope factoryScope) { + return factoryScope.getSessionFactory().getJdbcServices().getDialect().currentDate().contains( "(" ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/HQLTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/HQLTest.java index 94c29e613d8b..7994df88d6e8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/HQLTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/HQLTest.java @@ -4,37 +4,24 @@ */ package org.hibernate.orm.test.hql; -import java.math.BigDecimal; -import java.time.Instant; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.Arrays; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.Stream; import jakarta.persistence.FlushModeType; import jakarta.persistence.Query; import jakarta.persistence.Tuple; import jakarta.persistence.TypedQuery; - import org.hibernate.CacheMode; import org.hibernate.ScrollableResults; import org.hibernate.Session; +import org.hibernate.community.dialect.DerbyDialect; import org.hibernate.community.dialect.FirebirdDialect; import org.hibernate.community.dialect.InformixDialect; import org.hibernate.dialect.CockroachDialect; -import org.hibernate.community.dialect.DerbyDialect; import org.hibernate.dialect.H2Dialect; import org.hibernate.dialect.MySQLDialect; import org.hibernate.dialect.OracleDialect; import org.hibernate.dialect.PostgreSQLDialect; import org.hibernate.dialect.SQLServerDialect; import org.hibernate.dialect.SybaseASEDialect; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; import org.hibernate.query.QueryProducer; -import org.hibernate.type.StandardBasicTypes; import org.hibernate.testing.orm.domain.userguide.Account; import org.hibernate.testing.orm.domain.userguide.AddressType; import org.hibernate.testing.orm.domain.userguide.Call; @@ -45,41 +32,59 @@ import org.hibernate.testing.orm.domain.userguide.Phone; import org.hibernate.testing.orm.domain.userguide.PhoneType; import org.hibernate.testing.orm.domain.userguide.WireTransferPayment; - -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.DialectFeatureChecks; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.ExpectedException; +import org.hibernate.testing.orm.junit.RequiresDialect; +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.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.type.StandardBasicTypes; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.math.BigDecimal; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Vlad Mihalcea */ -@SuppressWarnings("unused") -public class HQLTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class, - Call.class, - Account.class, - CreditCardPayment.class, - WireTransferPayment.class - }; - } - - @Before - public void init() { - doInJPA(this::entityManagerFactory, entityManager -> { +@SuppressWarnings({"unused", "JUnitMalformedDeclaration", "removal", "deprecation"}) +@DomainModel(annotatedClasses = { + Person.class, + Phone.class, + Call.class, + Account.class, + CreditCardPayment.class, + WireTransferPayment.class +}) +@SessionFactory +public class HQLTest { + + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); + } + + @BeforeEach + public void createTestData(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (entityManager) -> { Person person1 = new Person("John Doe"); person1.setNickName("JD"); person1.setAddress("Earth"); @@ -150,36 +155,36 @@ public void init() { entityManager.persist(creditCardPayment); entityManager.persist(wireTransferPayment); - }); + } ); } @Test - public void test_hql_select_simplest_example() { - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + public void test_hql_select_simplest_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { List objects = session.createQuery( - "from java.lang.Object", - Object.class) - .getResultList(); + "from java.lang.Object", + Object.class) + .getResultList(); //tag::hql-select-simplest-example[] List persons = session.createQuery( - "from Person", Person.class) - .getResultList(); + "from Person", Person.class) + .getResultList(); //end::hql-select-simplest-example[] //tag::hql-select-simplest-example-alt[] LocalDateTime datetime = session.createQuery( - "select local datetime", - LocalDateTime.class) - .getSingleResult(); + "select local datetime", + LocalDateTime.class) + .getSingleResult(); //end::hql-select-simplest-example-alt[] - }); + + } ); } @Test - public void test_hql_select_simplest_jpql_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_select_simplest_jpql_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (entityManager) -> { //tag::hql-select-simplest-jpql-example[] List persons = entityManager.createQuery( "select p " + @@ -199,11 +204,9 @@ public void test_hql_select_simplest_jpql_example() { } @Test - public void test_hql_select_no_from() { - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + public void test_hql_select_no_from(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { //tag::hql-select-no-from[] - // result type Person, only the Person selected List persons = session.createQuery( "from Person join phones", Person.class) @@ -226,8 +229,8 @@ public void test_hql_select_no_from() { } @Test - public void hql_update_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void hql_update_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-update-example[] entityManager.createQuery( "update Person set nickName = 'Nacho' " + @@ -238,8 +241,8 @@ public void hql_update_example() { } @Test - public void hql_insert_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void hql_insert_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-insert-example[] entityManager.createQuery( "insert Person (id, name) " + @@ -250,8 +253,8 @@ public void hql_insert_example() { } @Test - public void hql_multi_insert_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void hql_multi_insert_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-insert-example[] entityManager.createQuery( "insert Person (id, name) " + @@ -264,8 +267,8 @@ public void hql_multi_insert_example() { } @Test - public void hql_insert_with_sequence_example() { - doInJPA( this::entityManagerFactory, entityManager -> { + public void hql_insert_with_sequence_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { entityManager.createQuery( "insert Person (name) values ('Jane Doe2')" ) .executeUpdate(); @@ -273,8 +276,8 @@ public void hql_insert_with_sequence_example() { } @Test - public void hql_select_simplest_jpql_fqn_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void hql_select_simplest_jpql_fqn_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-select-simplest-jpql-fqn-example[] List persons = entityManager.createQuery( "select p " + @@ -286,8 +289,8 @@ public void hql_select_simplest_jpql_fqn_example() { } @Test - public void test_hql_multiple_root_reference_jpql_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_multiple_root_reference_jpql_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-multiple-root-reference-jpql-example[] List persons = entityManager.createQuery( "select distinct pr, ph " + @@ -301,8 +304,8 @@ public void test_hql_multiple_root_reference_jpql_example() { } @Test - public void test_hql_cross_join_jpql_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_cross_join_jpql_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-cross-join-jpql-example[] List persons = entityManager.createQuery( "select distinct pr, ph " + @@ -316,8 +319,8 @@ public void test_hql_cross_join_jpql_example() { } @Test - public void test_hql_multiple_same_root_reference_jpql_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_multiple_same_root_reference_jpql_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-multiple-same-root-reference-jpql-example[] List persons = entityManager.createQuery( "select distinct pr1 " + @@ -333,8 +336,8 @@ public void test_hql_multiple_same_root_reference_jpql_example() { } @Test - public void test_hql_explicit_root_join_example_1() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_explicit_root_join_example_1(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-explicit-root-join-example[] List persons = entityManager.createQuery( "select distinct pr " + @@ -350,8 +353,8 @@ public void test_hql_explicit_root_join_example_1() { } @Test - public void test_hql_explicit_inner_join_example_1() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_explicit_inner_join_example_1(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-explicit-inner-join-example[] List persons = entityManager.createQuery( "select distinct pr " + @@ -367,8 +370,8 @@ public void test_hql_explicit_inner_join_example_1() { } @Test - public void test_hql_explicit_inner_join_example_2() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_explicit_inner_join_example_2(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-explicit-inner-join-example[] // same query, but specifying join type as 'inner' explicitly @@ -386,8 +389,8 @@ public void test_hql_explicit_inner_join_example_2() { } @Test - public void test_hql_explicit_outer_join_example_1() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_explicit_outer_join_example_1(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-explicit-outer-join-example[] List persons = entityManager.createQuery( "select distinct pr " + @@ -404,8 +407,8 @@ public void test_hql_explicit_outer_join_example_1() { } @Test - public void test_hql_explicit_outer_join_example_2() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_explicit_outer_join_example_2(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-explicit-outer-join-example[] // same query, but specifying join type as 'outer' explicitly @@ -424,8 +427,8 @@ public void test_hql_explicit_outer_join_example_2() { } @Test - public void test_hql_explicit_fetch_join_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_explicit_fetch_join_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-explicit-fetch-join-example[] List persons = entityManager.createQuery( "select distinct pr " + @@ -439,8 +442,8 @@ public void test_hql_explicit_fetch_join_example() { } @Test - public void test_hql_explicit_join_with_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_explicit_join_with_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { Session session = entityManager.unwrap(Session.class); //tag::hql-explicit-join-with-example[] List personsAndPhones = session.createQuery( @@ -456,8 +459,8 @@ public void test_hql_explicit_join_with_example() { } @Test - public void test_jpql_explicit_join_on_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_jpql_explicit_join_on_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-explicit-join-jpql-on-example[] List personsAndPhones = entityManager.createQuery( "select pr.name, ph.number " + @@ -472,8 +475,8 @@ public void test_jpql_explicit_join_on_example() { } @Test - public void test_hql_implicit_join_example_1() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_implicit_join_example_1(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { String address = "Earth"; //tag::hql-implicit-join-example[] List phones = entityManager.createQuery( @@ -489,8 +492,8 @@ public void test_hql_implicit_join_example_1() { } @Test - public void test_hql_implicit_join_example_2() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_implicit_join_example_2(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { String address = "Earth"; //tag::hql-implicit-join-example[] @@ -509,8 +512,8 @@ public void test_hql_implicit_join_example_2() { } @Test - public void test_hql_implicit_join_alias_example_1() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_implicit_join_alias_example_1(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { String address = "Earth"; LocalDateTime timestamp = LocalDateTime.ofInstant(Instant.EPOCH, ZoneId.systemDefault()); //tag::hql-implicit-join-alias-example[] @@ -529,8 +532,8 @@ public void test_hql_implicit_join_alias_example_1() { } @Test - public void test_hql_implicit_join_alias_example_2() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_implicit_join_alias_example_2(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { String address = "Earth"; LocalDateTime timestamp = LocalDateTime.ofInstant(Instant.EPOCH, ZoneId.systemDefault()); //tag::hql-implicit-join-alias-example[] @@ -552,8 +555,8 @@ public void test_hql_implicit_join_alias_example_2() { } @Test - public void test_hql_collection_valued_associations_1() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_collection_valued_associations_1(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { String address = "Earth"; int duration = 20; //tag::hql-collection-valued-associations[] @@ -578,8 +581,8 @@ public void test_hql_collection_valued_associations_1() { @Test // we do not need to document this syntax, which is a // legacy of EJB entity beans, prior to JPA / EJB 3 - public void test_hql_collection_valued_associations_2() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_collection_valued_associations_2(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { Session session = entityManager.unwrap(Session.class); String address = "Earth"; int duration = 20; @@ -604,9 +607,8 @@ public void test_hql_collection_valued_associations_2() { } @Test - public void test_hql_collection_qualification_associations_1() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_collection_qualification_associations_1(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { Long id = 1L; //tag::hql-collection-qualification-example[] @@ -628,8 +630,8 @@ public void test_hql_collection_qualification_associations_1() { } @Test - public void test_hql_collection_qualification_associations_2() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_collection_qualification_associations_2(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { Long id = 1L; //tag::hql-collection-qualification-example[] @@ -648,8 +650,8 @@ public void test_hql_collection_qualification_associations_2() { } @Test - public void test_hql_collection_qualification_associations_3() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_collection_qualification_associations_3(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { Long id = 1L; //tag::hql-collection-qualification-example[] @@ -669,8 +671,8 @@ public void test_hql_collection_qualification_associations_3() { } @Test - public void test_hql_collection_qualification_associations_4() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_collection_qualification_associations_4(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { Long id = 1L; //tag::hql-collection-qualification-example[] @@ -689,8 +691,8 @@ public void test_hql_collection_qualification_associations_4() { } @Test - public void test_hql_collection_qualification_associations_5() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_collection_qualification_associations_5(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { Long id = 1L; Integer phoneIndex = 0; @@ -715,8 +717,8 @@ public void test_hql_collection_qualification_associations_5() { } @Test - public void test_hql_collection_implicit_join_1() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_collection_implicit_join_1(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { Long id = 1L; //tag::hql-collection-implicit-join-example[] @@ -734,8 +736,8 @@ public void test_hql_collection_implicit_join_1() { } @Test - public void test_hql_collection_implicit_join_2() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_collection_implicit_join_2(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { Long id = 1L; //tag::hql-collection-implicit-join-example[] @@ -753,8 +755,8 @@ public void test_hql_collection_implicit_join_2() { } @Test - public void test_projection_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_projection_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::jpql-projection-example[] List results = entityManager.createQuery( "select p.name, p.nickName " + @@ -780,8 +782,8 @@ public void test_projection_example() { } @Test - public void test_union_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_union_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-union-example[] List results = entityManager.createQuery( "select p.name from Person p " + @@ -794,8 +796,8 @@ public void test_union_example() { }); } @Test - public void test_jpql_api_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_jpql_api_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::jpql-api-example[] Query query = entityManager.createQuery( "select p " + @@ -814,8 +816,8 @@ public void test_jpql_api_example() { } @Test - public void test_jpql_api_named_query_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_jpql_api_named_query_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::jpql-api-named-query-example[] Query query = entityManager.createNamedQuery("get_person_by_name"); @@ -825,8 +827,8 @@ public void test_jpql_api_named_query_example() { } @Test - public void test_jpql_api_hibernate_named_query_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_jpql_api_hibernate_named_query_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::jpql-api-hibernate-named-query-example[] Phone phone = entityManager .createNamedQuery("get_phone_by_number", Phone.class) @@ -838,9 +840,9 @@ public void test_jpql_api_hibernate_named_query_example() { } @Test - public void test_jpql_api_basic_usage_example() { + public void test_jpql_api_basic_usage_example(SessionFactoryScope factoryScope) { int page = 1; - doInJPA(this::entityManagerFactory, entityManager -> { + factoryScope.inTransaction( entityManager -> { //tag::jpql-api-basic-usage-example[] Person person = entityManager.createQuery( "select p " + @@ -865,8 +867,8 @@ public void test_jpql_api_basic_usage_example() { } @Test - public void test_jpql_api_hint_usage_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_jpql_api_hint_usage_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::jpql-api-hint-usage-example[] Person query = entityManager.createQuery( "select p " + @@ -884,8 +886,8 @@ public void test_jpql_api_hint_usage_example() { } @Test - public void test_jpql_api_parameter_example_1() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_jpql_api_parameter_example_1(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::jpql-api-parameter-example[] Query query = entityManager.createQuery( "select p " + @@ -897,8 +899,8 @@ public void test_jpql_api_parameter_example_1() { } @Test - public void test_jpql_api_parameter_example_2() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_jpql_api_parameter_example_2(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { LocalDateTime timestamp = LocalDateTime.now(); //tag::jpql-api-parameter-example[] @@ -912,8 +914,8 @@ public void test_jpql_api_parameter_example_2() { } @Test - public void test_jpql_api_positional_parameter_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_jpql_api_positional_parameter_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::jpql-api-ordinal-parameter-example[] TypedQuery query = entityManager.createQuery( "select p " + @@ -926,8 +928,8 @@ public void test_jpql_api_positional_parameter_example() { } @Test - public void test_jpql_api_list_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_jpql_api_list_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::jpql-api-list-example[] List persons = entityManager.createQuery( "select p " + @@ -941,8 +943,8 @@ public void test_jpql_api_list_example() { } @Test - public void test_jpql_api_stream_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_jpql_api_stream_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::jpql-api-stream-example[] try(Stream personStream = entityManager.createQuery( "select p " + @@ -954,15 +956,15 @@ public void test_jpql_api_stream_example() { List persons = personStream .skip(5) .limit(5) - .collect(Collectors.toList()); + .toList(); } //end::jpql-api-stream-example[] }); } @Test - public void test_jpql_api_single_result_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_jpql_api_single_result_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::jpql-api-single-result-example[] Person person = (Person) entityManager.createQuery( "select p " + @@ -975,8 +977,8 @@ public void test_jpql_api_single_result_example() { } @Test - public void test_hql_api_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_api_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { QueryProducer session = entityManager.unwrap(Session.class); //tag::hql-api-example[] org.hibernate.query.Query query = session.createQuery( @@ -989,8 +991,8 @@ public void test_hql_api_example() { } @Test - public void test_hql_api_named_query_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_api_named_query_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { QueryProducer session = entityManager.unwrap(Session.class); //tag::hql-api-named-query-example[] org.hibernate.query.Query query = session.createNamedQuery( @@ -1001,8 +1003,8 @@ public void test_hql_api_named_query_example() { } @Test - public void test_hql_api_basic_usage_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_api_basic_usage_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { QueryProducer session = entityManager.unwrap(Session.class); //tag::hql-api-basic-usage-example[] org.hibernate.query.Query query = session.createQuery( @@ -1023,8 +1025,8 @@ public void test_hql_api_basic_usage_example() { } @Test - public void test_hql_api_parameter_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_api_parameter_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { QueryProducer session = entityManager.unwrap(Session.class); //tag::hql-api-parameter-example[] org.hibernate.query.Query query = session.createQuery( @@ -1038,8 +1040,8 @@ public void test_hql_api_parameter_example() { } @Test - public void test_hql_api_parameter_inferred_type_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_api_parameter_inferred_type_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { QueryProducer session = entityManager.unwrap(Session.class); //tag::hql-api-parameter-inferred-type-example[] org.hibernate.query.Query query = session.createQuery( @@ -1053,8 +1055,8 @@ public void test_hql_api_parameter_inferred_type_example() { } @Test - public void test_hql_api_parameter_short_form_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_api_parameter_short_form_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { LocalDateTime timestamp = LocalDateTime.now(); QueryProducer session = entityManager.unwrap(Session.class); //tag::hql-api-parameter-short-form-example[] @@ -1070,9 +1072,10 @@ public void test_hql_api_parameter_short_form_example() { }); } - @Test(expected = IllegalArgumentException.class) - public void test_hql_api_positional_parameter_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + @Test + @ExpectedException( IllegalArgumentException.class ) + public void test_hql_api_positional_parameter_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { Date timestamp = new Date(); QueryProducer session = entityManager.unwrap(Session.class); //tag::hql-api-ordinal-parameter-example[] @@ -1087,8 +1090,8 @@ public void test_hql_api_positional_parameter_example() { } @Test - public void test_hql_api_list_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_api_list_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { QueryProducer session = entityManager.unwrap(Session.class); //tag::hql-api-list-example[] List persons = session.createQuery( @@ -1103,8 +1106,8 @@ public void test_hql_api_list_example() { } @Test - public void test_hql_api_stream_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_api_stream_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { QueryProducer session = entityManager.unwrap(Session.class); //tag::hql-api-stream-example[] try(Stream persons = session.createQuery( @@ -1130,8 +1133,8 @@ private void process(Map> callRegistry) { } @Test - public void test_hql_api_stream_projection_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_api_stream_projection_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { QueryProducer session = entityManager.unwrap(Session.class); //tag::hql-api-stream-projection-example[] try (Stream persons = session.createQuery( @@ -1149,8 +1152,8 @@ public void test_hql_api_stream_projection_example() { } @Test - public void test_hql_api_scroll_projection_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_api_scroll_projection_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { QueryProducer session = entityManager.unwrap(Session.class); //tag::hql-api-scroll-example[] try (ScrollableResults scrollableResults = session.createQuery( @@ -1171,17 +1174,18 @@ public void test_hql_api_scroll_projection_example() { } @Test - public void test_hql_api_scroll_open_example() { - ScrollableResults scrollableResults = doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_api_scroll_open_example(SessionFactoryScope factoryScope) { + //noinspection resource + ScrollableResults scrollableResults = factoryScope.fromTransaction( entityManager -> { QueryProducer session = entityManager.unwrap(Session.class); return session.createQuery( - "select p " + - "from Person p " + - "where p.name like :name", - Person.class) - .setParameter("name", "J%") - .scroll(); - }); + "select p " + + "from Person p " + + "where p.name like :name", + Person.class) + .setParameter("name", "J%") + .scroll(); + } ); try { scrollableResults.next(); fail("Should throw exception because the ResultSet must be closed by now!"); @@ -1197,8 +1201,8 @@ private void process(PersonNames personName) { } @Test - public void test_hql_api_unique_result_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_api_unique_result_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { Session session = entityManager.unwrap(Session.class); //tag::hql-api-unique-result-example[] Person person = session.createQuery( @@ -1213,8 +1217,8 @@ public void test_hql_api_unique_result_example() { } @Test - public void test_hql_string_literals_example_1() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_string_literals_example_1(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-string-literals-example[] List persons = entityManager.createQuery( "select p " + @@ -1227,8 +1231,8 @@ public void test_hql_string_literals_example_1() { } @Test - public void test_hql_string_literals_example_2() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_string_literals_example_2(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-string-literals-example[] // Escaping quotes @@ -1243,8 +1247,8 @@ public void test_hql_string_literals_example_2() { } @Test - public void test_hql_string_literals_example_3() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_string_literals_example_3(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-numeric-literals-example[] // simple integer literal Person person = entityManager.createQuery( @@ -1258,8 +1262,8 @@ public void test_hql_string_literals_example_3() { } @Test - public void test_hql_string_literals_example_4() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_string_literals_example_4(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-numeric-literals-example[] // simple integer literal, typed as a long @@ -1274,8 +1278,8 @@ public void test_hql_string_literals_example_4() { } @Test - public void test_hql_string_literals_example_5() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_string_literals_example_5(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-numeric-literals-example[] // decimal notation @@ -1290,8 +1294,8 @@ public void test_hql_string_literals_example_5() { } @Test - public void test_hql_string_literals_example_6() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_string_literals_example_6(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-numeric-literals-example[] // decimal notation, typed as a float @@ -1306,8 +1310,8 @@ public void test_hql_string_literals_example_6() { } @Test - public void test_hql_string_literals_example_7() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_string_literals_example_7(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-numeric-literals-example[] // scientific notation @@ -1322,8 +1326,8 @@ public void test_hql_string_literals_example_7() { } @Test - public void test_hql_string_literals_example_8() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_string_literals_example_8(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-numeric-literals-example[] // scientific notation, typed as a float @@ -1339,8 +1343,8 @@ public void test_hql_string_literals_example_8() { } @Test - public void test_hql_java_constant_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_java_constant_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-java-constant-example[] // select clause date/time arithmetic operations Double pi = entityManager.createQuery( @@ -1353,8 +1357,8 @@ public void test_hql_java_constant_example() { } @Test - public void test_hql_enum_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_enum_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-enum-example[] // select clause date/time arithmetic operations List phones1 = entityManager.createQuery( @@ -1368,8 +1372,8 @@ public void test_hql_enum_example() { @Test - public void test_hql_numeric_arithmetic_example_1() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_numeric_arithmetic_example_1(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-numeric-arithmetic-example[] // select clause date/time arithmetic operations Long duration = entityManager.createQuery( @@ -1382,13 +1386,13 @@ public void test_hql_numeric_arithmetic_example_1() { .setParameter("multiplier", 1000L) .getSingleResult(); //end::hql-numeric-arithmetic-example[] - assertTrue(duration > 0); + assertTrue( duration > 0 ); }); } @Test - public void test_hql_numeric_arithmetic_example_2() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_numeric_arithmetic_example_2(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-numeric-arithmetic-example[] // select clause date/time arithmetic operations @@ -1399,13 +1403,13 @@ public void test_hql_numeric_arithmetic_example_2() { Integer.class) .getSingleResult(); //end::hql-numeric-arithmetic-example[] - assertTrue(years > 0); + assertTrue( years > 0 ); }); } @Test - public void test_hql_numeric_arithmetic_example_3() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_numeric_arithmetic_example_3(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-numeric-arithmetic-example[] // where clause arithmetic operations @@ -1416,13 +1420,13 @@ public void test_hql_numeric_arithmetic_example_3() { Person.class) .getResultList(); //end::hql-numeric-arithmetic-example[] - assertTrue(persons.size() > 0); + assertFalse( persons.isEmpty() ); }); } @Test - public void test_hql_concatenation_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_concatenation_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-concatenation-example[] String name = entityManager.createQuery( "select 'Customer ' || p.name " + @@ -1436,8 +1440,8 @@ public void test_hql_concatenation_example() { } @Test - public void test_hql_aggregate_functions_example_1() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_aggregate_functions_example_1(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-aggregate-functions-example[] Object[] callStatistics = entityManager.createQuery( "select " + @@ -1455,8 +1459,8 @@ public void test_hql_aggregate_functions_example_1() { } @Test - public void test_hql_aggregate_functions_example_2() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_aggregate_functions_example_2(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-aggregate-functions-example[] Long phoneCount = entityManager.createQuery( @@ -1470,8 +1474,8 @@ public void test_hql_aggregate_functions_example_2() { } @Test - public void test_hql_aggregate_functions_example_3() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_aggregate_functions_example_3(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-aggregate-functions-example[] List callCount = entityManager.createQuery( @@ -1487,8 +1491,8 @@ public void test_hql_aggregate_functions_example_3() { } @Test - public void test_hql_aggregate_functions_simple_filter_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_aggregate_functions_simple_filter_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-aggregate-functions-simple-filter-example[] List callCount = entityManager.createQuery( @@ -1502,8 +1506,8 @@ public void test_hql_aggregate_functions_simple_filter_example() { } @Test - public void test_hql_aggregate_functions_filter_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_aggregate_functions_filter_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-aggregate-functions-filter-example[] List callCount = entityManager.createQuery( @@ -1523,8 +1527,8 @@ public void test_hql_aggregate_functions_filter_example() { @SkipForDialect(dialectClass = SybaseASEDialect.class) @SkipForDialect(dialectClass = FirebirdDialect.class, reason = "order by not supported in list") @SkipForDialect(dialectClass = InformixDialect.class) - public void test_hql_aggregate_functions_within_group_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_aggregate_functions_within_group_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-aggregate-functions-within-group-example[] List callCount = entityManager.createQuery( @@ -1540,8 +1544,8 @@ public void test_hql_aggregate_functions_within_group_example() { @Test @SkipForDialect(dialectClass = DerbyDialect.class, reason = "See https://issues.apache.org/jira/browse/DERBY-2072") - public void test_hql_concat_function_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_concat_function_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-concat-function-example[] List callHistory = entityManager.createQuery( "select concat(p.number, ' : ' , cast(c.duration as string)) " + @@ -1555,8 +1559,8 @@ public void test_hql_concat_function_example() { } @Test - public void test_hql_substring_function_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_substring_function_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-substring-function-example[] // JPQL-style @@ -1581,8 +1585,8 @@ public void test_hql_substring_function_example() { } @Test - public void test_hql_upper_function_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_upper_function_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-upper-function-example[] List names = entityManager.createQuery( "select upper(p.name) " + @@ -1595,8 +1599,8 @@ public void test_hql_upper_function_example() { } @Test - public void test_hql_lower_function_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_lower_function_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-lower-function-example[] List names = entityManager.createQuery( "select lower(p.name) " + @@ -1609,8 +1613,8 @@ public void test_hql_lower_function_example() { } @Test - public void test_hql_trim_function_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_trim_function_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-trim-function-example[] // trim whitespace from both ends @@ -1633,8 +1637,8 @@ public void test_hql_trim_function_example() { } @Test - public void test_hql_length_function_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_length_function_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-length-function-example[] List lengths = entityManager.createQuery( "select length(p.name) " + @@ -1647,8 +1651,8 @@ public void test_hql_length_function_example() { } @Test - public void test_hql_locate_function_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_locate_function_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-locate-function-example[] List sizes = entityManager.createQuery( "select locate('John', p.name) " + @@ -1661,8 +1665,8 @@ public void test_hql_locate_function_example() { } @Test - public void test_hql_position_function_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_position_function_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-position-function-example[] List sizes = entityManager.createQuery( "select position('John' in p.name) " + @@ -1675,8 +1679,8 @@ public void test_hql_position_function_example() { } @Test - public void test_hql_abs_function_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_abs_function_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-abs-function-example[] List abs = entityManager.createQuery( "select abs(c.duration) " + @@ -1689,8 +1693,8 @@ public void test_hql_abs_function_example() { } @Test - public void test_hql_mod_function_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_mod_function_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-mod-function-example[] List mods = entityManager.createQuery( "select mod(c.duration, 10) " + @@ -1704,8 +1708,8 @@ public void test_hql_mod_function_example() { @Test @SkipForDialect(dialectClass = CockroachDialect.class, reason = "https://github.com/cockroachdb/cockroach/issues/26710") - public void test_hql_sqrt_function_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_sqrt_function_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-sqrt-function-example[] List sqrts = entityManager.createQuery( "select sqrt(c.duration) " + @@ -1720,8 +1724,8 @@ public void test_hql_sqrt_function_example() { @Test @SkipForDialect(dialectClass = SQLServerDialect.class) @SkipForDialect(dialectClass = DerbyDialect.class, reason = "Comparisons between 'DATE' and 'TIMESTAMP' are not supported") - public void test_hql_current_date_function_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_current_date_function_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-current-date-function-example[] List calls = entityManager.createQuery( "select c " + @@ -1735,8 +1739,8 @@ public void test_hql_current_date_function_example() { } @Test - public void test_hql_current_date_function_example_sql_server() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_current_date_function_example_sql_server(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-extract-function-example[] List calls = entityManager.createQuery( "select c " + @@ -1752,8 +1756,8 @@ public void test_hql_current_date_function_example_sql_server() { @Test @RequiresDialect(H2Dialect.class) - public void test_hql_current_time_function_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_current_time_function_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-current-time-function-example[] List calls = entityManager.createQuery( "select c " + @@ -1767,8 +1771,8 @@ public void test_hql_current_time_function_example() { } @Test - public void test_hql_current_timestamp_function_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_current_timestamp_function_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-current-timestamp-function-example[] List calls = entityManager.createQuery( "select c " + @@ -1782,9 +1786,8 @@ public void test_hql_current_timestamp_function_example() { } @Test -// @RequiresDialect({MySQLDialect.class, PostgreSQLDialect.class, H2Dialect.class, DerbyDialect.class, OracleDialect.class}) - public void test_var_function_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_var_function_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-native-function-example[] // careful: these functions are not supported on all databases! @@ -1802,8 +1805,8 @@ public void test_var_function_example() { @RequiresDialect(MySQLDialect.class) @RequiresDialect(PostgreSQLDialect.class) @RequiresDialect(OracleDialect.class) - public void test_hql_bit_length_function_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_bit_length_function_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-native-function-example[] List bits = entityManager.createQuery( @@ -1817,8 +1820,8 @@ public void test_hql_bit_length_function_example() { } @Test - public void test_hql_cast_function_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_cast_function_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-cast-function-example[] List durations = entityManager.createQuery( "select cast(c.duration as String) " + @@ -1831,8 +1834,8 @@ public void test_hql_cast_function_example() { } @Test - public void test_hql_extract_function_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_extract_function_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-extract-function-example[] List years = entityManager.createQuery( "select extract(year from c.timestamp) " + @@ -1845,8 +1848,8 @@ public void test_hql_extract_function_example() { } @Test - public void test_hql_year_function_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_year_function_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-year-function-example[] List years = entityManager.createQuery( "select year(c.timestamp) " + @@ -1860,8 +1863,8 @@ public void test_hql_year_function_example() { @Test @SkipForDialect(dialectClass = SQLServerDialect.class) - public void test_hql_str_function_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_str_function_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-str-function-example[] List timestamps = entityManager.createQuery( "select str(c.timestamp) " + @@ -1875,8 +1878,8 @@ public void test_hql_str_function_example() { @Test @RequiresDialect(SQLServerDialect.class) - public void test_hql_str_function_example_sql_server() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_str_function_example_sql_server(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-str-function-example[] // Special SQL Server function "str" that converts floats List timestamps = entityManager.createQuery( @@ -1890,8 +1893,8 @@ public void test_hql_str_function_example_sql_server() { } @Test - public void test_hql_collection_expressions_example_1() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_collection_expressions_example_1(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { Call call = entityManager.createQuery("select c from Call c", Call.class).getResultList().get(1); //tag::hql-collection-expressions-example[] List phones = entityManager.createQuery( @@ -1907,8 +1910,8 @@ public void test_hql_collection_expressions_example_1() { } @Test - public void test_hql_collection_expressions_example_2() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_collection_expressions_example_2(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { Call call = entityManager.createQuery("select c from Call c", Call.class).getResultList().get(0); //tag::hql-collection-expressions-example[] @@ -1925,8 +1928,8 @@ public void test_hql_collection_expressions_example_2() { } @Test - public void test_hql_collection_expressions_example_3() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_collection_expressions_example_3(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-collection-expressions-example[] List persons = entityManager.createQuery( @@ -1941,8 +1944,8 @@ public void test_hql_collection_expressions_example_3() { } @Test - public void test_hql_collection_expressions_example_5() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_collection_expressions_example_5(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { Call call = entityManager.createQuery("select c from Call c", Call.class).getResultList().get(0); Phone phone = call.getPhone(); //tag::hql-collection-expressions-some-example[] @@ -1960,8 +1963,8 @@ public void test_hql_collection_expressions_example_5() { } @Test - public void test_hql_collection_expressions_example_4() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_collection_expressions_example_4(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { Call call = entityManager.createQuery("select c from Call c", Call.class).getResultList().get(0); Phone phone = call.getPhone(); //tag::hql-collection-expressions-some-example[] @@ -1980,8 +1983,8 @@ public void test_hql_collection_expressions_example_4() { } @Test - public void test_hql_collection_expressions_example_6() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_collection_expressions_example_6(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-collection-expressions-exists-example[] List persons = entityManager.createQuery( @@ -1997,8 +2000,8 @@ public void test_hql_collection_expressions_example_6() { @Test @SkipForDialect(dialectClass = DerbyDialect.class, reason = "Comparisons between 'DATE' and 'TIMESTAMP' are not supported") - public void test_hql_collection_expressions_example_8() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_collection_expressions_example_8(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-collection-expressions-all-example[] List phones = entityManager.createQuery( @@ -2013,8 +2016,8 @@ public void test_hql_collection_expressions_example_8() { } @Test - public void test_hql_collection_expressions_example_9() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_collection_expressions_example_9(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-collection-expressions-in-example[] List persons = entityManager.createQuery( @@ -2029,8 +2032,8 @@ public void test_hql_collection_expressions_example_9() { } @Test - public void test_hql_collection_expressions_example_10() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_collection_expressions_example_10(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-size-example[] List persons = entityManager.createQuery( @@ -2045,8 +2048,8 @@ public void test_hql_collection_expressions_example_10() { } @Test - public void test_collection_index_operator_example_1() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_collection_index_operator_example_1(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-collection-index-operator-example[] // indexed lists List persons = entityManager.createQuery( @@ -2061,8 +2064,8 @@ public void test_collection_index_operator_example_1() { } @Test - public void test_hql_collection_index_operator_example_2() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_collection_index_operator_example_2(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { String address = "Home address"; //tag::hql-collection-index-operator-example[] @@ -2080,9 +2083,9 @@ public void test_hql_collection_index_operator_example_2() { } @Test - @RequiresDialectFeature(DialectChecks.SupportsSubqueryInOnClause.class) - public void test_hql_collection_index_operator_example_3() { - doInJPA(this::entityManagerFactory, entityManager -> { + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsSubqueryInOnClause.class) + public void test_hql_collection_index_operator_example_3(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-collection-index-operator-example[] //max index in list @@ -2098,8 +2101,8 @@ public void test_hql_collection_index_operator_example_3() { } @Test - public void test_hql_polymorphism_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_polymorphism_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-polymorphism-example[] List payments = entityManager.createQuery( "select p " + @@ -2112,8 +2115,8 @@ public void test_hql_polymorphism_example() { } @Test - public void test_hql_treat_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_treat_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-treat-example[] List payments = entityManager.createQuery( "select p " + @@ -2127,8 +2130,8 @@ public void test_hql_treat_example() { } @Test - public void test_hql_join_many_treat_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_join_many_treat_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-join-treat-example[] // a to-many association List payments = entityManager.createQuery( @@ -2144,8 +2147,8 @@ public void test_hql_join_many_treat_example() { } @Test - public void test_hql_join_one_treat_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_join_one_treat_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-join-treat-example[] // a to-one association @@ -2162,8 +2165,8 @@ public void test_hql_join_one_treat_example() { } @Test - public void test_hql_entity_type_exp_example_1() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_entity_type_exp_example_1(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-entity-type-exp-example[] List payments = entityManager.createQuery( "select p " + @@ -2177,8 +2180,8 @@ public void test_hql_entity_type_exp_example_1() { } @Test - public void test_hql_entity_type_exp_example_2() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_entity_type_exp_example_2(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-entity-type-exp-example[] // using a parameter instead of a literal entity type @@ -2195,8 +2198,8 @@ public void test_hql_entity_type_exp_example_2() { } @Test - public void test_hql_entity_type_exp_example_3() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_entity_type_exp_example_3(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-entity-type-exp-example[] // using a parameter instead of a literal entity type @@ -2213,8 +2216,8 @@ public void test_hql_entity_type_exp_example_3() { } @Test - public void test_simple_case_expressions_example_1() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_simple_case_expressions_example_1(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-simple-case-expressions-example[] List nickNames = entityManager.createQuery( "select " + @@ -2232,8 +2235,8 @@ public void test_simple_case_expressions_example_1() { } @Test - public void test_simple_case_expressions_example_2() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_simple_case_expressions_example_2(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-coalesce-example[] List nickNames = entityManager.createQuery( "select coalesce(p.nickName, '') " + @@ -2246,8 +2249,8 @@ public void test_simple_case_expressions_example_2() { } @Test - public void test_searched_case_expressions_example_1() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_searched_case_expressions_example_1(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-searched-case-expressions-example[] List nickNames = entityManager.createQuery( "select " + @@ -2270,8 +2273,8 @@ public void test_searched_case_expressions_example_1() { } @Test - public void test_searched_case_expressions_example_2() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_searched_case_expressions_example_2(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-coalesce-example[] List nickNames = entityManager.createQuery( @@ -2285,8 +2288,8 @@ public void test_searched_case_expressions_example_2() { } @Test - public void test_case_arithmetic_expressions_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_case_arithmetic_expressions_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-case-arithmetic-expressions-example[] List values = entityManager.createQuery( "select " + @@ -2308,8 +2311,8 @@ public void test_case_arithmetic_expressions_example() { } @Test - public void test_hql_null_if_example_1() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_null_if_example_1(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-nullif-example[] List nickNames = entityManager.createQuery( "select nullif(p.nickName, p.name) " + @@ -2322,8 +2325,8 @@ public void test_hql_null_if_example_1() { } @Test - public void test_hql_null_if_example_2() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_null_if_example_2(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-nullif-example[] // equivalent CASE expression @@ -2343,8 +2346,8 @@ public void test_hql_null_if_example_2() { } @Test - public void test_hql_select_clause_dynamic_instantiation_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_select_clause_dynamic_instantiation_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-select-clause-dynamic-instantiation-example[] CallStatistics callStatistics = entityManager.createQuery( "select new org.hibernate.orm.test.hql.CallStatistics(" + @@ -2363,8 +2366,8 @@ public void test_hql_select_clause_dynamic_instantiation_example() { } @Test - public void test_hql_select_clause_dynamic_list_instantiation_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_select_clause_dynamic_list_instantiation_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-select-clause-dynamic-list-instantiation-example[] List phoneCallDurations = entityManager.createQuery( "select new list(" + @@ -2381,9 +2384,8 @@ public void test_hql_select_clause_dynamic_list_instantiation_example() { } @Test - public void test_hql_select_clause_dynamic_map_instantiation_example() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_select_clause_dynamic_map_instantiation_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-select-clause-dynamic-map-instantiation-example[] List phoneCallTotalDurations = entityManager.createQuery( "select new map(" + @@ -2402,9 +2404,8 @@ public void test_hql_select_clause_dynamic_map_instantiation_example() { } @Test - public void test_hql_relational_comparisons_example_1() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_relational_comparisons_example_1(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-relational-comparisons-example[] // numeric comparison List calls = entityManager.createQuery( @@ -2419,9 +2420,8 @@ public void test_hql_relational_comparisons_example_1() { } @Test - public void test_hql_relational_comparisons_example_2() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_relational_comparisons_example_2(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-relational-comparisons-example[] // string comparison @@ -2440,9 +2440,8 @@ public void test_hql_relational_comparisons_example_2() { @RequiresDialect(H2Dialect.class) @RequiresDialect(PostgreSQLDialect.class) @RequiresDialect(MySQLDialect.class) - public void test_hql_relational_comparisons_example_3() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_relational_comparisons_example_3(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-relational-comparisons-example[] // datetime comparison @@ -2458,9 +2457,8 @@ public void test_hql_relational_comparisons_example_3() { } @Test - public void test_hql_relational_comparisons_example_4() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_relational_comparisons_example_4(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-relational-comparisons-example[] // enum comparison @@ -2476,9 +2474,8 @@ public void test_hql_relational_comparisons_example_4() { } @Test - public void test_hql_relational_comparisons_example_5() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_relational_comparisons_example_5(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-relational-comparisons-example[] // boolean comparison @@ -2494,9 +2491,8 @@ public void test_hql_relational_comparisons_example_5() { } @Test - public void test_hql_relational_comparisons_example_6() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_relational_comparisons_example_6(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-relational-comparisons-example[] // boolean comparison @@ -2512,9 +2508,8 @@ public void test_hql_relational_comparisons_example_6() { } @Test - public void test_hql_relational_comparisons_example_7() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_relational_comparisons_example_7(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-relational-comparisons-example[] // entity value comparison @@ -2530,9 +2525,8 @@ public void test_hql_relational_comparisons_example_7() { } @Test - public void test_hql_all_subquery_comparison_qualifier_example() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_all_subquery_comparison_qualifier_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-all-subquery-comparison-qualifier-example[] // select all persons with all calls shorter than 50 seconds List persons = entityManager.createQuery( @@ -2551,9 +2545,8 @@ public void test_hql_all_subquery_comparison_qualifier_example() { } @Test - public void test_hql_null_predicate_example_1() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_null_predicate_example_1(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-null-predicate-example[] // select all persons with a nickname List persons = entityManager.createQuery( @@ -2568,9 +2561,8 @@ public void test_hql_null_predicate_example_1() { } @Test - public void test_hql_null_predicate_example_2() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_null_predicate_example_2(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-null-predicate-example[] // select all persons without a nickname @@ -2586,9 +2578,8 @@ public void test_hql_null_predicate_example_2() { } @Test - public void test_hql_like_predicate_example_1() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_like_predicate_example_1(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-like-predicate-example[] List persons = entityManager.createQuery( "select p " + @@ -2602,9 +2593,8 @@ public void test_hql_like_predicate_example_1() { } @Test - public void test_hql_like_predicate_example_2() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_like_predicate_example_2(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-like-predicate-example[] List persons = entityManager.createQuery( @@ -2619,9 +2609,8 @@ public void test_hql_like_predicate_example_2() { } @Test - public void test_hql_like_predicate_escape_example() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_like_predicate_escape_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-like-predicate-escape-example[] // find any person with a name starting with "Dr_" List persons = entityManager.createQuery( @@ -2636,9 +2625,8 @@ public void test_hql_like_predicate_escape_example() { } @Test - public void test_hql_between_predicate_example_1() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_between_predicate_example_1(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-between-predicate-example[] List persons = entityManager.createQuery( "select p " + @@ -2656,9 +2644,8 @@ public void test_hql_between_predicate_example_1() { @RequiresDialect(H2Dialect.class) @RequiresDialect(PostgreSQLDialect.class) @RequiresDialect(MySQLDialect.class) - public void test_hql_between_predicate_example_2() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_between_predicate_example_2(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-between-predicate-example[] List persons = entityManager.createQuery( @@ -2673,9 +2660,8 @@ public void test_hql_between_predicate_example_2() { } @Test - public void test_hql_between_predicate_example_3() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_between_predicate_example_3(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-between-predicate-example[] List calls = entityManager.createQuery( @@ -2690,9 +2676,8 @@ public void test_hql_between_predicate_example_3() { } @Test - public void test_hql_between_predicate_example_4() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_between_predicate_example_4(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-between-predicate-example[] List persons = entityManager.createQuery( @@ -2707,9 +2692,8 @@ public void test_hql_between_predicate_example_4() { } @Test - public void test_hql_in_predicate_example_1() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_in_predicate_example_1(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-in-predicate-example[] List payments = entityManager.createQuery( "select p " + @@ -2723,9 +2707,8 @@ public void test_hql_in_predicate_example_1() { } @Test - public void test_hql_in_predicate_example_2() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_in_predicate_example_2(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-in-predicate-example[] List phones = entityManager.createQuery( @@ -2740,9 +2723,8 @@ public void test_hql_in_predicate_example_2() { } @Test - public void test_hql_in_predicate_example_3() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_in_predicate_example_3(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-in-predicate-example[] List phones = entityManager.createQuery( @@ -2758,9 +2740,8 @@ public void test_hql_in_predicate_example_3() { } @Test - public void test_hql_in_predicate_example_4() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_in_predicate_example_4(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-in-predicate-example[] List phones = entityManager.createQuery( @@ -2779,9 +2760,8 @@ public void test_hql_in_predicate_example_4() { } @Test - public void test_hql_in_predicate_example_5() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_in_predicate_example_5(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-in-predicate-example[] // Not JPQL compliant! @@ -2802,9 +2782,8 @@ public void test_hql_in_predicate_example_5() { @Test - public void test_hql_in_predicate_example_6() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_in_predicate_example_6(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-in-predicate-example[] // Not JPQL compliant! @@ -2823,9 +2802,8 @@ public void test_hql_in_predicate_example_6() { } @Test - public void test_hql_empty_collection_predicate_example_1() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_empty_collection_predicate_example_1(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-empty-collection-predicate-example[] List persons = entityManager.createQuery( "select p " + @@ -2839,9 +2817,8 @@ public void test_hql_empty_collection_predicate_example_1() { } @Test - public void test_hql_empty_collection_predicate_example_2() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_empty_collection_predicate_example_2(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-empty-collection-predicate-example[] List persons = entityManager.createQuery( @@ -2856,9 +2833,8 @@ public void test_hql_empty_collection_predicate_example_2() { } @Test - public void test_hql_member_of_collection_predicate_example_1() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_member_of_collection_predicate_example_1(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-member-of-collection-predicate-example[] List persons = entityManager.createQuery( "select p " + @@ -2872,9 +2848,8 @@ public void test_hql_member_of_collection_predicate_example_1() { } @Test - public void test_hql_member_of_collection_predicate_example_2() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_member_of_collection_predicate_example_2(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-member-of-collection-predicate-example[] List persons = entityManager.createQuery( @@ -2889,9 +2864,8 @@ public void test_hql_member_of_collection_predicate_example_2() { } @Test - public void test_hql_group_by_example_1() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_group_by_example_1(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-group-by-example[] Long totalDuration = entityManager.createQuery( "select sum(c.duration) " + @@ -2904,9 +2878,8 @@ public void test_hql_group_by_example_1() { } @Test - public void test_hql_group_by_example_2() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_group_by_example_2(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-group-by-example[] List personTotalCallDurations = entityManager.createQuery( @@ -2923,9 +2896,8 @@ public void test_hql_group_by_example_2() { } @Test - public void test_hql_group_by_example_3() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_group_by_example_3(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-group-by-example[] //It's even possible to group by entities! @@ -2943,9 +2915,8 @@ public void test_hql_group_by_example_3() { } @Test - public void test_hql_group_by_example_4() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_group_by_example_4(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { Call call11 = new Call(); call11.setDuration(10); @@ -2968,9 +2939,8 @@ public void test_hql_group_by_example_4() { } @Test - public void test_hql_group_by_having_example() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_group_by_having_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-group-by-having-example[] List personTotalCallDurations = entityManager.createQuery( @@ -2988,9 +2958,8 @@ public void test_hql_group_by_having_example() { } @Test - public void test_hql_order_by_example_1() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_order_by_example_1(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-order-by-example[] List persons = entityManager.createQuery( "select p " + @@ -3004,9 +2973,8 @@ public void test_hql_order_by_example_1() { } @Test - public void test_hql_order_by_example_2() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_order_by_example_2(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-order-by-example[] List personTotalCallDurations = entityManager.createQuery( @@ -3024,9 +2992,8 @@ public void test_hql_order_by_example_2() { } @Test - public void test_hql_limit_example() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_limit_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-limit-example[] List calls1 = entityManager.createQuery( "select c " + @@ -3051,9 +3018,8 @@ public void test_hql_limit_example() { } @Test - public void test_hql_bad_limit_example() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_bad_limit_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-bad-limit-example[] // don't do this! join fetch should not be used with limit List wrongCalls = entityManager.createQuery( @@ -3069,9 +3035,8 @@ public void test_hql_bad_limit_example() { } @Test - public void test_hql_bad_fetch_first_example() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_bad_fetch_first_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { List wrongCalls = entityManager.createQuery( "select p " + "from Phone p " + @@ -3084,9 +3049,8 @@ public void test_hql_bad_fetch_first_example() { } @Test - public void test_hql_read_only_entities_example() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_read_only_entities_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-read-only-entities-example[] List calls = entityManager.createQuery( "select c " + @@ -3104,9 +3068,8 @@ public void test_hql_read_only_entities_example() { } @Test - public void test_hql_read_only_entities_native_example() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_read_only_entities_native_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-read-only-entities-native-example[] List calls = entityManager.createQuery( "select c " + @@ -3123,9 +3086,8 @@ public void test_hql_read_only_entities_native_example() { } @Test - public void test_hql_derived_root_example() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_derived_root_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-derived-root-example[] List calls = entityManager.createQuery( "select d.owner, d.payed " + @@ -3142,9 +3104,8 @@ public void test_hql_derived_root_example() { } @Test - public void test_hql_cte_materialized_example() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void test_hql_cte_materialized_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-cte-materialized-example[] List calls = entityManager.createQuery( "with data as materialized(" + @@ -3163,9 +3124,9 @@ public void test_hql_cte_materialized_example() { } @Test - @RequiresDialectFeature( DialectChecks.SupportsRecursiveCtes.class ) - public void test_hql_cte_recursive_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsRecursiveCtes.class ) + public void test_hql_cte_recursive_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-cte-recursive-example[] List calls = entityManager.createQuery( "with paymentConnectedPersons as(" + @@ -3188,9 +3149,9 @@ public void test_hql_cte_recursive_example() { } @Test - @RequiresDialectFeature( DialectChecks.SupportsRecursiveCtes.class ) - public void test_hql_cte_recursive_search_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsRecursiveCtes.class ) + public void test_hql_cte_recursive_search_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-cte-recursive-search-example[] List calls = entityManager.createQuery( "with paymentConnectedPersons as(" + @@ -3213,9 +3174,9 @@ public void test_hql_cte_recursive_search_example() { } @Test - @RequiresDialectFeature( DialectChecks.SupportsRecursiveCtes.class ) - public void test_hql_cte_recursive_cycle_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsRecursiveCtes.class ) + public void test_hql_cte_recursive_cycle_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-cte-recursive-cycle-example[] List calls = entityManager.createQuery( "with paymentConnectedPersons as(" + @@ -3238,14 +3199,12 @@ public void test_hql_cte_recursive_cycle_example() { } @Test - @RequiresDialectFeature({ - DialectChecks.SupportsSubqueryInOnClause.class, - DialectChecks.SupportsOrderByInCorrelatedSubquery.class - }) - @SkipForDialect(dialectClass = OracleDialect.class, majorVersion = 11, reason = "The lateral emulation for Oracle 11 would be very complex because nested correlation is unsupported") - public void test_hql_derived_join_example() { - - doInJPA(this::entityManagerFactory, entityManager -> { + @RequiresDialectFeature( feature = DialectFeatureChecks.SupportsSubqueryInOnClause.class ) + @RequiresDialectFeature( feature = DialectFeatureChecks.SupportsOrderByInCorrelatedSubquery.class ) + @SkipForDialect(dialectClass = OracleDialect.class, majorVersion = 11, + reason = "The lateral emulation for Oracle 11 would be very complex because nested correlation is unsupported") + public void test_hql_derived_join_example(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-derived-join-example[] List calls1 = entityManager.createQuery( "from Phone p " + diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/IndicesTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/IndicesTest.java index 6651e076228c..4d4ed1c23df8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/IndicesTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/IndicesTest.java @@ -4,9 +4,6 @@ */ package org.hibernate.orm.test.hql; -import java.util.HashMap; -import java.util.List; -import java.util.Map; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; @@ -14,29 +11,32 @@ import jakarta.persistence.MapKeyJoinColumn; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; -import static org.hamcrest.core.Is.is; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import org.junit.Before; -import org.junit.Test; -import static org.junit.Assert.assertThat; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; /** * @author Burkhard Graves */ +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey(value = "HHH-14475") -public class IndicesTest extends BaseNonConfigCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] {Project.class, Role.class, Person.class}; - } - - @Before - public void setUp() { - doInHibernate( this::sessionFactory, session -> { +@DomainModel(annotatedClasses = {IndicesTest.Project.class, IndicesTest.Role.class, IndicesTest.Person.class}) +@SessionFactory +public class IndicesTest { + @BeforeEach + public void createTestData(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { Project project = new Project(1); Role role = new Role(1); @@ -46,19 +46,20 @@ public void setUp() { Person person = new Person(1, project, role); session.persist( person ); - }); + } ); } - @Test - public void testSelectIndices() { - doInHibernate( this::sessionFactory, session -> { - - List result = session.createQuery( - "select indices(p.roles) from Person p" - ).list(); + @AfterEach + public void dropTestData(SessionFactoryScope factoryScope) throws Exception { + factoryScope.dropData(); + } - assertThat( result.size(), is( 1 ) ); - }); + @Test + public void testSelectIndices(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + List result = session.createQuery("select indices(p.roles) from Person p" ).list(); + assertThat( result ).hasSize( 1 ); + } ); } @Entity(name = "Person") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/InferenceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/InferenceTest.java index b1f4fe782c13..7fa71f120437 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/InferenceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/InferenceTest.java @@ -4,79 +4,71 @@ */ package org.hibernate.orm.test.hql; -import java.util.List; - +import jakarta.persistence.Entity; +import jakarta.persistence.Id; import org.hibernate.dialect.CockroachDialect; import org.hibernate.query.criteria.HibernateCriteriaBuilder; import org.hibernate.query.criteria.JpaCriteriaQuery; import org.hibernate.query.criteria.JpaRoot; - -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.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.testing.orm.junit.SkipForDialect; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import jakarta.persistence.Column; -import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.Id; -import jakarta.persistence.TypedQuery; +import java.util.List; -import static org.hamcrest.CoreMatchers.hasItem; -import static org.hamcrest.CoreMatchers.is; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Beikov */ -public class InferenceTest extends BaseCoreFunctionalTestCase { - - private Person person; - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class - }; - } - - @Before - public void setUp() { - doInHibernate( this::sessionFactory, session -> { - person = new Person(); - person.setName( "Johannes" ); - person.setSurname( "Buehler" ); +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(annotatedClasses = InferenceTest.Person.class) +@SessionFactory +public class InferenceTest { + + @BeforeEach + public void createTestData(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( session -> { + var person = new Person( 1, "Johannes", "Buehler" ); session.persist( person ); } ); } - @After - public void cleanUp() { - doInHibernate( this::sessionFactory, session -> { - session.createMutationQuery( "delete from Person" ).executeUpdate(); - } ); + @AfterEach + public void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test - public void testBinaryArithmeticInference() { - doInHibernate( this::sessionFactory, session -> { - TypedQuery query = session.createQuery( "from Person p where p.id + 1 < :param", Person.class ); - query.setParameter("param", 10); - List resultList = query.getResultList(); - assertThat(resultList, hasItem(person)); + public void testBinaryArithmeticInference(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( session -> { + List resultList = session.createQuery( "from Person p where p.id + 1 < :param", Person.class ) + .setParameter("param", 10) + .getResultList(); + assertThat( resultList ).map( Person::getId ).contains( 1 ); } ); } @Test @JiraKey("HHH-17386") - public void testInferenceSourceResetForOnClause() { - doInHibernate( this::sessionFactory, session -> { - session.createQuery( "from Person p where p in (select p2 from Person p2 join Person p3 on exists (select 1 from Person p4))", Person.class ) - .getResultList(); + public void testInferenceSourceResetForOnClause(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( session -> { + var hql = """ + from Person p + where p in ( + select p2 + from Person p2 + join Person p3 + on exists (select 1 from Person p4) + ) + """; + session.createQuery( hql, Person.class ).getResultList(); } ); } @@ -84,30 +76,33 @@ public void testInferenceSourceResetForOnClause() { @Test @JiraKey("HHH-18046") @SkipForDialect( dialectClass = CockroachDialect.class, reason = "CockroachDB doesn't support multiplication between int and float columns" ) - public void testBinaryArithmeticParameterInference() { - doInHibernate( this::sessionFactory, session -> { + public void testBinaryArithmeticParameterInference(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( session -> { HibernateCriteriaBuilder cb = session.getCriteriaBuilder(); JpaCriteriaQuery cq = cb.createQuery( Double.class ); JpaRoot root = cq.from( Person.class ); cq.select( cb.toDouble( cb.prod( root.get( "id" ), 0.5f ) ) ); Double result = session.createQuery( cq ).getSingleResult(); - assertThat( result, is( person.getId() * 0.5d ) ); + assertThat( result ).isEqualTo( 0.5d ); } ); } @Entity(name = "Person") public static class Person { - @Id - @GeneratedValue private Integer id; - - @Column private String name; - - @Column private String surname; + public Person() { + } + + public Person(Integer id, String name, String surname) { + this.id = id; + this.name = name; + this.surname = surname; + } + public String getName() { return name; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/JoinOnClauseTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/JoinOnClauseTest.java index 7c51702c0472..501648c1b54c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/JoinOnClauseTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/JoinOnClauseTest.java @@ -4,12 +4,6 @@ */ package org.hibernate.orm.test.hql; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Before; -import org.junit.Test; - import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; @@ -20,9 +14,16 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeEach; + import java.util.List; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -30,40 +31,51 @@ /** * @author Christian Beikov */ -public class JoinOnClauseTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] {Item.class, Price.class, Book.class, Bid.class, Author.class, Car.class, Person.class}; - } - - @Before - public void setUp(){ - doInJPA( this::entityManagerFactory, entityManager -> { +@SuppressWarnings({"JUnitMalformedDeclaration", "JUnitMixedFramework"}) +@DomainModel(annotatedClasses = { + JoinOnClauseTest.Item.class, + JoinOnClauseTest.Price.class, + JoinOnClauseTest.Book.class, + JoinOnClauseTest.Bid.class, + JoinOnClauseTest.Author.class, + JoinOnClauseTest.Car.class, + JoinOnClauseTest.Person.class +}) +@SessionFactory +public class JoinOnClauseTest { + + @BeforeEach + public void createTestData(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( session -> { Price price = new Price( 10, "EUR" ); Author author = new Author( "Author 1" ); Book book = new Book( author, "Book 1", price ); - entityManager.persist( book ); + session.persist( book ); book = new Book( author, "Book 2", price ); - entityManager.persist( book ); + session.persist( book ); } ); } + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); + } + @Test @JiraKey(value = "HHH-11437") - public void testOnClauseUsesSuperclassAttribute() { - doInJPA( this::entityManagerFactory, entityManager -> { - List result = entityManager.createQuery( "SELECT DISTINCT b1 FROM Book b1 JOIN Book b2 ON b1.price = b2.price", Book.class ) - .getResultList(); + public void testOnClauseUsesSuperclassAttribute(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( session -> { + List result = session.createQuery( "SELECT DISTINCT b1 FROM Book b1 JOIN Book b2 ON b1.price = b2.price", Book.class ) + .getResultList(); assertEquals(2, result.size()); } ); } @Test @JiraKey(value = "HHH-11435") - public void testOnClauseUsesNonDrivingTableAlias() { - doInJPA( this::entityManagerFactory, entityManager -> { + public void testOnClauseUsesNonDrivingTableAlias(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { try { entityManager.createQuery( "SELECT b1 FROM Book b1 JOIN Book b2 ON b1.author = author2 LEFT JOIN b2.author author2" ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/MapFunctionExpressionsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/MapFunctionExpressionsTest.java index 4618e188ec52..e3f5056e7291 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/MapFunctionExpressionsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/MapFunctionExpressionsTest.java @@ -4,147 +4,121 @@ */ package org.hibernate.orm.test.hql; -import java.util.HashMap; -import java.util.List; -import java.util.Map; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.JoinTable; import jakarta.persistence.MapKeyJoinColumn; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.hibernate.Session; - -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import java.util.HashMap; +import java.util.Map; -import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test originally written to help verify/diagnose HHH-10125 * * @author Steve Ebersole */ -public class MapFunctionExpressionsTest extends BaseNonConfigCoreFunctionalTestCase { - - @Before - public void prepareTestData() { - Session s = openSession(); - s.getTransaction().begin(); - - AddressType homeType = new AddressType( 1, "home" ); - s.persist( homeType ); - - Address address = new Address( 1, "Main St.", "Somewhere, USA" ); - s.persist( address ); - - Contact contact = new Contact( 1, "John" ); - contact.addresses.put( homeType, address ); - s.persist( contact ); - - s.getTransaction().commit(); - s.close(); +@SuppressWarnings({"JUnitMalformedDeclaration", "deprecation"}) +@JiraKey("HHH-10125") +@DomainModel(annotatedClasses = { + MapFunctionExpressionsTest.Address.class, + MapFunctionExpressionsTest.AddressType.class, + MapFunctionExpressionsTest.Contact.class +}) +@SessionFactory +public class MapFunctionExpressionsTest { + + @BeforeEach + public void prepareTestData(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( s -> { + AddressType homeType = new AddressType( 1, "home" ); + s.persist( homeType ); + + Address address = new Address( 1, "Main St.", "Somewhere, USA" ); + s.persist( address ); + + Contact contact = new Contact( 1, "John" ); + contact.addresses.put( homeType, address ); + s.persist( contact ); + } ); } - @After - public void cleanUpTestData() { - Session s = openSession(); - s.getTransaction().begin(); - - s.remove( s.get( Contact.class, 1 ) ); - - s.remove( s.get( Address.class, 1 ) ); - s.remove( s.get( AddressType.class, 1 ) ); - - s.getTransaction().commit(); - s.close(); + @AfterEach + public void cleanUpTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test - public void testMapKeyExpressionInWhere() { - // NOTE : JPA requires that an alias be used in the key() expression. Hibernate allows - // path or alias. - - Session s = openSession(); - s.getTransaction().begin(); - - // JPA form - List contacts = s.createQuery( "select c from Contact c join c.addresses a where key(a) is not null" ).list(); - assertEquals( 1, contacts.size() ); - Contact contact = assertTyping( Contact.class, contacts.get( 0 ) ); - - // Hibernate additional form - contacts = s.createQuery( "select c from Contact c where key(c.addresses) is not null" ).list(); - assertEquals( 1, contacts.size() ); - contact = assertTyping( Contact.class, contacts.get( 0 ) ); - - s.getTransaction().commit(); - s.close(); + public void testMapKeyExpressionInWhere(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (s) -> { + // NOTE : JPA requires that an alias be used in the key() expression. + // Hibernate allows path or alias. + + // JPA form + var results = s.createQuery( "select c from Contact c join c.addresses a where key(a) is not null" ).list(); + assertEquals( 1, results.size() ); + assertThat( results.get(0) ).isInstanceOf( Contact.class ); + + // Hibernate additional form + results = s.createQuery( "select c from Contact c where key(c.addresses) is not null" ).list(); + assertEquals( 1, results.size() ); + assertThat( results.get(0) ).isInstanceOf( Contact.class ); + } ); } @Test - public void testMapKeyExpressionInSelect() { - // NOTE : JPA requires that an alias be used in the key() expression. Hibernate allows - // path or alias. - - Session s = openSession(); - s.getTransaction().begin(); - - // JPA form - List types = s.createQuery( "select key(a) from Contact c join c.addresses a" ).list(); - assertEquals( 1, types.size() ); - assertTyping( AddressType.class, types.get( 0 ) ); - - // Hibernate additional form - types = s.createQuery( "select key(c.addresses) from Contact c" ).list(); - assertEquals( 1, types.size() ); - assertTyping( AddressType.class, types.get( 0 ) ); - - s.getTransaction().commit(); - s.close(); + public void testMapKeyExpressionInSelect(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (s) -> { + // NOTE : JPA requires that an alias be used in the key() expression. + // Hibernate allows path or alias. + + // JPA form + var results = s.createQuery( "select key(a) from Contact c join c.addresses a" ).list(); + assertEquals( 1, results.size() ); + assertThat( results.get(0) ).isInstanceOf( AddressType.class ); + + // Hibernate additional form + results = s.createQuery( "select key(c.addresses) from Contact c" ).list(); + assertEquals( 1, results.size() ); + assertThat( results.get(0) ).isInstanceOf( AddressType.class ); + } ); } @Test - public void testMapValueExpressionInSelect() { - Session s = openSession(); - s.getTransaction().begin(); - - List addresses = s.createQuery( "select value(a) from Contact c join c.addresses a" ).list(); - assertEquals( 1, addresses.size() ); - assertTyping( Address.class, addresses.get( 0 ) ); - - addresses = s.createQuery( "select value(c.addresses) from Contact c" ).list(); - assertEquals( 1, addresses.size() ); - assertTyping( Address.class, addresses.get( 0 ) ); - - s.getTransaction().commit(); - s.close(); + public void testMapValueExpressionInSelect(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (s) -> { + var results = s.createQuery( "select value(a) from Contact c join c.addresses a" ).list(); + assertEquals( 1, results.size() ); + assertThat( results.get(0) ).isInstanceOf( Address.class ); + + results = s.createQuery( "select value(c.addresses) from Contact c" ).list(); + assertEquals( 1, results.size() ); + assertThat( results.get(0) ).isInstanceOf( Address.class ); + } ); } @Test - public void testMapEntryExpressionInSelect() { - Session s = openSession(); - s.getTransaction().begin(); - - List addresses = s.createQuery( "select entry(a) from Contact c join c.addresses a" ).list(); - assertEquals( 1, addresses.size() ); - assertTyping( Map.Entry.class, addresses.get( 0 ) ); - - addresses = s.createQuery( "select entry(c.addresses) from Contact c" ).list(); - assertEquals( 1, addresses.size() ); - assertTyping( Map.Entry.class, addresses.get( 0 ) ); - - s.getTransaction().commit(); - s.close(); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Address.class, AddressType.class, Contact.class }; + public void testMapEntryExpressionInSelect(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (s) -> { + var results = s.createQuery( "select entry(a) from Contact c join c.addresses a" ).list(); + assertEquals( 1, results.size() ); + assertThat( results.get(0) ).isInstanceOf( Map.Entry.class ); + + results = s.createQuery( "select entry(c.addresses) from Contact c" ).list(); + assertEquals( 1, results.size() ); + assertThat( results.get(0) ).isInstanceOf( Map.Entry.class ); + } ); } @Entity(name = "AddressType") @@ -165,7 +139,6 @@ public AddressType(Integer id, String name) { @Entity(name = "Address") @Table(name = "address") -// @Embeddable public static class Address { @Id public Integer id; @@ -191,11 +164,7 @@ public static class Contact { @OneToMany @JoinTable(name = "contact_address") @MapKeyJoinColumn(name="address_type_id", referencedColumnName="id") -// @JoinColumn -// @ElementCollection -// @MapKeyEnumerated(EnumType.STRING) -// @MapKeyColumn(name = "addr_type") - Map addresses = new HashMap(); + Map addresses = new HashMap<>(); public Contact() { } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/MetamodelBoundedCacheTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/MetamodelBoundedCacheTest.java index abd78074ca27..61edaf87b401 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/MetamodelBoundedCacheTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/MetamodelBoundedCacheTest.java @@ -4,46 +4,43 @@ */ package org.hibernate.orm.test.hql; -import java.lang.reflect.Field; -import java.util.Map; - -import org.hibernate.metamodel.MappingMetamodel; -import org.hibernate.metamodel.model.domain.JpaMetamodel; -import org.hibernate.metamodel.model.domain.internal.JpaMetamodelImpl; -import org.hibernate.metamodel.model.domain.internal.MappingMetamodelImpl; - -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; - import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; +import org.hibernate.metamodel.model.domain.JpaMetamodel; +import org.hibernate.metamodel.model.domain.internal.JpaMetamodelImpl; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import java.lang.reflect.Field; +import java.util.Map; -public class MetamodelBoundedCacheTest extends BaseNonConfigCoreFunctionalTestCase { +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(annotatedClasses = MetamodelBoundedCacheTest.Employee.class) +@SessionFactory +public class MetamodelBoundedCacheTest { @Test @JiraKey(value = "HHH-14948") - public void testMemoryConsumptionOfFailedImportsCache() throws NoSuchFieldException, IllegalAccessException { - MappingMetamodel mappingMetamodel = sessionFactory().getMappingMetamodel(); - - MappingMetamodelImpl mImpl = (MappingMetamodelImpl) mappingMetamodel; - final JpaMetamodel jpaMetamodel = mImpl.getJpaMetamodel(); + public void testMemoryConsumptionOfFailedImportsCache(SessionFactoryScope factoryScope) throws NoSuchFieldException, IllegalAccessException { + var jpaModel = factoryScope.getSessionFactory().getJpaMetamodel(); for ( int i = 0; i < 1001; i++ ) { - jpaMetamodel.qualifyImportableName( "nonexistend" + i ); + jpaModel.qualifyImportableName( "nonexistend" + i ); } - Map validImports = extractMapFromMetamodel( jpaMetamodel, "nameToImportMap" ); - Map invalidImports = extractMapFromMetamodel( jpaMetamodel, "knownInvalidnameToImportMap" ); + Map validImports = extractMapFromMetamodel( jpaModel, "nameToImportMap" ); + Map invalidImports = extractMapFromMetamodel( jpaModel, "knownInvalidnameToImportMap" ); - assertEquals( 2, validImports.size() ); + Assertions.assertEquals( 2, validImports.size() ); // VERY hard-coded, but considering the possibility of a regression of a memory-related issue, // it should be worth it - assertEquals( 1000, invalidImports.size() ); + Assertions.assertEquals( 1000, invalidImports.size() ); } @@ -54,11 +51,6 @@ public void testMemoryConsumptionOfFailedImportsCache() throws NoSuchFieldExcept return (Map) field.get( jpaMetamodel ); } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Employee.class }; - } - @Entity( name = "Employee" ) @Table( name= "tabEmployees" ) public class Employee { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/ParameterCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/ParameterCollectionTest.java index 6f4f1b8570af..e327f80c3fba 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/ParameterCollectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/ParameterCollectionTest.java @@ -7,55 +7,47 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; +import org.hibernate.query.Query; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import java.util.ArrayList; import java.util.Collection; import java.util.List; -import org.hibernate.Session; -import org.hibernate.query.Query; - -import org.junit.Test; - -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Andrea Boriero */ +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey(value = "HHH-10893") -public class ParameterCollectionTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] {Person.class}; +@DomainModel(annotatedClasses = ParameterCollectionTest.Person.class) +@SessionFactory +public class ParameterCollectionTest { + @BeforeEach + public void createTestData(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + for ( int i = 0; i < 20; i++ ) { + Person p1 = new Person( i, "p" + i ); + session.persist( p1 ); + } + } ); } - @Override - protected void prepareTest() throws Exception { - try (Session session = openSession()) { - session.beginTransaction(); - try { - for ( int i = 0; i < 20; i++ ) { - Person p1 = new Person( i, "p" + i ); - session.persist( p1 ); - } - session.getTransaction().commit(); - } - catch (Exception e) { - if ( session.getTransaction().isActive() ) { - session.getTransaction().rollback(); - } - throw e; - } - } + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test - public void testReusingQueryWithNewParameterValues() throws Exception { - try (Session session = openSession()) { + public void testReusingQueryWithNewParameterValues(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { Collection ids = new ArrayList<>(); Query q = session.createQuery( "select id from Person where id in (:ids) order by id" ); for ( int i = 0; i < 10; i++ ) { @@ -72,9 +64,11 @@ public void testReusingQueryWithNewParameterValues() throws Exception { q.setParameterList( "ids", ids ); List foundIds = q.list(); - assertThat( "Wrong number of results", foundIds.size(), is( ids.size() ) ); - assertThat( foundIds, is( ids ) ); - } + assertThat( foundIds ) + .withFailMessage( "Wrong number of results" ) + .hasSize( ids.size() ); + assertThat( foundIds ).containsAll( ids ); + } ); } @Entity(name = "Person") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/QuotedIdentifierTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/QuotedIdentifierTest.java index 3290de05530d..626ee9ca2e94 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/QuotedIdentifierTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/QuotedIdentifierTest.java @@ -7,59 +7,49 @@ import java.util.List; import org.hibernate.annotations.processing.Exclude; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; import jakarta.persistence.Column; import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.Tuple; import jakarta.persistence.TypedQuery; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Christian Beikov */ +@SuppressWarnings("JUnitMalformedDeclaration") @Exclude -public class QuotedIdentifierTest extends BaseCoreFunctionalTestCase { - - private Person person; - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class - }; - } - - @Before - public void setUp() { - doInHibernate( this::sessionFactory, session -> { - person = new Person(); - person.setName( "Chuck" ); - person.setSurname( "Norris" ); +@DomainModel(annotatedClasses = QuotedIdentifierTest.Person.class) +@SessionFactory +public class QuotedIdentifierTest { + + @BeforeEach + public void createTestData(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + var person = new Person( 1, "Chuck", "Norris" ); session.persist( person ); } ); } - @After - public void tearDown() { - doInHibernate( this::sessionFactory, session -> { - session.createQuery("delete `The Person`").executeUpdate(); - } ); + @AfterEach + public void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test - public void testQuotedIdentifier() { - doInHibernate( this::sessionFactory, session -> { + public void testQuotedIdentifier(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { TypedQuery query = session.createQuery( "select `the person`.`name` as `The person name` " + - "from `The Person` `the person`", + "from `The Person` `the person`", Tuple.class ); List resultList = query.getResultList(); @@ -69,8 +59,8 @@ public void testQuotedIdentifier() { } @Test - public void testQuotedFunctionName() { - doInHibernate( this::sessionFactory, session -> { + public void testQuotedFunctionName(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( session -> { TypedQuery query = session.createQuery( "select `upper`(`the person`.`name`) as `The person name` " + "from `The Person` `the person`", @@ -84,17 +74,21 @@ public void testQuotedFunctionName() { @Entity(name = "The Person") public static class Person { - @Id - @GeneratedValue private Integer id; - @Column(name = "the name") private String name; - - @Column private String surname; + public Person() { + } + + public Person(Integer id, String name, String surname) { + this.id = id; + this.name = name; + this.surname = surname; + } + public String getName() { return name; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/SelectDistinctTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/SelectDistinctTest.java index 435f6071c044..9764dc7295e1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/SelectDistinctTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/SelectDistinctTest.java @@ -4,14 +4,6 @@ */ package org.hibernate.orm.test.hql; -import java.util.ArrayList; -import java.util.List; - -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Before; -import org.junit.Test; - import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -20,26 +12,32 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertTrue; +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; /** * @author Vlad Mihalcea */ -public class SelectDistinctTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Book.class - }; - } - - @Before - public void init() { - doInJPA(this::entityManagerFactory, entityManager -> { +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(annotatedClasses = { + SelectDistinctTest.Person.class, + SelectDistinctTest.Book.class +}) +@SessionFactory +public class SelectDistinctTest { + + @BeforeEach + public void createTestData(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { Person gavinKing = new Person("Gavin", "King"); Person stephenKing = new Person("Stephen", "King"); Person vladMihalcea = new Person("Vlad", "Mihalcea"); @@ -57,10 +55,14 @@ public void init() { }); } - @Test - public void testDistinctProjection() { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); + } - doInJPA(this::entityManagerFactory, entityManager -> { + @Test + public void testDistinctProjection(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { //tag::hql-distinct-projection-query-example[] List lastNames = entityManager.createQuery( "select distinct p.lastName " + @@ -68,11 +70,8 @@ public void testDistinctProjection() { .getResultList(); //end::hql-distinct-projection-query-example[] - assertTrue( - lastNames.size() == 2 && - lastNames.contains("King") && - lastNames.contains("Mihalcea") - ); + assertThat( lastNames ).hasSize( 2 ); + assertThat( lastNames ).contains( "King", "Mihalcea" ); }); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/SelectNewEmbeddedIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/SelectNewEmbeddedIdTest.java index df36b46d7029..089ef83d3e63 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/SelectNewEmbeddedIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/SelectNewEmbeddedIdTest.java @@ -4,19 +4,20 @@ */ package org.hibernate.orm.test.hql; -import java.io.Serializable; - import jakarta.persistence.Embeddable; import jakarta.persistence.EmbeddedId; import jakarta.persistence.Entity; -import jakarta.persistence.EntityManager; import jakarta.persistence.Query; - -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import java.io.Serializable; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test entities with a non-identifier property named 'id' with an EmbeddedId using @@ -24,69 +25,63 @@ * * @author Chris Cranford */ -public class SelectNewEmbeddedIdTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Simple.class }; +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(annotatedClasses = SelectNewEmbeddedIdTest.Simple.class) +@SessionFactory +public class SelectNewEmbeddedIdTest { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } - private void assertQueryRowCount(String queryString, int rowCount) { - EntityManager entityManager = getOrCreateEntityManager(); - try { - // persist the data - entityManager.getTransaction().begin(); - entityManager.persist( new Simple( new SimpleId( 1, 1 ), 1 ) ); - entityManager.getTransaction().commit(); + private void assertQueryRowCount( + String queryString, + @SuppressWarnings("SameParameterValue") int rowCount, + SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + session.persist( new Simple( new SimpleId( 1, 1 ), 1 ) ); + session.flush(); - Query query = entityManager.createQuery( queryString ); + //noinspection deprecation + Query query = session.createQuery( queryString ); assertEquals( rowCount, query.getResultList().size() ); - } - catch ( Exception e ) { - if ( entityManager.getTransaction().isActive() ) { - entityManager.getTransaction().rollback(); - } - throw e; - } - finally { - entityManager.close(); - } + } ); } @Test @JiraKey(value = "HHH-4712") - public void testSelectNewListEntity() { - assertQueryRowCount( "select new list(e) FROM Simple e", 1 ); + public void testSelectNewListEntity(SessionFactoryScope factoryScope) { + assertQueryRowCount( "select new list(e) FROM Simple e", 1, factoryScope ); } @Test @JiraKey(value = "HHH-4712") - public void testSelectNewListEmbeddedIdValue() { - assertQueryRowCount( "select new list(e.simpleId) FROM Simple e", 1 ); + public void testSelectNewListEmbeddedIdValue(SessionFactoryScope factoryScope) { + assertQueryRowCount( "select new list(e.simpleId) FROM Simple e", 1, factoryScope ); } @Test @JiraKey(value = "HHH-4712") - public void testSelectNewMapEntity() { - assertQueryRowCount( "select new map(e.id, e) FROM Simple e", 1 ); + public void testSelectNewMapEntity(SessionFactoryScope factoryScope) { + assertQueryRowCount( "select new map(e.id, e) FROM Simple e", 1, factoryScope ); } @Test @JiraKey(value = "HHH-4712") - public void testSelectNewMapEmbeddedIdValue() { - assertQueryRowCount( "select new map(e.simpleId, e.simpleId) FROM Simple e", 1 ); + public void testSelectNewMapEmbeddedIdValue(SessionFactoryScope factoryScope) { + assertQueryRowCount( "select new map(e.simpleId, e.simpleId) FROM Simple e", 1, factoryScope ); } @Test @JiraKey(value = "HHH-4712") - public void testSelectNewObjectEntity() { - assertQueryRowCount( "select new " + Wrapper.class.getName() + "(e) FROM Simple e", 1 ); + public void testSelectNewObjectEntity(SessionFactoryScope factoryScope) { + assertQueryRowCount( "select new " + Wrapper.class.getName() + "(e) FROM Simple e", 1, factoryScope ); } @Test @JiraKey(value = "HHH-4712") - public void testSelectNewObjectEmbeddedIdValue() { - assertQueryRowCount( "select new " + Wrapper.class.getName() + "(e.simpleId) FROM Simple e", 1 ); + public void testSelectNewObjectEmbeddedIdValue(SessionFactoryScope factoryScope) { + assertQueryRowCount( "select new " + Wrapper.class.getName() + "(e.simpleId) FROM Simple e", 1, factoryScope ); } @Entity(name = "Simple") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/SubQueryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/SubQueryTest.java index 1ef7f4a4a42d..0eef5c88b5b7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/SubQueryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/SubQueryTest.java @@ -4,32 +4,207 @@ */ package org.hibernate.orm.test.hql; -import java.util.ArrayList; -import java.util.List; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.OneToMany; import jakarta.persistence.OneToOne; import jakarta.persistence.Table; - -import org.hibernate.Session; - +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -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.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import java.util.ArrayList; +import java.util.List; /** - * NOTE : some subquery related tests still exist in other test classes in the suite. This is a later - * attempt to create a more targeted set of subquery related tests. + * NOTE : some subquery related tests still exist in other test classes in the suite. + * This is a later attempt to create a more targeted set of subquery related tests. * * @author Steve Ebersole */ -public class SubQueryTest extends BaseCoreFunctionalTestCase { +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(annotatedClasses = { SubQueryTest.Root.class, SubQueryTest.Branch.class, SubQueryTest.Leaf.class }) +@SessionFactory +public class SubQueryTest { + @AfterEach + void dropTestData(SessionFactoryScope sessions) { + sessions.dropData(); + } + + @Test + @JiraKey( value = "HHH-9090" ) + public void testCorrelatedJoin(SessionFactoryScope sessions) { + sessions.inTransaction( (session) -> { + Root root = new Root(); + root.rootName = "root name"; + root.branch = new Branch(); + root.branch.branchName = "branch"; + root.branch.leaves = new ArrayList(); + Leaf leaf1 = new Leaf(); + leaf1.leafName = "leaf1"; + Leaf leaf2 = new Leaf(); + leaf2.leafName = "leaf2"; + root.branch.leaves.add( leaf1 ); + root.branch.leaves.add( leaf2 ); + session.persist( leaf1 ); + session.persist( leaf2 ); + session.persist( root.branch ); + session.persist( root ); + Root otherRoot = new Root(); + otherRoot.rootName = "other root name"; + otherRoot.branch = new Branch(); + otherRoot.branch.branchName = "other branch"; + otherRoot.branch.leaves = new ArrayList(); + Leaf otherLeaf1 = new Leaf(); + otherLeaf1.leafName = "leaf1"; + Leaf otherLeaf3 = new Leaf(); + otherLeaf3.leafName = "leaf3"; + otherRoot.branch.leaves.add( otherLeaf1 ); + otherRoot.branch.leaves.add( otherLeaf3 ); + session.persist( otherLeaf1 ); + session.persist( otherLeaf3 ); + session.persist( otherRoot.branch ); + session.persist( otherRoot ); + } ); + + sessions.inTransaction( (session) -> { + var qry = """ + from Root as r + where r.branch.branchName = 'branch' + and exists( from r.branch.leaves as s where s.leafName = 'leaf1') + """; + Root rootQueried = session.createQuery( qry, Root.class ).uniqueResult(); + Assertions.assertEquals( "root name", rootQueried.rootName ); + Assertions.assertEquals( "branch", rootQueried.branch.branchName ); + Assertions.assertEquals( "leaf1", rootQueried.branch.leaves.get( 0 ).leafName ); + Assertions.assertEquals( "leaf2", rootQueried.branch.leaves.get( 1 ).leafName ); + } ); + + sessions.inTransaction( (session) -> { + var qry = """ + from Root as r + where r.branch.branchName = 'branch' + and exists( from r.branch.leaves as s where s.leafName = 'leaf3') + """; + Assertions.assertNull( session.createQuery( qry ).uniqueResult() ); + } ); + + sessions.inTransaction( (session) -> { + var qry = """ + from Root as r + where exists( from r.branch.leaves as s where r.branch.branchName = 'branch' + and s.leafName = 'leaf1') + """; + var rootQueried = session.createQuery( qry, Root.class ).uniqueResult(); + Assertions.assertEquals( "root name", rootQueried.rootName ); + Assertions.assertEquals( "branch", rootQueried.branch.branchName ); + Assertions.assertEquals( "leaf1", rootQueried.branch.leaves.get( 0 ).leafName ); + Assertions.assertEquals( "leaf2", rootQueried.branch.leaves.get( 1 ).leafName ); + } ); + + sessions.inTransaction( (session) -> { + var qry = """ + from Root as r + where exists( from Root r1 where r1.branch.branchName = r.branch.branchName and r1.branch.branchName != 'other branch') + """; + var rootQueried = session.createQuery( qry, Root.class ).uniqueResult(); + Assertions.assertEquals( "root name", rootQueried.rootName ); + Assertions.assertEquals( "branch", rootQueried.branch.branchName ); + Assertions.assertEquals( "leaf1", rootQueried.branch.leaves.get( 0 ).leafName ); + Assertions.assertEquals( "leaf2", rootQueried.branch.leaves.get( 1 ).leafName ); + } ); + + } + + @Test + @JiraKey( value = "HHH-1689" ) + @JiraKey( value = "SQM-30" ) + public void testSubQueryAsSearchedCaseResultExpression(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + final String query = """ + SELECT CASE + WHEN l.id IS NOT NULL + THEN (SELECT COUNT(r.id) FROM Root r) + ELSE 0 + END + FROM Leaf l + """; + // simple syntax check + session.createQuery( query ).list(); + } ); + } + + @Test + @JiraKey( value = "HHH-1689" ) + @JiraKey( value = "SQM-30" ) + public void testSubQueryAsSearchedCaseExpression(SessionFactoryScope sessions) { + sessions.inTransaction( (session) -> { + final String query = """ + SELECT CASE + WHEN (SELECT COUNT(r.id) FROM Root r) > 1 THEN 1 + ELSE 0 + END + FROM Leaf l + """; + // simple syntax check + session.createQuery( query ).list(); + } ); + } + + @Test + @JiraKey( value = "HHH-1689" ) + @JiraKey( value = "SQM-30" ) + public void testSubQueryAsCaseElseResultExpression(SessionFactoryScope sessions) { + sessions.inTransaction( (session) -> { + final String query = """ + SELECT CASE WHEN l.id > 1 THEN 1 + ELSE (SELECT COUNT(r.id) FROM Root r) + END FROM Leaf l + """; + // simple syntax check + session.createQuery( query ).list(); + } ); + } + + @Test + @JiraKey( value = "HHH-1689" ) + @JiraKey( value = "SQM-30" ) + public void testSubQueryAsSimpleCaseTestExpression(SessionFactoryScope sessions) { + sessions.inTransaction( (session) -> { + final String query = """ + SELECT CASE (SELECT COUNT(r.id) FROM Root r) + WHEN 1 THEN 1 + ELSE 0 + END + FROM Leaf l + """; + // simple syntax check + session.createQuery( query ).list(); + } ); + } + + @Test + @JiraKey( value = "HHH-1689" ) + @JiraKey( value = "SQM-30" ) + public void testSubQueryAsSimpleCaseWhenExpression(SessionFactoryScope sessions) { + sessions.inTransaction( (session) -> { + final String query = """ + SELECT CASE l.id + WHEN (SELECT COUNT(r.id) FROM Root r) THEN 1 + ELSE 0 + END + FROM Leaf l + """; + // simple syntax check + session.createQuery( query ).list(); + } ); + } + @Entity( name = "Root" ) @Table( name = "ROOT" ) @@ -64,169 +239,4 @@ public static class Leaf { public String leafName; } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Root.class, Branch.class, Leaf.class }; - } - - @Test - @JiraKey( value = "HHH-9090" ) - public void testCorrelatedJoin() { - Session s = openSession(); - s.beginTransaction(); - Root root = new Root(); - root.rootName = "root name"; - root.branch = new Branch(); - root.branch.branchName = "branch"; - root.branch.leaves = new ArrayList(); - Leaf leaf1 = new Leaf(); - leaf1.leafName = "leaf1"; - Leaf leaf2 = new Leaf(); - leaf2.leafName = "leaf2"; - root.branch.leaves.add( leaf1 ); - root.branch.leaves.add( leaf2 ); - s.persist( leaf1 ); - s.persist( leaf2 ); - s.persist( root.branch ); - s.persist( root ); - Root otherRoot = new Root(); - otherRoot.rootName = "other root name"; - otherRoot.branch = new Branch(); - otherRoot.branch.branchName = "other branch"; - otherRoot.branch.leaves = new ArrayList(); - Leaf otherLeaf1 = new Leaf(); - otherLeaf1.leafName = "leaf1"; - Leaf otherLeaf3 = new Leaf(); - otherLeaf3.leafName = "leaf3"; - otherRoot.branch.leaves.add( otherLeaf1 ); - otherRoot.branch.leaves.add( otherLeaf3 ); - s.persist( otherLeaf1 ); - s.persist( otherLeaf3 ); - s.persist( otherRoot.branch ); - s.persist( otherRoot ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - String qry = "from Root as r " + - "where r.branch.branchName = 'branch' " + - " and exists( from r.branch.leaves as s where s.leafName = 'leaf1')"; - Root rootQueried = s.createQuery( qry, Root.class ).uniqueResult(); - assertEquals( root.rootName, rootQueried.rootName ); - assertEquals( root.branch.branchName, rootQueried.branch.branchName ); - assertEquals( leaf1.leafName, rootQueried.branch.leaves.get( 0 ).leafName ); - assertEquals( leaf2.leafName, rootQueried.branch.leaves.get( 1 ).leafName ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - qry = "from Root as r " + - "where r.branch.branchName = 'branch' " + - " and exists( from r.branch.leaves as s where s.leafName = 'leaf3')"; - assertNull( s.createQuery( qry ).uniqueResult() ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - qry = "from Root as r " + - "where exists( from r.branch.leaves as s where r.branch.branchName = 'branch' and s.leafName = 'leaf1')"; - rootQueried = (Root) s.createQuery( qry ).uniqueResult(); - assertEquals( root.rootName, rootQueried.rootName ); - assertEquals( root.branch.branchName, rootQueried.branch.branchName ); - assertEquals( leaf1.leafName, rootQueried.branch.leaves.get( 0 ).leafName ); - assertEquals( leaf2.leafName, rootQueried.branch.leaves.get( 1 ).leafName ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - qry = "from Root as r" + - " where exists( from Root r1 where r1.branch.branchName = r.branch.branchName and r1.branch.branchName != 'other branch')"; - rootQueried = (Root) s.createQuery( qry ).uniqueResult(); - assertEquals( root.rootName, rootQueried.rootName ); - assertEquals( root.branch.branchName, rootQueried.branch.branchName ); - assertEquals( leaf1.leafName, rootQueried.branch.leaves.get( 0 ).leafName ); - assertEquals( leaf2.leafName, rootQueried.branch.leaves.get( 1 ).leafName ); - s.getTransaction().commit(); - s.close(); - - } - - @Test - @JiraKeyGroup( value = { - @JiraKey( value = "HHH-1689" ), - @JiraKey( value = "SQM-30" ) - } ) - public void testSubQueryAsSearchedCaseResultExpression() { - final String query = "SELECT CASE WHEN l.id IS NOT NULL THEN (SELECT COUNT(r.id) FROM Root r) ELSE 0 END FROM Leaf l"; - // simple syntax check - Session s = openSession(); - s.beginTransaction(); - s.createQuery( query ).list(); - s.getTransaction().commit(); - s.close(); - } - - @Test - @JiraKeyGroup( value = { - @JiraKey( value = "HHH-1689" ), - @JiraKey( value = "SQM-30" ) - } ) - public void testSubQueryAsSearchedCaseExpression() { - final String query = "SELECT CASE WHEN (SELECT COUNT(r.id) FROM Root r) > 1 THEN 1 ELSE 0 END FROM Leaf l"; - // simple syntax check - Session s = openSession(); - s.beginTransaction(); - s.createQuery( query ).list(); - s.getTransaction().commit(); - s.close(); - } - - @Test - @JiraKeyGroup( value = { - @JiraKey( value = "HHH-1689" ), - @JiraKey( value = "SQM-30" ) - } ) - public void testSubQueryAsCaseElseResultExpression() { - final String query = "SELECT CASE WHEN l.id > 1 THEN 1 ELSE (SELECT COUNT(r.id) FROM Root r) END FROM Leaf l"; - // simple syntax check - Session s = openSession(); - s.beginTransaction(); - s.createQuery( query ).list(); - s.getTransaction().commit(); - s.close(); - } - - @Test - @JiraKeyGroup( value = { - @JiraKey( value = "HHH-1689" ), - @JiraKey( value = "SQM-30" ) - } ) - public void testSubQueryAsSimpleCaseTestExpression() { - final String query = "SELECT CASE (SELECT COUNT(r.id) FROM Root r) WHEN 1 THEN 1 ELSE 0 END FROM Leaf l"; - // simple syntax check - Session s = openSession(); - s.beginTransaction(); - s.createQuery( query ).list(); - s.getTransaction().commit(); - s.close(); - } - - @Test - @JiraKeyGroup( value = { - @JiraKey( value = "HHH-1689" ), - @JiraKey( value = "SQM-30" ) - } ) - public void testSubQueryAsSimpleCaseWhenExpression() { - final String query = "SELECT CASE l.id WHEN (SELECT COUNT(r.id) FROM Root r) THEN 1 ELSE 0 END FROM Leaf l"; - // simple syntax check - Session s = openSession(); - s.beginTransaction(); - s.createQuery( query ).list(); - s.getTransaction().commit(); - s.close(); - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/TreatKeywordTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/TreatKeywordTest.java index c52cafb4b617..d6fc0642ab93 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/TreatKeywordTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/TreatKeywordTest.java @@ -4,16 +4,16 @@ */ package org.hibernate.orm.test.hql; -import java.util.List; -import org.hibernate.query.Query; -import org.hibernate.Session; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import static junit.framework.TestCase.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests the "treat" keyword in HQL. @@ -23,65 +23,43 @@ * * @see org.hibernate.orm.test.jpa.ql.TreatKeywordTest */ -public class TreatKeywordTest extends BaseCoreFunctionalTestCase { - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } - - @Override - public String[] getMappings() { - return new String[] { "hql/Animal.hbm.xml" }; +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(xmlMappings = "org/hibernate/orm/test/hql/Animal.hbm.xml") +@SessionFactory +public class TreatKeywordTest { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test @JiraKey( value = "HHH-9342" ) - public void memberOfTreatTest() { + public void memberOfTreatTest(SessionFactoryScope factoryScope) { // prepare test data - Session s = openSession(); - s.getTransaction().begin(); - - Human owner = new Human(); - s.persist( owner ); - - Dog wildDog = new Dog(); - s.persist( wildDog ); - - Dog petDog = new Dog(); - petDog.setOwner( owner ); - s.persist( petDog ); - - Cat petCat = new Cat(); - petCat.setOwner( owner ); - s.persist( petCat ); - - s.getTransaction().commit(); - s.close(); - - - // perform test - s = openSession(); - s.getTransaction().begin(); - Query q = s.createQuery( - "select pet" + - " from Animal pet, Animal owner" + - " where pet member of treat (owner as Human).pets" - ); - @SuppressWarnings("unchecked") - List results = q.list(); - assertEquals( 2, results.size() ); - s.getTransaction().commit(); - s.close(); - - - // clean up test data - s = openSession(); - s.getTransaction().begin(); - s.remove( petCat ); - s.remove( petDog ); - s.remove( wildDog ); - s.remove( owner ); - s.getTransaction().commit(); - s.close(); + factoryScope.inTransaction( (s) -> { + var owner = new Human(); + s.persist( owner ); + + var wildDog = new Dog(); + s.persist( wildDog ); + + var petDog = new Dog(); + petDog.setOwner( owner ); + s.persist( petDog ); + + var petCat = new Cat(); + petCat.setOwner( owner ); + s.persist( petCat ); + } ); + + factoryScope.inTransaction( (s) -> { + var hql = """ + select pet + from Animal pet, Animal owner + where pet member of treat (owner as Human).pets + """; + var results = s.createQuery( hql ).list(); + assertEquals( 2, results.size() ); + } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/UpdateJoinedSubclassCorrelationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/UpdateJoinedSubclassCorrelationTest.java index eaa8415a0fa1..057d714f095e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/UpdateJoinedSubclassCorrelationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/UpdateJoinedSubclassCorrelationTest.java @@ -4,39 +4,49 @@ */ package org.hibernate.orm.test.hql; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Assert; -import org.junit.Test; - -import jakarta.persistence.*; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Inheritance; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Query; import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import java.util.List; import static jakarta.persistence.InheritanceType.JOINED; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import static org.junit.jupiter.api.Assertions.assertEquals; +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey(value = "HHH-13169") -public class UpdateJoinedSubclassCorrelationTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Root.class, SubRoot.class, Detail.class }; +@DomainModel(annotatedClasses = { + UpdateJoinedSubclassCorrelationTest.Root.class, + UpdateJoinedSubclassCorrelationTest.SubRoot.class, + UpdateJoinedSubclassCorrelationTest.Detail.class +}) +@SessionFactory +public class UpdateJoinedSubclassCorrelationTest { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test - public void testJoinedSubclassUpdateWithCorrelation() { - // prepare - doInJPA( this::entityManagerFactory, entityManager -> { + public void testJoinedSubclassUpdateWithCorrelation(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { Root m1 = new SubRoot( 1, null ); entityManager.persist( m1 ); Detail d11 = new Detail( 10, m1 ); entityManager.persist( d11 ); } ); - doInJPA( this::entityManagerFactory, entityManager -> { + factoryScope.inTransaction( entityManager -> { // DO NOT CHANGE this query: it used to trigger a very specific bug caused // by the root table alias being added to the generated subquery instead of the table name String u = "update SubRoot m set name = (select 'test' from Detail d where d.root = m)"; @@ -48,8 +58,8 @@ public void testJoinedSubclassUpdateWithCorrelation() { CriteriaQuery query = builder.createQuery( Root.class ); query.select( query.from( Root.class ) ); List roots = entityManager.createQuery( query ).getResultList(); - Assert.assertEquals( 1, roots.size() ); - Assert.assertEquals( "test", ((SubRoot) roots.get(0)).name ); + assertEquals( 1, roots.size() ); + assertEquals( "test", ((SubRoot) roots.get(0)).name ); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/fetchAndJoin/ToManyFetchAndJoinTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/fetchAndJoin/ToManyFetchAndJoinTest.java index 51d949c8dd92..3b87156d3bca 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/fetchAndJoin/ToManyFetchAndJoinTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/fetchAndJoin/ToManyFetchAndJoinTest.java @@ -6,182 +6,173 @@ import java.util.Iterator; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - import org.hibernate.Hibernate; -import org.hibernate.Session; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Gail Badner */ -public class ToManyFetchAndJoinTest extends BaseCoreFunctionalTestCase { - - @Before - public void setupData() { - Parent p = new Parent( "p" ); - Child c1 = new Child( "c1" ); - GrandChild gc11 = new GrandChild( "gc11" ); - GrandChild gc12 = new GrandChild( "gc12" ); - p.getChildren().add( c1 ); - c1.getGrandChildren().add( gc11 ); - c1.getGrandChildren().add( gc12 ); - - Child c2 = new Child( "c2" ); - GrandChild gc21 = new GrandChild( "gc21" ); - GrandChild gc22 = new GrandChild( "gc22" ); - GrandChild gc23 = new GrandChild( "gc23" ); - p.getChildren().add( c2 ); - c2.getGrandChildren().add( gc21 ); - c2.getGrandChildren().add( gc22 ); - c2.getGrandChildren().add( gc23 ); - - Session s = openSession(); - s.getTransaction().begin(); - s.persist( p ); - s.getTransaction().commit(); - s.close(); +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(annotatedClasses = { + Parent.class, + Child.class, + GrandChild.class +}) +@SessionFactory +public class ToManyFetchAndJoinTest { + + @BeforeEach + public void setupData(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( session -> { + Parent p = new Parent( "p" ); + Child c1 = new Child( "c1" ); + GrandChild gc11 = new GrandChild( "gc11" ); + GrandChild gc12 = new GrandChild( "gc12" ); + p.getChildren().add( c1 ); + c1.getGrandChildren().add( gc11 ); + c1.getGrandChildren().add( gc12 ); + + Child c2 = new Child( "c2" ); + GrandChild gc21 = new GrandChild( "gc21" ); + GrandChild gc22 = new GrandChild( "gc22" ); + GrandChild gc23 = new GrandChild( "gc23" ); + p.getChildren().add( c2 ); + c2.getGrandChildren().add( gc21 ); + c2.getGrandChildren().add( gc22 ); + c2.getGrandChildren().add( gc23 ); + + session.persist( p ); + } ); } - @After - public void cleanupData() { - Session s = openSession(); - s.getTransaction().begin(); - s.createQuery( "delete GrandChild" ).executeUpdate(); - s.createQuery( "delete Child" ).executeUpdate(); - s.createQuery( "delete Parent" ).executeUpdate(); - s.getTransaction().commit(); - s.close(); + @AfterEach + public void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test @JiraKey( value = "HHH-9637") - public void testExplicitJoinBeforeFetchJoins() { - - Session s = openSession(); - s.getTransaction().begin(); - - Parent p = - (Parent) s.createQuery( - "select p from Parent p inner join p.children cRestrict inner join fetch p.children c inner join fetch c.grandChildren where cRestrict.value = 'c1'" ) - .uniqueResult(); - - assertEquals( "p", p.getValue() ); - assertTrue( Hibernate.isInitialized( p.getChildren() ) ); - assertEquals( 2, p.getChildren().size() ); - Iterator iterator = p.getChildren().iterator(); - Child cA = iterator.next(); - assertTrue( Hibernate.isInitialized( cA.getGrandChildren() ) ); - if ( cA.getValue().equals( "c1" ) ) { - assertEquals( 2, cA.getGrandChildren().size() ); - Child cB = iterator.next(); - assertTrue( Hibernate.isInitialized( cB.getGrandChildren() ) ); - assertEquals( 3, cB.getGrandChildren().size() ); - } - else if ( cA.getValue().equals( "c2" ) ) { - assertEquals( 3, cA.getGrandChildren().size() ); - Child cB = iterator.next(); - assertTrue( Hibernate.isInitialized( cB.getGrandChildren() ) ); - assertEquals( 2, cB.getGrandChildren().size() ); - } - else { - fail( "unexpected value" ); - } - - s.getTransaction().commit(); - s.close(); + public void testExplicitJoinBeforeFetchJoins(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( session -> { + + var hql = """ + select p + from Parent p + inner join p.children cRestrict + inner join fetch p.children c + inner join fetch c.grandChildren + where cRestrict.value = 'c1' + """; + var parent = session.createQuery( hql, Parent.class ).uniqueResult(); + + assertEquals( "p", parent.getValue() ); + assertTrue( Hibernate.isInitialized( parent.getChildren() ) ); + assertEquals( 2, parent.getChildren().size() ); + Iterator iterator = parent.getChildren().iterator(); + Child cA = iterator.next(); + assertTrue( Hibernate.isInitialized( cA.getGrandChildren() ) ); + if ( cA.getValue().equals( "c1" ) ) { + assertEquals( 2, cA.getGrandChildren().size() ); + Child cB = iterator.next(); + assertTrue( Hibernate.isInitialized( cB.getGrandChildren() ) ); + assertEquals( 3, cB.getGrandChildren().size() ); + } + else if ( cA.getValue().equals( "c2" ) ) { + assertEquals( 3, cA.getGrandChildren().size() ); + Child cB = iterator.next(); + assertTrue( Hibernate.isInitialized( cB.getGrandChildren() ) ); + assertEquals( 2, cB.getGrandChildren().size() ); + } + else { + fail( "unexpected value" ); + } + } ); } @Test @JiraKey( value = "HHH-9637") - public void testExplicitJoinBetweenFetchJoins() { - - Session s = openSession(); - s.getTransaction().begin(); - - Parent p = - (Parent) s.createQuery( - "select p from Parent p inner join fetch p.children c inner join p.children cRestrict inner join fetch c.grandChildren where cRestrict.value = 'c1'" ) - .uniqueResult(); - - assertEquals( "p", p.getValue() ); - assertTrue( Hibernate.isInitialized( p.getChildren() ) ); - assertEquals( 2, p.getChildren().size() ); - Iterator iterator = p.getChildren().iterator(); - Child cA = iterator.next(); - assertTrue( Hibernate.isInitialized( cA.getGrandChildren() ) ); - if ( cA.getValue().equals( "c1" ) ) { - assertEquals( 2, cA.getGrandChildren().size() ); - Child cB = iterator.next(); - assertTrue( Hibernate.isInitialized( cB.getGrandChildren() ) ); - assertEquals( 3, cB.getGrandChildren().size() ); - } - else if ( cA.getValue().equals( "c2" ) ) { - assertEquals( 3, cA.getGrandChildren().size() ); - Child cB = iterator.next(); - assertTrue( Hibernate.isInitialized( cB.getGrandChildren() ) ); - assertEquals( 2, cB.getGrandChildren().size() ); - } - else { - fail( "unexpected value" ); - } - - s.getTransaction().commit(); - s.close(); + public void testExplicitJoinBetweenFetchJoins(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( session -> { + var hql = """ + select p + from Parent p + inner join fetch p.children c + inner join p.children cRestrict + inner join fetch c.grandChildren + where cRestrict.value = 'c1' + """; + var parent = session.createQuery( hql, Parent.class ).uniqueResult(); + + assertEquals( "p", parent.getValue() ); + assertTrue( Hibernate.isInitialized( parent.getChildren() ) ); + assertEquals( 2, parent.getChildren().size() ); + Iterator iterator = parent.getChildren().iterator(); + Child cA = iterator.next(); + assertTrue( Hibernate.isInitialized( cA.getGrandChildren() ) ); + if ( cA.getValue().equals( "c1" ) ) { + assertEquals( 2, cA.getGrandChildren().size() ); + Child cB = iterator.next(); + assertTrue( Hibernate.isInitialized( cB.getGrandChildren() ) ); + assertEquals( 3, cB.getGrandChildren().size() ); + } + else if ( cA.getValue().equals( "c2" ) ) { + assertEquals( 3, cA.getGrandChildren().size() ); + Child cB = iterator.next(); + assertTrue( Hibernate.isInitialized( cB.getGrandChildren() ) ); + assertEquals( 2, cB.getGrandChildren().size() ); + } + else { + fail( "unexpected value" ); + } + } ); } @Test @JiraKey( value = "HHH-9637") - public void testExplicitJoinAfterFetchJoins() { - - Session s = openSession(); - s.getTransaction().begin(); - - Parent p = - (Parent) s.createQuery( - "select p from Parent p inner join fetch p.children c inner join fetch c.grandChildren inner join p.children cRestrict where cRestrict.value = 'c1'" ) - .uniqueResult(); - - assertEquals( "p", p.getValue() ); - assertTrue( Hibernate.isInitialized( p.getChildren() ) ); - assertEquals( 2, p.getChildren().size() ); - Iterator iterator = p.getChildren().iterator(); - Child cA = iterator.next(); - assertTrue( Hibernate.isInitialized( cA.getGrandChildren() ) ); - if ( cA.getValue().equals( "c1" ) ) { - assertEquals( 2, cA.getGrandChildren().size() ); - Child cB = iterator.next(); - assertTrue( Hibernate.isInitialized( cB.getGrandChildren() ) ); - assertEquals( 3, cB.getGrandChildren().size() ); - } - else if ( cA.getValue().equals( "c2" ) ) { - assertEquals( 3, cA.getGrandChildren().size() ); - Child cB = iterator.next(); - assertTrue( Hibernate.isInitialized( cB.getGrandChildren() ) ); - assertEquals( 2, cB.getGrandChildren().size() ); - } - else { - fail( "unexpected value" ); - } - - s.getTransaction().commit(); - s.close(); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - Parent.class, - Child.class, - GrandChild.class - }; + public void testExplicitJoinAfterFetchJoins(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( session -> { + var hql = """ + select p + from Parent p + inner join fetch p.children c + inner join fetch c.grandChildren + inner join p.children cRestrict + where cRestrict.value = 'c1' + """; + Parent parent = session.createQuery( hql, Parent.class ).uniqueResult(); + + assertEquals( "p", parent.getValue() ); + assertTrue( Hibernate.isInitialized( parent.getChildren() ) ); + assertEquals( 2, parent.getChildren().size() ); + Iterator iterator = parent.getChildren().iterator(); + Child cA = iterator.next(); + assertTrue( Hibernate.isInitialized( cA.getGrandChildren() ) ); + if ( cA.getValue().equals( "c1" ) ) { + assertEquals( 2, cA.getGrandChildren().size() ); + Child cB = iterator.next(); + assertTrue( Hibernate.isInitialized( cB.getGrandChildren() ) ); + assertEquals( 3, cB.getGrandChildren().size() ); + } + else if ( cA.getValue().equals( "c2" ) ) { + assertEquals( 3, cA.getGrandChildren().size() ); + Child cB = iterator.next(); + assertTrue( Hibernate.isInitialized( cB.getGrandChildren() ) ); + assertEquals( 2, cB.getGrandChildren().size() ); + } + else { + fail( "unexpected value" ); + } + } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/size/WhereClauseOrderBySizeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/size/WhereClauseOrderBySizeTest.java index 8a2698bfd60f..e46d58759793 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/size/WhereClauseOrderBySizeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/size/WhereClauseOrderBySizeTest.java @@ -4,21 +4,6 @@ */ package org.hibernate.orm.test.hql.size; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.hibernate.annotations.SQLDelete; -import org.hibernate.annotations.SQLRestriction; -import org.hibernate.dialect.H2Dialect; -import org.hibernate.dialect.PostgreSQLDialect; -import org.hibernate.jdbc.Expectation; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; - import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; @@ -27,65 +12,79 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; import jakarta.persistence.TypedQuery; +import org.hibernate.annotations.SQLDelete; +import org.hibernate.annotations.SQLRestriction; +import org.hibernate.dialect.H2Dialect; +import org.hibernate.dialect.PostgreSQLDialect; +import org.hibernate.jdbc.Expectation; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; + +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey(value = "HHH-14585") @RequiresDialect(value = PostgreSQLDialect.class, comment = "Other databases may not support boolean data types") @RequiresDialect(value = H2Dialect.class, comment = "Other databases may not support boolean data types") -public class WhereClauseOrderBySizeTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Person.class, Book.class }; +@DomainModel(annotatedClasses = { WhereClauseOrderBySizeTest.Person.class, WhereClauseOrderBySizeTest.Book.class }) +@SessionFactory +public class WhereClauseOrderBySizeTest { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test - public void testSizeAsOrderByExpression() { - doInJPA( - this::entityManagerFactory, - entityManager -> { - // initial situation: Alice has 1 book, Bob none - final Person alice = new Person( "Alice" ); - entityManager.persist( alice ); - - final Book book1 = new Book(); - book1.setOwner( alice ); - entityManager.persist( book1 ); - - final Person bob = new Person( "Bob" ); - entityManager.persist( bob ); - - final TypedQuery orderByBroken = entityManager.createQuery( - "SELECT p FROM Person p ORDER BY size(p.books) DESC", - Person.class - ); - - List dbPeopleBroken = orderByBroken.getResultList(); - assertEquals( Arrays.asList( alice, bob ), dbPeopleBroken ); - - // add 2 books to Bob - final Book book2 = new Book(); - book2.setOwner( bob ); - entityManager.persist( book2 ); - - final Book book3 = new Book(); - book3.setOwner( bob ); - entityManager.persist( book3 ); - - dbPeopleBroken = orderByBroken.getResultList(); - assertEquals( Arrays.asList( bob, alice ), dbPeopleBroken ); - - // remove (soft-deleting) both Bob's books - entityManager.remove( book2 ); - entityManager.remove( book3 ); - - // result lists are not equal anymore - dbPeopleBroken = orderByBroken.getResultList(); - assertEquals( Arrays.asList( alice, bob ), dbPeopleBroken ); - } - ); + public void testSizeAsOrderByExpression(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (entityManager) -> { + // initial situation: Alice has 1 book, Bob none + final Person alice = new Person( "Alice" ); + entityManager.persist( alice ); + + final Book book1 = new Book(); + book1.setOwner( alice ); + entityManager.persist( book1 ); + + final Person bob = new Person( "Bob" ); + entityManager.persist( bob ); + + final TypedQuery orderByBroken = entityManager.createQuery( + "SELECT p FROM Person p ORDER BY size(p.books) DESC", + Person.class + ); + + List dbPeopleBroken = orderByBroken.getResultList(); + assertEquals( Arrays.asList( alice, bob ), dbPeopleBroken ); + + // add 2 books to Bob + final Book book2 = new Book(); + book2.setOwner( bob ); + entityManager.persist( book2 ); + + final Book book3 = new Book(); + book3.setOwner( bob ); + entityManager.persist( book3 ); + + dbPeopleBroken = orderByBroken.getResultList(); + assertEquals( Arrays.asList( bob, alice ), dbPeopleBroken ); + + // remove (soft-deleting) both Bob's books + entityManager.remove( book2 ); + entityManager.remove( book3 ); + + // result lists are not equal anymore + dbPeopleBroken = orderByBroken.getResultList(); + assertEquals( Arrays.asList( alice, bob ), dbPeopleBroken ); + } ); } @Entity(name = "Person") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/size/filter/WhereAnnotatedOneToManySizeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/size/filter/WhereAnnotatedOneToManySizeTest.java index dd0f21ac4832..dffe69bc9951 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/size/filter/WhereAnnotatedOneToManySizeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/size/filter/WhereAnnotatedOneToManySizeTest.java @@ -15,62 +15,62 @@ import org.hibernate.community.dialect.TiDBDialect; import org.hibernate.query.Query; -import org.hibernate.testing.SkipForDialect; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.SkipForDialect; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; @JiraKey(value = "HHH-14585") -public class WhereAnnotatedOneToManySizeTest extends BaseCoreFunctionalTestCase { +@DomainModel(annotatedClasses = { Region.class, City.class }) +@SessionFactory +public class WhereAnnotatedOneToManySizeTest { + + + @BeforeEach + public void createTestData(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + Region lazio = new Region(); + lazio.setId( 1 ); + lazio.setName( "Lazio" ); + + Region lombardy = new Region(); + lombardy.setId( 2 ); + lombardy.setName( "Lombardy" ); + + City rome = new City(); + rome.setId( 1 ); + rome.setName( "Rome" ); + rome.setDeleted( false ); + rome.setRegion( lazio ); + + City gradoli = new City(); + gradoli.setId( 2 ); + gradoli.setName( "Gradoli" ); + gradoli.setDeleted( true ); + gradoli.setRegion( lazio ); + + City milan = new City(); + milan.setId( 3 ); + milan.setName( "Milan" ); + milan.setDeleted( false ); + milan.setRegion( lombardy ); + + City pavia = new City(); + pavia.setId( 4 ); + pavia.setName( "Pavia" ); + pavia.setDeleted( false ); + pavia.setRegion( lombardy ); + + lazio.getCities().add( rome ); + lazio.getCities().add( gradoli ); + + lombardy.getCities().add( milan ); + lombardy.getCities().add( pavia ); - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Region.class, City.class }; - } - - @Before - public void before() { - Region lazio = new Region(); - lazio.setId( 1 ); - lazio.setName( "Lazio" ); - - Region lombardy = new Region(); - lombardy.setId( 2 ); - lombardy.setName( "Lombardy" ); - - City rome = new City(); - rome.setId( 1 ); - rome.setName( "Rome" ); - rome.setDeleted( false ); - rome.setRegion( lazio ); - - City gradoli = new City(); - gradoli.setId( 2 ); - gradoli.setName( "Gradoli" ); - gradoli.setDeleted( true ); - gradoli.setRegion( lazio ); - - City milan = new City(); - milan.setId( 3 ); - milan.setName( "Milan" ); - milan.setDeleted( false ); - milan.setRegion( lombardy ); - - City pavia = new City(); - pavia.setId( 4 ); - pavia.setName( "Pavia" ); - pavia.setDeleted( false ); - pavia.setRegion( lombardy ); - - lazio.getCities().add( rome ); - lazio.getCities().add( gradoli ); - - lombardy.getCities().add( milan ); - lombardy.getCities().add( pavia ); - - inTransaction( session -> { session.persist( lazio ); session.persist( lombardy ); @@ -81,22 +81,24 @@ public void before() { } ); } - @After - public void after() { - inTransaction( session -> { - session.createNativeQuery( "DELETE FROM City" ).executeUpdate(); - session.createQuery( "DELETE FROM Region c" ).executeUpdate(); - } ); + @AfterEach + public void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test - @SkipForDialect(value = DB2Dialect.class, comment = "DB2 does not support correlated subqueries in the ORDER BY clause") - @SkipForDialect(value = HANADialect.class, comment = "HANA db does not support correlated subqueries in the ORDER BY clause") - @SkipForDialect(value = TiDBDialect.class, comment = "TiDB db does not support correlated subqueries in the ORDER BY clause") - @SkipForDialect(value = SybaseDialect.class, comment = "Sybase db does not support subqueries in the ORDER BY clause") - @SkipForDialect(value = InformixDialect.class, comment = "Informix does not support correlated subqueries in the ORDER BY clause") - public void orderBy_sizeOf() { - inSession( session -> { + @SkipForDialect(dialectClass = DB2Dialect.class, + reason = "DB2 does not support correlated subqueries in the ORDER BY clause") + @SkipForDialect(dialectClass = HANADialect.class, + reason = "HANA db does not support correlated subqueries in the ORDER BY clause") + @SkipForDialect(dialectClass = TiDBDialect.class, + reason = "TiDB db does not support correlated subqueries in the ORDER BY clause") + @SkipForDialect(dialectClass = SybaseDialect.class, + reason = "Sybase db does not support subqueries in the ORDER BY clause") + @SkipForDialect(dialectClass = InformixDialect.class, + reason = "Informix does not support correlated subqueries in the ORDER BY clause") + public void orderBy_sizeOf(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { Query query = session.createQuery( "select r, size(r.cities) from Region r order by size(r.cities) desc" ); List result = query.getResultList(); @@ -106,8 +108,8 @@ public void orderBy_sizeOf() { } @Test - public void project_sizeOf() { - inSession( session -> { + public void project_sizeOf(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { Query query = session.createQuery( "SELECT size(r.cities) FROM Region r", Integer.class ); List cityCounts = query.getResultList(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/id/IdClassManyToOneCascadeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/id/IdClassManyToOneCascadeTest.java index cd7c4caffd63..18912f9602f4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/id/IdClassManyToOneCascadeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/id/IdClassManyToOneCascadeTest.java @@ -12,32 +12,35 @@ import jakarta.persistence.IdClass; import jakarta.persistence.ManyToOne; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertTrue; /** * @author Vlad Mihalcea */ +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey( value = "HHH-12251" ) -public class IdClassManyToOneCascadeTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - SomeEntity.class, - ReferencedEntity.class - }; +@DomainModel(annotatedClasses = { + IdClassManyToOneCascadeTest.SomeEntity.class, + IdClassManyToOneCascadeTest.ReferencedEntity.class +}) +@SessionFactory +public class IdClassManyToOneCascadeTest { + @AfterEach + public void tearDown(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test - public void testMergeCascadesToManyToOne() { - - doInJPA( this::entityManagerFactory, entityManager -> { + public void testMergeCascadesToManyToOne(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { ReferencedEntity referencedEntity = new ReferencedEntity(); referencedEntity.setId( 42L ); @@ -47,14 +50,13 @@ public void testMergeCascadesToManyToOne() { SomeEntity merged = entityManager.merge(someEntity); - assertTrue( entityManager.contains( merged.getReferencedEntity() ) ); + Assertions.assertTrue( entityManager.contains( merged.getReferencedEntity() ) ); } ); } @Test - public void testPersistCascadesToManyToOne() { - - doInJPA( this::entityManagerFactory, entityManager -> { + public void testPersistCascadesToManyToOne(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( entityManager -> { ReferencedEntity referencedEntity = new ReferencedEntity(); referencedEntity.setId( 42L ); @@ -64,7 +66,7 @@ public void testPersistCascadesToManyToOne() { entityManager.persist( someEntity ); - assertTrue( entityManager.contains( referencedEntity ) ); + Assertions.assertTrue( entityManager.contains( referencedEntity ) ); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/id/ReSaveReferencedDeletedEntity.java b/hibernate-core/src/test/java/org/hibernate/orm/test/id/ReSaveReferencedDeletedEntityTests.java similarity index 56% rename from hibernate-core/src/test/java/org/hibernate/orm/test/id/ReSaveReferencedDeletedEntity.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/id/ReSaveReferencedDeletedEntityTests.java index 65b66f73e67d..68b4a97d0a65 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/id/ReSaveReferencedDeletedEntity.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/id/ReSaveReferencedDeletedEntityTests.java @@ -4,36 +4,43 @@ */ package org.hibernate.orm.test.id; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.OneToOne; import org.hibernate.dialect.HANADialect; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; import org.hibernate.testing.orm.junit.SkipForDialect; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import jakarta.persistence.*; - -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; +import static org.hibernate.cfg.AvailableSettings.USE_IDENTIFIER_ROLLBACK; +@SuppressWarnings("JUnitMalformedDeclaration") @SkipForDialect( dialectClass = HANADialect.class, reason = "The INSERT statement for table [Child] contains no column, and this is not supported") -public class ReSaveReferencedDeletedEntity extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Child.class, Parent.class }; - } - - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - configuration.setProperty( AvailableSettings.USE_IDENTIFIER_ROLLBACK, "true" ); +@ServiceRegistry(settings = @Setting(name=USE_IDENTIFIER_ROLLBACK, value = "true")) +@DomainModel(annotatedClasses = { + ReSaveReferencedDeletedEntityTests.Child.class, + ReSaveReferencedDeletedEntityTests.Parent.class +}) +@SessionFactory +public class ReSaveReferencedDeletedEntityTests { + @AfterEach + public void dropTestData(SessionFactoryScope factoryScope) throws Exception { + factoryScope.dropData(); } @Test @JiraKey("HHH-14416") - public void testReSaveDeletedEntity() { - doInHibernate( this::sessionFactory, session -> { + public void testReSaveDeletedEntity(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { Parent parent = new Parent(); Child child = new Child(); @@ -53,8 +60,8 @@ public void testReSaveDeletedEntity() { @Test @JiraKey("HHH-14416") - public void testReSaveDeletedEntityWithDetach() { - doInHibernate( this::sessionFactory, session -> { + public void testReSaveDeletedEntityWithDetach(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { Parent parent = new Parent(); Child child = new Child(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/id/enhanced/OptimizerConcurrencyUnitTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/id/enhanced/OptimizerConcurrencyUnitTest.java index aa2ca2e80fa6..8d755e94f3a1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/id/enhanced/OptimizerConcurrencyUnitTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/id/enhanced/OptimizerConcurrencyUnitTest.java @@ -22,55 +22,33 @@ import org.hibernate.id.enhanced.Optimizer; import org.hibernate.id.enhanced.OptimizerFactory; import org.hibernate.id.enhanced.StandardOptimizerDescriptor; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.hibernate.testing.junit4.CustomParameterized; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.junit.Assert.assertEquals; -@RunWith(CustomParameterized.class) -public class OptimizerConcurrencyUnitTest extends BaseUnitTestCase { +public class OptimizerConcurrencyUnitTest { - @Parameterized.Parameters(name = "{0}") - public static List params() { - List params = new ArrayList<>(); - for ( StandardOptimizerDescriptor value : StandardOptimizerDescriptor.values() ) { - params.add( new Object[] { value } ); - } - return params; - } - - private final StandardOptimizerDescriptor optimizerDescriptor; - - public OptimizerConcurrencyUnitTest(StandardOptimizerDescriptor optimizerDescriptor) { - this.optimizerDescriptor = optimizerDescriptor; - } - - @Test - public void testConcurrentUsage_singleTenancy() throws InterruptedException { + @ParameterizedTest + @MethodSource("org.hibernate.id.enhanced.StandardOptimizerDescriptor#values") + public void testConcurrentUsage_singleTenancy(StandardOptimizerDescriptor descriptor) throws InterruptedException { final int increment = 50; final int taskCount = 100 * increment; - Optimizer optimizer = buildOptimizer( 1, increment ); + Optimizer optimizer = buildOptimizer( 1, increment, descriptor ); List> tasks = new ArrayList<>(); SourceMock sequence = new SourceMock( 1, increment ); - assertEquals( 0, sequence.getTimesCalled() ); - assertEquals( -1, sequence.getCurrentValue() ); + Assertions.assertEquals( 0, sequence.getTimesCalled() ); + Assertions.assertEquals( -1, sequence.getCurrentValue() ); for ( int i = 0; i < taskCount; i++ ) { - tasks.add( new Callable() { - @Override - public Long call() throws Exception { - return ( Long ) optimizer.generate( sequence ); - } - } ); + tasks.add( () -> ( Long ) optimizer.generate( sequence ) ); } ExecutorService executor = Executors.newFixedThreadPool( 10 ); @@ -97,14 +75,15 @@ public Long call() throws Exception { System.out.println( "Generated IDs: " + generated ); } - @Test - public void testConcurrentUsage_multiTenancy() throws InterruptedException { + @ParameterizedTest + @MethodSource("org.hibernate.id.enhanced.StandardOptimizerDescriptor#values") + public void testConcurrentUsage_multiTenancy(StandardOptimizerDescriptor descriptor) throws InterruptedException { final int increment = 50; final int tenantCount = 5; final int taskCountPerTenant = 20 * increment; - Optimizer optimizer = buildOptimizer( 1, increment ); + Optimizer optimizer = buildOptimizer( 1, increment, descriptor ); Map>> tasksByTenantId = new LinkedHashMap<>(); @@ -118,12 +97,7 @@ public void testConcurrentUsage_multiTenancy() throws InterruptedException { List> tasksForTenant = new ArrayList<>(); tasksByTenantId.put( tenantId, tasksForTenant ); for ( int j = 0; j < taskCountPerTenant; j++ ) { - tasksForTenant.add( new Callable() { - @Override - public Long call() throws Exception { - return ( Long ) optimizer.generate( sequenceForTenant ); - } - } ); + tasksForTenant.add( () -> ( Long ) optimizer.generate( sequenceForTenant ) ); } } @@ -173,7 +147,7 @@ public Long call() throws Exception { } } - private Optimizer buildOptimizer(long initial, int increment) { + private Optimizer buildOptimizer(long initial, int increment, StandardOptimizerDescriptor optimizerDescriptor) { return OptimizerFactory.buildOptimizer( optimizerDescriptor, Long.class, increment, initial ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/id/sequence/SequenceExportTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/id/sequence/SequenceExportTest.java index 0c8eaa425de7..8664d7d837e2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/id/sequence/SequenceExportTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/id/sequence/SequenceExportTest.java @@ -7,48 +7,41 @@ import org.hibernate.boot.MetadataSources; import org.hibernate.boot.model.relational.Namespace; import org.hibernate.boot.model.relational.Sequence; +import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.spi.MetadataImplementor; -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.DialectFeatureChecks; 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 jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.Table; +import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.ServiceRegistryProducer; +import org.hibernate.testing.orm.junit.ServiceRegistryScope; +import org.hibernate.testing.util.ServiceRegistryUtil; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; /** * @author Steve Ebersole */ -@RequiresDialectFeature(value= DialectChecks.SupportsSequences.class, jiraKey = "HHH-10320" ) -public class SequenceExportTest extends BaseUnitTestCase { - private StandardServiceRegistry ssr; - - @Before - public void prepare() { - ssr = ServiceRegistryUtil.serviceRegistry(); - } - - @After - public void destroy() { - StandardServiceRegistryBuilder.destroy( ssr ); - } +@SuppressWarnings("JUnitMalformedDeclaration") +@JiraKey("HHH-10320") +@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsSequences.class ) +@ServiceRegistry +public class SequenceExportTest implements ServiceRegistryProducer { @Test - @JiraKey( value = "HHH-9936" ) - public void testMultipleUsesOfDefaultSequenceName() { - final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( ssr ) + @JiraKey("HHH-9936") + public void testMultipleUsesOfDefaultSequenceName(ServiceRegistryScope registryScope) { + final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( registryScope.getRegistry() ) .addAnnotatedClass( Entity1.class ) .addAnnotatedClass( Entity2.class ) .buildMetadata(); @@ -70,9 +63,9 @@ public void testMultipleUsesOfDefaultSequenceName() { } @Test - @JiraKey( value = "HHH-9936" ) - public void testMultipleUsesOfExplicitSequenceName() { - final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( ssr ) + @JiraKey("HHH-9936") + public void testMultipleUsesOfExplicitSequenceName(ServiceRegistryScope registryScope) { + final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( registryScope.getRegistry() ) .addAnnotatedClass( Entity3.class ) .addAnnotatedClass( Entity4.class ) .buildMetadata(); @@ -92,6 +85,15 @@ public void testMultipleUsesOfExplicitSequenceName() { assertThat( sequenceCount ).isEqualTo( 1 ); } + @Override + public StandardServiceRegistry produceServiceRegistry(StandardServiceRegistryBuilder builder) { + return ServiceRegistryUtil.applySettings( builder ).build(); + } + + @Override + public void prepareBootstrapRegistryBuilder(BootstrapServiceRegistryBuilder bsrb) { + } + @Entity( name = "Entity1" ) @Table( name = "Entity1" ) public static class Entity1 { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/id/uuid/generator/UUID2GeneratorStringUniqueIdentifierIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/id/uuid/generator/UUID2GeneratorStringUniqueIdentifierIdTest.java index bda4bf4177af..dbbf54351cad 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/id/uuid/generator/UUID2GeneratorStringUniqueIdentifierIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/id/uuid/generator/UUID2GeneratorStringUniqueIdentifierIdTest.java @@ -4,8 +4,6 @@ */ package org.hibernate.orm.test.id.uuid.generator; -import java.util.HashSet; -import java.util.Set; import jakarta.persistence.Column; import jakarta.persistence.ElementCollection; import jakarta.persistence.Entity; @@ -13,57 +11,63 @@ import jakarta.persistence.Id; import jakarta.persistence.JoinTable; import jakarta.persistence.Table; - import org.hibernate.annotations.GenericGenerator; import org.hibernate.dialect.SQLServerDialect; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -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.AfterEach; +import org.junit.jupiter.api.Test; + +import java.util.HashSet; +import java.util.Set; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Vlad Mihalcea */ -@RequiresDialect( SQLServerDialect.class ) -@JiraKey( value = "HHH-12943" ) -public class UUID2GeneratorStringUniqueIdentifierIdTest extends BaseEntityManagerFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { FooEntity.class }; +@SuppressWarnings("JUnitMalformedDeclaration") +@RequiresDialect(SQLServerDialect.class) +@JiraKey("HHH-12943") +@DomainModel(annotatedClasses = UUID2GeneratorStringUniqueIdentifierIdTest.FooEntity.class) +@SessionFactory +public class UUID2GeneratorStringUniqueIdentifierIdTest { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test - public void testPaginationQuery() { - String id = doInJPA( this::entityManagerFactory, entityManager -> { + public void testPaginationQuery(SessionFactoryScope factoryScope) { + var fooId = factoryScope.fromTransaction( (session) -> { FooEntity entity = new FooEntity(); entity.getFooValues().add("one"); entity.getFooValues().add("two"); entity.getFooValues().add("three"); - entityManager.persist(entity); + session.persist(entity); return entity.getId(); } ); - assertNotNull(id); + assertNotNull( fooId ); - doInJPA( this::entityManagerFactory, entityManager -> { - FooEntity entity = entityManager.find(FooEntity.class, id.toUpperCase()); + factoryScope.inTransaction( session -> { + FooEntity entity = session.find(FooEntity.class, fooId.toUpperCase()); assertNotNull(entity); - assertTrue(entity.getFooValues().size() == 3); + assertEquals( 3, entity.getFooValues().size() ); } ); - doInJPA( this::entityManagerFactory, entityManager -> { - FooEntity entity = entityManager.find(FooEntity.class, id); + factoryScope.inTransaction( entityManager -> { + FooEntity entity = entityManager.find(FooEntity.class, fooId); assertNotNull(entity); - assertTrue(entity.getFooValues().size() == 3); + assertEquals( 3, entity.getFooValues().size() ); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idclass/IdClassHbmTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idclass/IdClassHbmTest.java index 7e317e6e113e..cae2c7a801d5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idclass/IdClassHbmTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idclass/IdClassHbmTest.java @@ -4,70 +4,60 @@ */ package org.hibernate.orm.test.idclass; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; - -import static org.junit.Assert.assertEquals; +import static org.hibernate.cfg.MappingSettings.JPA_METAMODEL_POPULATION; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Gavin King */ -public class IdClassHbmTest extends BaseCoreFunctionalTestCase { - public String[] getMappings() { - return new String[] { "/org/hibernate/orm/test/idclass/Customer.hbm.xml" }; - } - - @Override - protected void configure(Configuration configuration) { - // the Customer entity has a composite id that is not embeddable ( not supported by JPA ). - configuration.setProperty( AvailableSettings.JPA_METAMODEL_POPULATION, "disabled" ); +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(xmlMappings = "/org/hibernate/orm/test/idclass/Customer.hbm.xml") +@ServiceRegistry(settings = @Setting(name=JPA_METAMODEL_POPULATION, value = "disabled")) +@SessionFactory +public class IdClassHbmTest { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test - public void testIdClass() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Customer cust = new FavoriteCustomer("JBoss", "RouteOne", "Detroit"); - s.persist(cust); - t.commit(); - s.close(); - - s = openSession(); - CustomerId custId = new CustomerId("JBoss", "RouteOne"); - t = s.beginTransaction(); - cust = (Customer) s.get(Customer.class, custId); - assertEquals( "Detroit", cust.getAddress() ); - assertEquals( cust.getCustomerName(), custId.getCustomerName() ); - assertEquals( cust.getOrgName(), custId.getOrgName() ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - cust = (Customer) s.createQuery("from Customer where id.customerName = 'RouteOne'").uniqueResult(); - assertEquals( "Detroit", cust.getAddress() ); - assertEquals( cust.getCustomerName(), custId.getCustomerName() ); - assertEquals( cust.getOrgName(), custId.getOrgName() ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - cust = (Customer) s.createQuery("from Customer where customerName = 'RouteOne'").uniqueResult(); - assertEquals( "Detroit", cust.getAddress() ); - assertEquals( cust.getCustomerName(), custId.getCustomerName() ); - assertEquals( cust.getOrgName(), custId.getOrgName() ); - - s.createQuery( "delete from Customer" ).executeUpdate(); - - t.commit(); - s.close(); + public void testIdClass(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (s) -> { + var customer = new FavoriteCustomer("JBoss", "RouteOne", "Detroit"); + s.persist(customer); + } ); + + var customerId = new CustomerId("JBoss", "RouteOne"); + + factoryScope.inTransaction( (s) -> { + var customer = s.find( Customer.class, customerId ); + assertEquals( "Detroit", customer.getAddress() ); + assertEquals( customerId.getCustomerName(), customer.getCustomerName() ); + assertEquals( customerId.getOrgName(), customer.getOrgName() ); + } ); + + factoryScope.inTransaction( (s) -> { + var customer = s.createQuery("from Customer where id.customerName = 'RouteOne'", Customer.class).uniqueResult(); + assertEquals( "Detroit", customer.getAddress() ); + assertEquals( customerId.getCustomerName(), customer.getCustomerName() ); + assertEquals( customerId.getOrgName(), customer.getOrgName() ); + } ); + + factoryScope.inTransaction( (s) -> { + var customer = s.createQuery("from Customer where customerName = 'RouteOne'", Customer.class).uniqueResult(); + assertEquals( "Detroit", customer.getAddress() ); + assertEquals( customerId.getCustomerName(), customer.getCustomerName() ); + assertEquals( customerId.getOrgName(), customer.getOrgName() ); + } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idclass/JoinedSubclassWithIdClassTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idclass/JoinedSubclassWithIdClassTest.java index 82eb8e8d145d..cd8b2280494f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idclass/JoinedSubclassWithIdClassTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idclass/JoinedSubclassWithIdClassTest.java @@ -5,55 +5,55 @@ package org.hibernate.orm.test.idclass; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.IdClass; +import jakarta.persistence.Inheritance; +import jakarta.persistence.InheritanceType; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; + import java.io.Serializable; import java.util.Objects; -import jakarta.persistence.*; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; -import static org.hamcrest.core.Is.is; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Aber Tian */ @JiraKey("HHH-16054") -public class JoinedSubclassWithIdClassTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - BaseEntity.class, - ConcreteEntity.class - }; - } - +@DomainModel(annotatedClasses = { + JoinedSubclassWithIdClassTest.BaseEntity.class, + JoinedSubclassWithIdClassTest.ConcreteEntity.class +}) +@SessionFactory +public class JoinedSubclassWithIdClassTest { @Test - public void testJoinedSubClassWithIdClassComposeKey() { - - ConcreteEntity entity = new ConcreteEntity(); - entity.setId( 1L ); - entity.setDealer( "dealer" ); - entity.setName( "aber" ); - entity.setAge( 18 ); + public void testJoinedSubClassWithIdClassComposeKey(SessionFactoryScope factoryScope) { + var created = factoryScope.fromTransaction( (session) -> { + var entity = new ConcreteEntity(); + entity.setId( 1L ); + entity.setDealer( "dealer" ); + entity.setName( "aber" ); + entity.setAge( 18 ); + + return session.merge( entity ); + } ); - Pk pk = new Pk(); - pk.id = 1L; - pk.dealer = "dealer"; + factoryScope.inTransaction( (session) -> { + created.setName( "tian" ); + session.merge( created ); - doInHibernate( this::sessionFactory, session -> { - session.merge( entity ); - } ); + var pk = new Pk(); + pk.id = 1L; + pk.dealer = "dealer"; - doInHibernate( this::sessionFactory, session -> { - entity.setName( "tian" ); - session.merge( entity ); - BaseEntity baseEntity = session.find( BaseEntity.class, pk ); - assertThat( baseEntity.name, is( "tian" ) ); + var baseEntity = session.find( BaseEntity.class, pk ); + assertThat( baseEntity.name ).isEqualTo( "tian" ); } ); - } public static class Pk implements Serializable { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/IdGeneratorNameScopingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/IdGeneratorNameScopingTest.java index 17930aaeac97..9b22b4b870fb 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/IdGeneratorNameScopingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/IdGeneratorNameScopingTest.java @@ -18,12 +18,11 @@ import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.SessionFactory; import org.hibernate.testing.util.ServiceRegistryUtil; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; + /** * Tests for scoping of generator names @@ -48,11 +47,11 @@ public void testGlobalScoping() { // this will fail because both try { buildMetadata( true ); - fail(); + Assertions.fail(); } catch (Exception e) { - assertThat( e, instanceOf( IllegalArgumentException.class ) ); - assertThat( e.getMessage(), startsWith( "Duplicate generator name" ) ); + assertThat( e ).isInstanceOf( IllegalArgumentException.class ); + assertThat( e.getMessage() ).startsWith( "Duplicate generator name" ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/biginteger/increment/BigIntegerIncrementGeneratorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/biginteger/increment/BigIntegerIncrementGeneratorTest.java index 9079f61fcc5f..40695cab50cd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/biginteger/increment/BigIntegerIncrementGeneratorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/biginteger/increment/BigIntegerIncrementGeneratorTest.java @@ -4,23 +4,20 @@ */ package org.hibernate.orm.test.idgen.biginteger.increment; -import java.math.BigInteger; - - 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 java.math.BigInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; -@DomainModel( - xmlMappings = "org/hibernate/orm/test/idgen/biginteger/increment/Mapping.hbm.xml" -) +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(xmlMappings = "org/hibernate/orm/test/idgen/biginteger/increment/Mapping.hbm.xml") @SessionFactory public class BigIntegerIncrementGeneratorTest { - @Test public void testBasics(SessionFactoryScope scope) { scope.inTransaction( @@ -40,6 +37,6 @@ public void testBasics(SessionFactoryScope scope) { @AfterEach public void dropTestData(SessionFactoryScope scope) { - scope.getSessionFactory().getSchemaManager().truncate(); + scope.dropData(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/biginteger/sequence/BigIntegerSequenceGeneratorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/biginteger/sequence/BigIntegerSequenceGeneratorTest.java index ca926643efa0..6bdcb6d935e9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/biginteger/sequence/BigIntegerSequenceGeneratorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/biginteger/sequence/BigIntegerSequenceGeneratorTest.java @@ -16,9 +16,8 @@ /** * @author Steve Ebersole */ -@DomainModel( - xmlMappings = "org/hibernate/orm/test/idgen/biginteger/sequence/Mapping.hbm.xml" -) +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(xmlMappings = "org/hibernate/orm/test/idgen/biginteger/sequence/Mapping.hbm.xml") @SessionFactory @RequiresDialectFeature( feature = DialectFeatureChecks.SupportsSequences.class ) public class BigIntegerSequenceGeneratorTest { @@ -46,6 +45,6 @@ public void testBasics(SessionFactoryScope scope) { @AfterEach public void dropTestData(SessionFactoryScope scope) { - scope.getSessionFactory().getSchemaManager().truncate(); + scope.dropData(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/biginteger/sequence/BigIntegerSequenceGeneratorZeroScaleTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/biginteger/sequence/BigIntegerSequenceGeneratorZeroScaleTest.java index 9105605d49cf..7ad354bc2164 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/biginteger/sequence/BigIntegerSequenceGeneratorZeroScaleTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/biginteger/sequence/BigIntegerSequenceGeneratorZeroScaleTest.java @@ -20,9 +20,8 @@ * * @author Gail Badner */ -@DomainModel( - xmlMappings = "org/hibernate/orm/test/idgen/biginteger/sequence/ZeroScaleMapping.hbm.xml" -) +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(xmlMappings = "org/hibernate/orm/test/idgen/biginteger/sequence/ZeroScaleMapping.hbm.xml") @SessionFactory @RequiresDialectFeature( feature = DialectFeatureChecks.SupportsSequences.class ) public class BigIntegerSequenceGeneratorZeroScaleTest extends BigIntegerSequenceGeneratorTest { @@ -31,5 +30,4 @@ public class BigIntegerSequenceGeneratorZeroScaleTest extends BigIntegerSequence public void testBasics(SessionFactoryScope scope) { super.testBasics( scope ); } - } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/auto/AutoGenerationTypeTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/auto/AutoGenerationTypeTests.java index 9df0906c0c76..b7b093171047 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/auto/AutoGenerationTypeTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/auto/AutoGenerationTypeTests.java @@ -13,8 +13,6 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; -import org.hamcrest.MatcherAssert; - import org.hibernate.annotations.CollectionId; import org.hibernate.annotations.CollectionIdJdbcTypeCode; import org.hibernate.boot.Metadata; @@ -33,7 +31,6 @@ import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Property; import org.hibernate.orm.test.idgen.n_ative.GeneratorSettingsImpl; - import org.hibernate.testing.orm.junit.FailureExpectedExtension; import org.hibernate.testing.util.ServiceRegistryUtil; import org.junit.jupiter.api.Test; @@ -43,10 +40,8 @@ import java.util.Collection; import java.util.UUID; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.equalToIgnoringCase; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Steve Ebersole @@ -64,14 +59,12 @@ public void testAutoDefaults() { final PersistentClass entityBinding = metadata.getEntityBinding( Entity1.class.getName() ); final KeyValue idMapping = entityBinding.getRootClass().getIdentifier(); Dialect dialect = new H2Dialect(); - final Generator generator = idMapping.createGenerator( dialect, entityBinding.getRootClass()); - final SequenceStyleGenerator entityIdGenerator = (SequenceStyleGenerator) (generator instanceof IdentifierGenerator ? (IdentifierGenerator) generator : null); - - final DatabaseStructure database1Structure = entityIdGenerator.getDatabaseStructure(); + final SequenceStyleGenerator generator = (SequenceStyleGenerator) idMapping.createGenerator( dialect, entityBinding.getRootClass()); + final DatabaseStructure database1Structure = generator.getDatabaseStructure(); // implicit name : `${entity-name}_seq` - assertThat( database1Structure.getPhysicalName().render(), equalToIgnoringCase( "tbl_1_SEQ" ) ); - assertThat( database1Structure.getIncrementSize(), is( 50 ) ); + assertThat( database1Structure.getPhysicalName().render() ).isEqualToIgnoringCase( "tbl_1_SEQ" ); + assertThat( database1Structure.getIncrementSize() ).isEqualTo( 50 ); } } @@ -87,19 +80,17 @@ public void testAutoGeneratedValueGenerator() { final PersistentClass entityBinding = metadata.getEntityBinding( Entity2.class.getName() ); final KeyValue idMapping = entityBinding.getRootClass().getIdentifier(); Dialect dialect = new H2Dialect(); - final Generator generator = idMapping.createGenerator( + final SequenceStyleGenerator generator = (SequenceStyleGenerator) idMapping.createGenerator( dialect, entityBinding.getRootClass(), entityBinding.getIdentifierProperty(), new GeneratorSettingsImpl( metadata ) ); - final SequenceStyleGenerator idGenerator = (SequenceStyleGenerator) (generator instanceof IdentifierGenerator ? (IdentifierGenerator) generator : null); - - final DatabaseStructure database2Structure = idGenerator.getDatabaseStructure(); + final DatabaseStructure database2Structure = generator.getDatabaseStructure(); // GeneratedValue#generator value - assertThat( database2Structure.getPhysicalName().render(), equalToIgnoringCase( "id_seq" ) ); - assertThat( database2Structure.getIncrementSize(), is( 50 ) ); + assertThat( database2Structure.getPhysicalName().render() ).isEqualToIgnoringCase("id_seq" ); + assertThat( database2Structure.getIncrementSize() ).isEqualTo( 50 ); } } @@ -120,13 +111,11 @@ public void testCollectionId() { final IdentifierBag idBagMapping = (IdentifierBag) theTwos.getValue(); final KeyValue collectionIdMapping = idBagMapping.getIdentifier(); Dialect dialect = new H2Dialect(); - final Generator generator = collectionIdMapping.createGenerator( dialect, null); - final SequenceStyleGenerator collectionIdGenerator = (SequenceStyleGenerator) (generator instanceof IdentifierGenerator ? (IdentifierGenerator) generator : null); - - final DatabaseStructure idBagIdGeneratorDbStructure = collectionIdGenerator.getDatabaseStructure(); + final SequenceStyleGenerator generator = (SequenceStyleGenerator) collectionIdMapping.createGenerator( dialect, null); + final DatabaseStructure idBagIdGeneratorDbStructure = generator.getDatabaseStructure(); - assertThat( idBagIdGeneratorDbStructure.getPhysicalName().render(), equalToIgnoringCase( "tbl_2_seq" ) ); - assertThat( idBagIdGeneratorDbStructure.getIncrementSize(), is( 50 ) ); + assertThat( idBagIdGeneratorDbStructure.getPhysicalName().render() ).isEqualToIgnoringCase( "tbl_2_seq" ); + assertThat( idBagIdGeneratorDbStructure.getIncrementSize() ).isEqualTo( 50 ); } } @@ -142,7 +131,7 @@ public void testUuid() { final KeyValue idMapping = entityBinding.getRootClass().getIdentifier(); Dialect dialect = new H2Dialect(); final Generator generator = idMapping.createGenerator( dialect, entityBinding.getRootClass(), identifierProperty, null ); - MatcherAssert.assertThat( generator, instanceOf( UuidGenerator.class ) ); + assertThat( generator ).isInstanceOf( UuidGenerator.class ); } } @@ -156,10 +145,8 @@ public void testIncrement() { final PersistentClass entityBinding = metadata.getEntityBinding( Entity3.class.getName() ); final KeyValue idMapping = entityBinding.getRootClass().getIdentifier(); Dialect dialect = new H2Dialect(); - final Generator generator = idMapping.createGenerator( dialect, entityBinding.getRootClass()); - final IdentifierGenerator idGenerator = generator instanceof IdentifierGenerator ? (IdentifierGenerator) generator : null; - - assertThat( idGenerator, instanceOf( IncrementGenerator.class ) ); + final IdentifierGenerator generator = (IdentifierGenerator) idMapping.createGenerator( dialect, entityBinding.getRootClass()); + assertThat( generator ).isInstanceOf( IncrementGenerator.class ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/forcedtable/BasicForcedTableSequenceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/forcedtable/BasicForcedTableSequenceTest.java index 7ebbec42315f..ef95f1bd933e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/forcedtable/BasicForcedTableSequenceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/forcedtable/BasicForcedTableSequenceTest.java @@ -10,21 +10,17 @@ import org.hibernate.id.enhanced.SequenceStyleGenerator; import org.hibernate.id.enhanced.TableStructure; import org.hibernate.persister.entity.EntityPersister; - 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.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; -@DomainModel( - xmlMappings = "org/hibernate/orm/test/idgen/enhanced/forcedtable/Basic.hbm.xml" -) +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(xmlMappings = "org/hibernate/orm/test/idgen/enhanced/forcedtable/Basic.hbm.xml") @SessionFactory public class BasicForcedTableSequenceTest { @@ -33,31 +29,28 @@ public void testNormalBoundary(SessionFactoryScope scope) { final EntityPersister persister = scope.getSessionFactory() .getMappingMetamodel() .getEntityDescriptor(Entity.class.getName()); - assertThat( persister.getGenerator(), instanceOf( SequenceStyleGenerator.class ) ); - + assertThat( persister.getGenerator() ).isInstanceOf( SequenceStyleGenerator.class ); final SequenceStyleGenerator generator = (SequenceStyleGenerator) persister.getGenerator(); - assertThat( generator.getDatabaseStructure(), instanceOf( TableStructure.class ) ); - assertThat( generator.getOptimizer(), instanceOf( NoopOptimizer.class ) ); - - scope.inTransaction( - (session) -> { - int count = 5; - - for ( int i = 0; i < count; i++ ) { - final Entity entity = new Entity( "" + ( i + 1 ) ); - session.persist( entity ); - long expectedId = i + 1; - assertEquals( expectedId, entity.getId().longValue() ); - assertEquals( expectedId, generator.getDatabaseStructure().getTimesAccessed() ); - assertEquals( expectedId, ( (BasicHolder) generator.getOptimizer().getLastSourceValue() ).getActualLongValue() ); - } - } - ); + assertThat( generator.getDatabaseStructure() ).isInstanceOf( TableStructure.class ); + assertThat( generator.getOptimizer() ).isInstanceOf( NoopOptimizer.class ); + + scope.inTransaction( (session) -> { + int count = 5; + + for ( int i = 0; i < count; i++ ) { + final Entity entity = new Entity( "" + ( i + 1 ) ); + session.persist( entity ); + long expectedId = i + 1; + assertEquals( expectedId, entity.getId().longValue() ); + assertEquals( expectedId, generator.getDatabaseStructure().getTimesAccessed() ); + assertEquals( expectedId, ( (BasicHolder) generator.getOptimizer().getLastSourceValue() ).getActualLongValue() ); + } + } ); } @AfterEach public void dropTestData(SessionFactoryScope scope) { - scope.getSessionFactory().getSchemaManager().truncate(); + scope.dropData(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/forcedtable/HiLoForcedTableSequenceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/forcedtable/HiLoForcedTableSequenceTest.java index 3c32d8fccd7e..5a7d889a0858 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/forcedtable/HiLoForcedTableSequenceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/forcedtable/HiLoForcedTableSequenceTest.java @@ -9,20 +9,16 @@ import org.hibernate.id.enhanced.SequenceStyleGenerator; import org.hibernate.id.enhanced.TableStructure; import org.hibernate.persister.entity.EntityPersister; - 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.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; -@DomainModel( - xmlMappings = "org/hibernate/orm/test/idgen/enhanced/forcedtable/HiLo.hbm.xml" -) +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(xmlMappings = "org/hibernate/orm/test/idgen/enhanced/forcedtable/HiLo.hbm.xml") @SessionFactory public class HiLoForcedTableSequenceTest { @@ -31,44 +27,41 @@ public void testNormalBoundary(SessionFactoryScope scope) { final EntityPersister persister = scope.getSessionFactory() .getMappingMetamodel() .getEntityDescriptor(Entity.class.getName()); - assertThat( persister.getIdentifierGenerator(), instanceOf( SequenceStyleGenerator.class ) ); - - final SequenceStyleGenerator generator = (SequenceStyleGenerator) persister.getIdentifierGenerator(); - assertThat( generator.getDatabaseStructure(), instanceOf( TableStructure.class ) ); - assertThat( generator.getOptimizer(), instanceOf( HiLoOptimizer.class ) ); + assertThat( persister.getGenerator() ).isInstanceOf( SequenceStyleGenerator.class ); + final SequenceStyleGenerator generator = (SequenceStyleGenerator) persister.getGenerator(); + assertThat( generator.getDatabaseStructure() ).isInstanceOf( TableStructure.class ); + assertThat( generator.getOptimizer() ).isInstanceOf( HiLoOptimizer.class ); final HiLoOptimizer optimizer = (HiLoOptimizer) generator.getOptimizer(); int increment = optimizer.getIncrementSize(); - scope.inTransaction( - (s) -> { - for ( int i = 0; i < increment; i++ ) { - final Entity entity = new Entity( "" + ( i + 1 ) ); - s.persist( entity ); + scope.inTransaction( (s) -> { + for ( int i = 0; i < increment; i++ ) { + final Entity entity = new Entity( "" + ( i + 1 ) ); + s.persist( entity ); - long expectedId = i + 1; - assertThat( entity.getId().longValue(), is( expectedId ) ); - assertThat( ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue(), is( 1L ) ); - assertThat( ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue(), is( i + 1L ) ); - assertThat( ( (BasicHolder) optimizer.getHiValue() ).getActualLongValue(), is( increment + 1L ) ); - } + long expectedId = i + 1; + assertThat( entity.getId().longValue() ).isEqualTo( expectedId ); + assertThat( ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ).isEqualTo( 1L ); + assertThat( ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ).isEqualTo( i + 1L ); + assertThat( ( (BasicHolder) optimizer.getHiValue() ).getActualLongValue() ).isEqualTo( increment + 1L ); + } - // now force a "clock over" - final Entity entity = new Entity( "" + increment ); - s.persist( entity ); + // now force a "clock over" + final Entity entity = new Entity( "" + increment ); + s.persist( entity ); - long expectedId = optimizer.getIncrementSize() + 1; - assertThat( entity.getId().longValue(), is( expectedId ) ); - // initialization + clock-over - assertThat( ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue(), is( 2L ) ); - assertThat( ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue(), is( increment + 1L ) ); - assertThat( ( (BasicHolder) optimizer.getHiValue() ).getActualLongValue(), is( ( increment * 2L ) + 1L ) ); - } - ); + long expectedId = optimizer.getIncrementSize() + 1; + assertThat( entity.getId() ).isEqualTo( expectedId ); + // initialization + clock-over + assertThat( ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ).isEqualTo( 2L ); + assertThat( ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ).isEqualTo( increment + 1L ); + assertThat( ( (BasicHolder) optimizer.getHiValue() ).getActualLongValue() ).isEqualTo( ( increment * 2L ) + 1L ); + } ); } @AfterEach public void dropTestData(SessionFactoryScope scope) { - scope.getSessionFactory().getSchemaManager().truncate(); + scope.dropData(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/forcedtable/PooledForcedTableSequenceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/forcedtable/PooledForcedTableSequenceTest.java index 178693712363..79a62027a710 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/forcedtable/PooledForcedTableSequenceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/forcedtable/PooledForcedTableSequenceTest.java @@ -16,16 +16,13 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; -@DomainModel( - xmlMappings = "org/hibernate/orm/test/idgen/enhanced/forcedtable/Pooled.hbm.xml" -) +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(xmlMappings = "org/hibernate/orm/test/idgen/enhanced/forcedtable/Pooled.hbm.xml") @SessionFactory public class PooledForcedTableSequenceTest { - private static final long INITIAL_VALUE = 1; @Test @@ -33,54 +30,51 @@ public void testNormalBoundary(SessionFactoryScope scope) { EntityPersister persister = scope.getSessionFactory() .getMappingMetamodel() .getEntityDescriptor(Entity.class.getName()); - assertThat( persister.getIdentifierGenerator(), instanceOf( SequenceStyleGenerator.class ) ); - - final SequenceStyleGenerator generator = (SequenceStyleGenerator) persister.getIdentifierGenerator(); - assertThat( generator.getDatabaseStructure(), instanceOf( TableStructure.class ) ); - assertThat( generator.getOptimizer(), instanceOf( PooledOptimizer.class ) ); + assertThat( persister.getGenerator() ).isInstanceOf( SequenceStyleGenerator.class ); + final SequenceStyleGenerator generator = (SequenceStyleGenerator) persister.getGenerator(); + assertThat( generator.getDatabaseStructure() ).isInstanceOf( TableStructure.class ); + assertThat( generator.getOptimizer() ).isInstanceOf( PooledOptimizer.class ); final PooledOptimizer optimizer = (PooledOptimizer) generator.getOptimizer(); final int increment = optimizer.getIncrementSize(); - scope.inTransaction( - (s) -> { - // The value that we get from the callback is the high value (PooledOptimizer by default) - // When first increment is initialValue, we can only generate one id from it -> id 1 - Entity entity = new Entity( "" + INITIAL_VALUE ); - s.persist( entity ); + scope.inTransaction( (s) -> { + // The value that we get from the callback is the high value (PooledOptimizer by default) + // When first increment is initialValue, we can only generate one id from it -> id 1 + Entity entity = new Entity( "" + INITIAL_VALUE ); + s.persist( entity ); - long expectedId = INITIAL_VALUE; - assertEquals( expectedId, entity.getId().longValue() ); - assertEquals( 1, generator.getDatabaseStructure().getTimesAccessed() ); - assertEquals( INITIAL_VALUE, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); - assertEquals( INITIAL_VALUE, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ); - assertEquals( INITIAL_VALUE, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); + long expectedId = INITIAL_VALUE; + assertEquals( expectedId, entity.getId().longValue() ); + assertEquals( 1, generator.getDatabaseStructure().getTimesAccessed() ); + assertEquals( INITIAL_VALUE, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); + assertEquals( INITIAL_VALUE, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ); + assertEquals( INITIAL_VALUE, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); - // now start a full range of values, callback give us hiValue 11 - // id : 2,3,4...,11 - for ( int i = 1; i <= increment; i++ ) { - entity = new Entity( "" + ( i + INITIAL_VALUE ) ); - s.persist( entity ); + // now start a full range of values, callback give us hiValue 11 + // id : 2,3,4...,11 + for ( int i = 1; i <= increment; i++ ) { + entity = new Entity( "" + ( i + INITIAL_VALUE ) ); + s.persist( entity ); - expectedId = i + INITIAL_VALUE; - assertEquals( expectedId, entity.getId().longValue() ); - assertEquals( 2, generator.getDatabaseStructure().getTimesAccessed() ); - assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); - assertEquals( expectedId, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ); - assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); - } + expectedId = i + INITIAL_VALUE; + assertEquals( expectedId, entity.getId().longValue() ); + assertEquals( 2, generator.getDatabaseStructure().getTimesAccessed() ); + assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); + assertEquals( expectedId, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ); + assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); + } - // now force a "clock over" - expectedId++; - entity = new Entity( "" + expectedId ); - s.persist( entity ); + // now force a "clock over" + expectedId++; + entity = new Entity( "" + expectedId ); + s.persist( entity ); - assertEquals( expectedId, entity.getId().longValue() ); - assertEquals( 3, generator.getDatabaseStructure().getTimesAccessed() ); - assertEquals( increment * 2L + 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); - assertEquals( expectedId, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ); - } - ); + assertEquals( expectedId, entity.getId().longValue() ); + assertEquals( 3, generator.getDatabaseStructure().getTimesAccessed() ); + assertEquals( increment * 2L + 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); + assertEquals( expectedId, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ); + } ); } @AfterEach diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/BasicSequenceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/BasicSequenceTest.java index bf77c9de036c..ae3908f3c0d2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/BasicSequenceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/BasicSequenceTest.java @@ -7,29 +7,25 @@ import org.hibernate.id.IdentifierGeneratorHelper.BasicHolder; import org.hibernate.id.enhanced.SequenceStyleGenerator; import org.hibernate.persister.entity.EntityPersister; - -import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.orm.junit.SessionFactory; import org.hibernate.testing.orm.junit.SessionFactoryScope; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Steve Ebersole * @author Lukasz Antoniak */ -@DomainModel( - xmlMappings = { - "org/hibernate/orm/test/idgen/enhanced/sequence/Basic.hbm.xml", - "org/hibernate/orm/test/idgen/enhanced/sequence/Dedicated.hbm.xml" - } -) +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel( xmlMappings = { + "org/hibernate/orm/test/idgen/enhanced/sequence/Basic.hbm.xml", + "org/hibernate/orm/test/idgen/enhanced/sequence/Dedicated.hbm.xml" +}) @SessionFactory public class BasicSequenceTest { @@ -38,27 +34,25 @@ public void testNormalBoundary(SessionFactoryScope scope) { final EntityPersister persister = scope.getSessionFactory() .getMappingMetamodel() .getEntityDescriptor(Entity.class.getName()); - assertThat( persister.getGenerator(), instanceOf( SequenceStyleGenerator.class ) ); + assertThat( persister.getGenerator() ).isInstanceOf( SequenceStyleGenerator.class ); final SequenceStyleGenerator generator = (SequenceStyleGenerator) persister.getGenerator(); final int count = 5; - scope.inTransaction( - (s) -> { - for ( int i = 0; i < count; i++ ) { - final Entity entity = new Entity( "" + ( i + 1 ) ); - s.persist( entity ); + scope.inTransaction( (s) -> { + for ( int i = 0; i < count; i++ ) { + final Entity entity = new Entity( "" + ( i + 1 ) ); + s.persist( entity ); - long expectedId = i + 1; + long expectedId = i + 1; - assertEquals( expectedId, entity.getId().longValue() ); - assertEquals( expectedId, generator.getDatabaseStructure().getTimesAccessed() ); - assertEquals( expectedId, ( (BasicHolder) generator.getOptimizer() - .getLastSourceValue() ).getActualLongValue() ); - } - } - ); + assertEquals( expectedId, entity.getId().longValue() ); + assertEquals( expectedId, generator.getDatabaseStructure().getTimesAccessed() ); + assertEquals( expectedId, ( (BasicHolder) generator.getOptimizer() + .getLastSourceValue() ).getActualLongValue() ); + } + } ); } @Test @@ -69,27 +63,25 @@ public void testSequencePerEntity(SessionFactoryScope scope) { final EntityPersister persister = scope.getSessionFactory() .getMappingMetamodel() .getEntityDescriptor(overriddenEntityName); - assertThat( persister.getGenerator(), instanceOf( SequenceStyleGenerator.class ) ); + assertThat( persister.getGenerator() ).isInstanceOf( SequenceStyleGenerator.class ); final SequenceStyleGenerator generator = (SequenceStyleGenerator) persister.getGenerator(); assertEquals( "ID_SEQ_BSC_ENTITY" + SequenceStyleGenerator.DEF_SEQUENCE_SUFFIX, generator.getDatabaseStructure().getPhysicalName().render() ); - scope.inTransaction( - (s) -> { - Entity entity1 = new Entity( "1" ); - s.persist( overriddenEntityName, entity1 ); - Entity entity2 = new Entity( "2" ); - s.persist( overriddenEntityName, entity2 ); + scope.inTransaction( (s) -> { + Entity entity1 = new Entity( "1" ); + s.persist( overriddenEntityName, entity1 ); + Entity entity2 = new Entity( "2" ); + s.persist( overriddenEntityName, entity2 ); - assertEquals( 1, entity1.getId().intValue() ); - assertEquals( 2, entity2.getId().intValue() ); - } - ); + assertEquals( 1, entity1.getId().intValue() ); + assertEquals( 2, entity2.getId().intValue() ); + } ); } @AfterEach public void dropTestData(SessionFactoryScope scope) { - scope.getSessionFactory().getSchemaManager().truncate(); + scope.dropData(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/HiLoSequenceMismatchStrategyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/HiLoSequenceMismatchStrategyTest.java index d7402be933e2..04a55b198006 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/HiLoSequenceMismatchStrategyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/HiLoSequenceMismatchStrategyTest.java @@ -4,53 +4,44 @@ */ package org.hibernate.orm.test.idgen.enhanced.sequence; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; - import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; -import org.hibernate.cfg.AvailableSettings; import org.hibernate.dialect.Dialect; -import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; -import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess; import org.hibernate.id.enhanced.HiLoOptimizer; import org.hibernate.id.enhanced.Optimizer; import org.hibernate.id.enhanced.SequenceStyleGenerator; import org.hibernate.persister.entity.EntityPersister; - -import org.hibernate.testing.orm.junit.JiraKey; 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.Setting; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import java.sql.SQLException; +import java.sql.Statement; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.hibernate.cfg.MappingSettings.SEQUENCE_INCREMENT_SIZE_MISMATCH_STRATEGY; /** * @author Nathan Xu */ +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey(value = "HHH-13783") @RequiresDialectFeature( feature = DialectFeatureChecks.SupportsSequences.class ) -@ServiceRegistry( - settings = @Setting( name = AvailableSettings.SEQUENCE_INCREMENT_SIZE_MISMATCH_STRATEGY, value = "EXCEPTION" ) -) +@ServiceRegistry( settings = @Setting( name = SEQUENCE_INCREMENT_SIZE_MISMATCH_STRATEGY, value = "EXCEPTION" ) ) @DomainModel( annotatedClasses = HiLoSequenceMismatchStrategyTest.TestEntity.class ) @SessionFactory public class HiLoSequenceMismatchStrategyTest { - public final static String sequenceName = "ID_SEQ_HILO_SEQ"; @BeforeEach @@ -60,51 +51,31 @@ public void dropDatabaseSequence(SessionFactoryScope scope) { final String[] dropSequenceStatements = dialect.getSequenceSupport().getDropSequenceStrings( sequenceName ); final String[] createSequenceStatements = dialect.getSequenceSupport().getCreateSequenceStrings( sequenceName, 1, 1 ); - final ConnectionProvider connectionProvider = scope.getSessionFactory() - .getServiceRegistry() - .getService( ConnectionProvider.class ); - scope.inSession( - session -> { - Connection connection = null; - final JdbcConnectionAccess jdbcConnectionAccess = session.getJdbcConnectionAccess(); + scope.inSession(session -> session.doWork( connection -> { + try ( Statement statement = connection.createStatement() ) { + for ( String dropSequenceStatement : dropSequenceStatements ) { try { - connection = jdbcConnectionAccess.obtainConnection(); - try ( Statement statement = connection.createStatement() ) { - - for ( String dropSequenceStatement : dropSequenceStatements ) { - try { - statement.execute( dropSequenceStatement ); - } - catch (SQLException e) { - System.out.printf( "TEST DEBUG : dropping sequence failed [`%s`] - %s", dropSequenceStatement, e.getMessage() ); - System.out.println(); - e.printStackTrace( System.out ); - // ignore - } - } - // Commit in between because CockroachDB fails to drop and commit schema objects in the same transaction - connection.commit(); - - for ( String createSequenceStatement : createSequenceStatements ) { - statement.execute( createSequenceStatement ); - } - connection.commit(); - } + statement.execute( dropSequenceStatement ); } catch (SQLException e) { - fail( e.getMessage() ); - } - finally { - if ( connection != null ) { - try { - jdbcConnectionAccess.releaseConnection( connection ); - } - catch (SQLException ignore) { - } - } + System.out.printf( "TEST DEBUG : dropping sequence failed [`%s`] - %s", dropSequenceStatement, e.getMessage() ); + System.out.println(); + e.printStackTrace( System.out ); + // ignore } } - ); + // Commit in between because CockroachDB fails to drop and commit schema objects in the same transaction + connection.commit(); + + for ( String createSequenceStatement : createSequenceStatements ) { + statement.execute( createSequenceStatement ); + } + connection.commit(); + } + catch (SQLException e) { + Assertions.fail( e.getMessage() ); + } + } ) ); } @Test @@ -112,16 +83,12 @@ public void testSequenceMismatchStrategyNotApplied(SessionFactoryScope scope) { final EntityPersister persister = scope.getSessionFactory() .getMappingMetamodel() .getEntityDescriptor(TestEntity.class.getName()); - assertThat( persister.getIdentifierGenerator(), instanceOf( SequenceStyleGenerator.class ) ); - - final SequenceStyleGenerator generator = (SequenceStyleGenerator) persister.getIdentifierGenerator(); - - + assertThat( persister.getGenerator() ).isInstanceOf( SequenceStyleGenerator.class ); + final SequenceStyleGenerator generator = (SequenceStyleGenerator) persister.getGenerator(); final Optimizer optimizer = generator.getOptimizer(); - assertThat( optimizer, instanceOf( HiLoOptimizer.class ) ); - assertThat( optimizer.getIncrementSize(), not( is( 1 ) ) ); - - assertThat( generator.getDatabaseStructure().getPhysicalName().render(), is( sequenceName ) ); + assertThat( optimizer ).isInstanceOf( HiLoOptimizer.class ); + assertThat( optimizer.getIncrementSize() ).isNotEqualTo( 1 ); + assertThat( generator.getDatabaseStructure().getPhysicalName().render() ).isEqualTo( sequenceName ); } @Entity(name = "TestEntity") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/HiLoSequenceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/HiLoSequenceTest.java index 8150953cd8f8..866cb6d4277f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/HiLoSequenceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/HiLoSequenceTest.java @@ -16,13 +16,13 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Steve Ebersole */ +@SuppressWarnings("JUnitMalformedDeclaration") @DomainModel( xmlMappings = "org/hibernate/orm/test/idgen/enhanced/sequence/HiLo.hbm.xml" ) @SessionFactory public class HiLoSequenceTest { @@ -32,38 +32,33 @@ public void testNormalBoundary(SessionFactoryScope scope) { final EntityPersister persister = scope.getSessionFactory() .getMappingMetamodel() .getEntityDescriptor(Entity.class.getName()); - assertThat( persister.getIdentifierGenerator(), instanceOf( SequenceStyleGenerator.class ) ); - - final SequenceStyleGenerator generator = (SequenceStyleGenerator) persister.getIdentifierGenerator(); - assertThat( generator.getOptimizer(), instanceOf( HiLoOptimizer.class ) ); - + assertThat( persister.getGenerator() ).isInstanceOf( SequenceStyleGenerator.class ); + final SequenceStyleGenerator generator = (SequenceStyleGenerator) persister.getGenerator(); + assertThat( generator.getOptimizer() ).isInstanceOf( HiLoOptimizer.class ); final HiLoOptimizer optimizer = (HiLoOptimizer) generator.getOptimizer(); - final int increment = optimizer.getIncrementSize(); - scope.inTransaction( - (s) -> { - for ( int i = 0; i < increment; i++ ) { - final Entity entity = new Entity( "" + ( i + 1 ) ); - s.persist( entity ); + scope.inTransaction( (s) -> { + for ( int i = 0; i < increment; i++ ) { + final Entity entity = new Entity( "" + ( i + 1 ) ); + s.persist( entity ); - // initialization - assertEquals( 1, generator.getDatabaseStructure().getTimesAccessed() ); - // initialization - assertEquals( 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); - assertEquals( i + 1, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ); - assertEquals( increment + 1, ( (BasicHolder) optimizer.getHiValue() ).getActualLongValue() ); - } + // initialization + assertEquals( 1, generator.getDatabaseStructure().getTimesAccessed() ); + // initialization + assertEquals( 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); + assertEquals( i + 1, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ); + assertEquals( increment + 1, ( (BasicHolder) optimizer.getHiValue() ).getActualLongValue() ); + } - // now force a "clock over" - final Entity entity = new Entity( "" + increment ); - s.persist( entity ); - assertEquals( 2, generator.getDatabaseStructure().getTimesAccessed() ); // initialization - assertEquals( 2, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); // initialization - assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ); - assertEquals( ( increment * 2 ) + 1, ( (BasicHolder) optimizer.getHiValue() ).getActualLongValue() ); - } - ); + // now force a "clock over" + final Entity entity = new Entity( "" + increment ); + s.persist( entity ); + assertEquals( 2, generator.getDatabaseStructure().getTimesAccessed() ); // initialization + assertEquals( 2, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); // initialization + assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ); + assertEquals( ( increment * 2L ) + 1, ( (BasicHolder) optimizer.getHiValue() ).getActualLongValue() ); + } ); } @AfterEach diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/PooledSequenceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/PooledSequenceTest.java index 049ce176b269..ab6580fa84fb 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/PooledSequenceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/PooledSequenceTest.java @@ -14,18 +14,17 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; -import static org.hamcrest.Matchers.instanceOf; +import static org.assertj.core.api.Assertions.assertThat; import static org.hibernate.id.IdentifierGeneratorHelper.BasicHolder; -import static org.junit.Assert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Steve Ebersole */ +@SuppressWarnings("JUnitMalformedDeclaration") @DomainModel( xmlMappings = "org/hibernate/orm/test/idgen/enhanced/sequence/Pooled.hbm.xml" ) @SessionFactory public class PooledSequenceTest { - private static final long INITIAL_VALUE = 1; @Test @@ -33,57 +32,53 @@ public void testNormalBoundary(SessionFactoryScope scope) { final EntityPersister persister = scope.getSessionFactory() .getMappingMetamodel() .getEntityDescriptor(Entity.class.getName()); - assertThat( persister.getIdentifierGenerator(), instanceOf( SequenceStyleGenerator.class ) ); - - final SequenceStyleGenerator generator = ( SequenceStyleGenerator ) persister.getIdentifierGenerator(); - assertThat( generator.getOptimizer(), instanceOf( PooledOptimizer.class ) ); - + assertThat( persister.getGenerator() ).isInstanceOf( SequenceStyleGenerator.class ); + final SequenceStyleGenerator generator = ( SequenceStyleGenerator ) persister.getGenerator(); + assertThat( generator.getOptimizer() ).isInstanceOf( PooledOptimizer.class ); final PooledOptimizer optimizer = (PooledOptimizer) generator.getOptimizer(); final int increment = optimizer.getIncrementSize(); - scope.inTransaction( - (session) -> { - // The value that we get from the callback is the high value (PooledOptimizer by default) - // When first increment is initialValue, we can only generate one id from it -> id 1 - Entity entity = new Entity( "" + INITIAL_VALUE ); - session.persist( entity ); + scope.inTransaction( (session) -> { + // The value that we get from the callback is the high value (PooledOptimizer by default) + // When first increment is initialValue, we can only generate one id from it -> id 1 + Entity entity = new Entity( "" + INITIAL_VALUE ); + session.persist( entity ); - long expectedId = INITIAL_VALUE; - assertEquals( expectedId, entity.getId().longValue() ); - assertEquals( 1, generator.getDatabaseStructure().getTimesAccessed() ); - assertEquals( INITIAL_VALUE, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); - assertEquals( INITIAL_VALUE, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ); - assertEquals( INITIAL_VALUE, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); + long expectedId = INITIAL_VALUE; + assertEquals( expectedId, entity.getId().longValue() ); + assertEquals( 1, generator.getDatabaseStructure().getTimesAccessed() ); + assertEquals( INITIAL_VALUE, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); + assertEquals( INITIAL_VALUE, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ); + assertEquals( INITIAL_VALUE, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); - // now start a full range of values, callback give us hiValue 11 - // id : 2,3,4...,11 - for ( int i = 1; i <= increment; i++ ) { - entity = new Entity( "" + ( i + INITIAL_VALUE ) ); - session.persist( entity ); + // now start a full range of values, callback give us hiValue 11 + // id : 2,3,4...,11 + for ( int i = 1; i <= increment; i++ ) { + entity = new Entity( "" + ( i + INITIAL_VALUE ) ); + session.persist( entity ); - expectedId = i + INITIAL_VALUE; - assertEquals( expectedId, entity.getId().longValue() ); - assertEquals( 2, generator.getDatabaseStructure().getTimesAccessed() ); // initialization calls seq twice - assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); // initialization calls seq twice - assertEquals( expectedId, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ); - assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); - } + expectedId = i + INITIAL_VALUE; + assertEquals( expectedId, entity.getId().longValue() ); + assertEquals( 2, generator.getDatabaseStructure().getTimesAccessed() ); // initialization calls seq twice + assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); // initialization calls seq twice + assertEquals( expectedId, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ); + assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); + } - // now force a "clock over" - expectedId++; - entity = new Entity( "" + expectedId ); - session.persist( entity ); + // now force a "clock over" + expectedId++; + entity = new Entity( "" + expectedId ); + session.persist( entity ); - assertEquals( expectedId, entity.getId().longValue() ); - assertEquals( 3, generator.getDatabaseStructure().getTimesAccessed() ); - assertEquals( increment * 2L + 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); - assertEquals( expectedId, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ); - } - ); + assertEquals( expectedId, entity.getId().longValue() ); + assertEquals( 3, generator.getDatabaseStructure().getTimesAccessed() ); + assertEquals( increment * 2L + 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); + assertEquals( expectedId, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ); + } ); } @AfterEach public void cleanTestData(SessionFactoryScope scope) { - scope.getSessionFactory().getSchemaManager().truncate(); + scope.dropData(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/table/BasicTableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/table/BasicTableTest.java index 52f8c1bf3030..4ad6925c78b0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/table/BasicTableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/table/BasicTableTest.java @@ -6,18 +6,17 @@ import org.hibernate.id.enhanced.TableGenerator; import org.hibernate.persister.entity.EntityPersister; - 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.hamcrest.Matchers.instanceOf; +import static org.assertj.core.api.Assertions.assertThat; import static org.hibernate.id.IdentifierGeneratorHelper.BasicHolder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +@SuppressWarnings("JUnitMalformedDeclaration") @DomainModel( xmlMappings = "org/hibernate/orm/test/idgen/enhanced/table/Basic.hbm.xml" ) @SessionFactory public class BasicTableTest { @@ -27,27 +26,24 @@ public void testNormalBoundary(SessionFactoryScope scope) { final EntityPersister persister = scope.getSessionFactory() .getMappingMetamodel() .getEntityDescriptor(Entity.class.getName()); - assertThat( persister.getGenerator(), instanceOf( TableGenerator.class ) ); - + assertThat( persister.getGenerator() ).isInstanceOf( TableGenerator.class ); final TableGenerator generator = ( TableGenerator ) persister.getGenerator(); - scope.inTransaction( - (s) -> { - int count = 5; - for ( int i = 0; i < count; i++ ) { - final Entity entity = new Entity( "" + ( i + 1 ) ); - s.persist( entity ); - long expectedId = i + 1; - assertEquals( expectedId, entity.getId().longValue() ); - assertEquals( expectedId, generator.getTableAccessCount() ); - assertEquals( expectedId, ( (BasicHolder) generator.getOptimizer().getLastSourceValue() ).getActualLongValue() ); - } - } - ); + scope.inTransaction( (s) -> { + int count = 5; + for ( int i = 0; i < count; i++ ) { + final Entity entity = new Entity( "" + ( i + 1 ) ); + s.persist( entity ); + long expectedId = i + 1; + assertEquals( expectedId, entity.getId().longValue() ); + assertEquals( expectedId, generator.getTableAccessCount() ); + assertEquals( expectedId, ( (BasicHolder) generator.getOptimizer().getLastSourceValue() ).getActualLongValue() ); + } + } ); } @AfterEach public void cleanTestData(SessionFactoryScope scope) { - scope.getSessionFactory().getSchemaManager().truncate(); + scope.dropData(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/table/HiLoTableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/table/HiLoTableTest.java index 51d33913d416..af1ca73517c8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/table/HiLoTableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/table/HiLoTableTest.java @@ -14,11 +14,11 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; -import static org.hamcrest.Matchers.instanceOf; +import static org.assertj.core.api.Assertions.assertThat; import static org.hibernate.id.IdentifierGeneratorHelper.BasicHolder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +@SuppressWarnings("JUnitMalformedDeclaration") @DomainModel( xmlMappings = "org/hibernate/orm/test/idgen/enhanced/table/HiLo.hbm.xml" ) @SessionFactory public class HiLoTableTest { @@ -27,38 +27,34 @@ public void testNormalBoundary(SessionFactoryScope scope) { final EntityPersister persister = scope.getSessionFactory() .getMappingMetamodel() .getEntityDescriptor(Entity.class.getName()); - assertThat( persister.getIdentifierGenerator(), instanceOf( TableGenerator.class ) ); - - final TableGenerator generator = (TableGenerator) persister.getIdentifierGenerator(); - assertThat( generator.getOptimizer(), instanceOf( HiLoOptimizer.class ) ); - + assertThat( persister.getGenerator() ).isInstanceOf( TableGenerator.class ); + final TableGenerator generator = (TableGenerator) persister.getGenerator(); + assertThat( generator.getOptimizer() ).isInstanceOf( HiLoOptimizer.class ); final HiLoOptimizer optimizer = (HiLoOptimizer) generator.getOptimizer(); final int increment = optimizer.getIncrementSize(); - scope.inTransaction( - (s) -> { - for ( int i = 0; i < increment; i++ ) { - final Entity entity = new Entity( "" + ( i + 1 ) ); - s.persist( entity ); - assertEquals( 1, generator.getTableAccessCount() ); // initialization - assertEquals( 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); // initialization - assertEquals( i + 1, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ); - assertEquals( increment + 1, ( (BasicHolder) optimizer.getHiValue() ).getActualLongValue() ); - } - - // now force a "clock over" - final Entity entity = new Entity( "" + increment ); - s.persist( entity ); - assertEquals( 2, generator.getTableAccessCount() ); // initialization - assertEquals( 2, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); // initialization - assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ); - assertEquals( ( increment * 2 ) + 1, ( (BasicHolder) optimizer.getHiValue() ).getActualLongValue() ); - } - ); + scope.inTransaction( (s) -> { + for ( int i = 0; i < increment; i++ ) { + final Entity entity = new Entity( "" + ( i + 1 ) ); + s.persist( entity ); + assertEquals( 1, generator.getTableAccessCount() ); // initialization + assertEquals( 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); // initialization + assertEquals( i + 1, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ); + assertEquals( increment + 1, ( (BasicHolder) optimizer.getHiValue() ).getActualLongValue() ); + } + + // now force a "clock over" + final Entity entity = new Entity( "" + increment ); + s.persist( entity ); + assertEquals( 2, generator.getTableAccessCount() ); // initialization + assertEquals( 2, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); // initialization + assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ); + assertEquals( ( increment * 2L ) + 1, ( (BasicHolder) optimizer.getHiValue() ).getActualLongValue() ); + } ); } @AfterEach public void cleanTestData(SessionFactoryScope scope) { - scope.getSessionFactory().getSchemaManager().truncate(); + scope.dropData(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/table/PooledTableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/table/PooledTableTest.java index 8b2c29704b06..a290063b3eae 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/table/PooledTableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/table/PooledTableTest.java @@ -14,15 +14,14 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; -import static org.hamcrest.Matchers.instanceOf; +import static org.assertj.core.api.Assertions.assertThat; import static org.hibernate.id.IdentifierGeneratorHelper.BasicHolder; -import static org.junit.Assert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; +@SuppressWarnings("JUnitMalformedDeclaration") @DomainModel( xmlMappings = "org/hibernate/orm/test/idgen/enhanced/table/Pooled.hbm.xml" ) @SessionFactory public class PooledTableTest { - private static final long INITIAL_VALUE = 1; @Test @@ -30,57 +29,53 @@ public void testNormalBoundary(SessionFactoryScope scope) { final EntityPersister persister = scope.getSessionFactory() .getMappingMetamodel() .getEntityDescriptor(Entity.class.getName()); - assertThat( persister.getIdentifierGenerator(), instanceOf( TableGenerator.class ) ); - - final TableGenerator generator = (TableGenerator) persister.getIdentifierGenerator(); - assertThat( generator.getOptimizer(), instanceOf( PooledOptimizer.class ) ); - + assertThat( persister.getGenerator() ).isInstanceOf( TableGenerator.class ); + final TableGenerator generator = (TableGenerator) persister.getGenerator(); + assertThat( generator.getOptimizer() ).isInstanceOf( PooledOptimizer.class ); final PooledOptimizer optimizer = (PooledOptimizer) generator.getOptimizer(); final int increment = optimizer.getIncrementSize(); - scope.inTransaction( - (s) -> { - // The value that we get from the callback is the high value (PooledOptimizer by default) - // When first increment is initialValue, we can only generate one id from it -> id 1 - Entity entity = new Entity( "" + INITIAL_VALUE ); - s.persist( entity ); + scope.inTransaction( (s) -> { + // The value that we get from the callback is the high value (PooledOptimizer by default) + // When first increment is initialValue, we can only generate one id from it -> id 1 + Entity entity = new Entity( "" + INITIAL_VALUE ); + s.persist( entity ); - long expectedId = INITIAL_VALUE; - assertEquals( expectedId, entity.getId().longValue() ); - assertEquals( 1, generator.getTableAccessCount() ); - assertEquals( INITIAL_VALUE, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); - assertEquals( INITIAL_VALUE, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ); - assertEquals( INITIAL_VALUE, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); + long expectedId = INITIAL_VALUE; + assertEquals( expectedId, entity.getId().longValue() ); + assertEquals( 1, generator.getTableAccessCount() ); + assertEquals( INITIAL_VALUE, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); + assertEquals( INITIAL_VALUE, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ); + assertEquals( INITIAL_VALUE, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); - // now start a full range of values, callback give us hiValue 11 - // id : 2,3,4...,11 - for ( int i = 1; i <= increment; i++ ) { - entity = new Entity( "" + ( i + INITIAL_VALUE ) ); - s.persist( entity ); + // now start a full range of values, callback give us hiValue 11 + // id : 2,3,4...,11 + for ( int i = 1; i <= increment; i++ ) { + entity = new Entity( "" + ( i + INITIAL_VALUE ) ); + s.persist( entity ); - expectedId = i + INITIAL_VALUE; - assertEquals( expectedId, entity.getId().longValue() ); - assertEquals( 2, generator.getTableAccessCount() ); - assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); - assertEquals( expectedId, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ); - assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); - } + expectedId = i + INITIAL_VALUE; + assertEquals( expectedId, entity.getId().longValue() ); + assertEquals( 2, generator.getTableAccessCount() ); + assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); + assertEquals( expectedId, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ); + assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); + } - // now force a "clock over" - expectedId++; - entity = new Entity( "" + expectedId ); - s.persist( entity ); + // now force a "clock over" + expectedId++; + entity = new Entity( "" + expectedId ); + s.persist( entity ); - assertEquals( expectedId, entity.getId().longValue() ); - assertEquals( 3, generator.getTableAccessCount() ); - assertEquals( increment * 2L + 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); - assertEquals( expectedId, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ); - } - ); + assertEquals( expectedId, entity.getId().longValue() ); + assertEquals( 3, generator.getTableAccessCount() ); + assertEquals( increment * 2L + 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); + assertEquals( expectedId, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ); + } ); } @AfterEach public void cleanTestData(SessionFactoryScope scope) { - scope.getSessionFactory().getSchemaManager().truncate(); + scope.dropData(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/foreign/ForeignGeneratorResourceLocalTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/foreign/ForeignGeneratorResourceLocalTest.java index b1f38424a4e9..9218ee30caab 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/foreign/ForeignGeneratorResourceLocalTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/foreign/ForeignGeneratorResourceLocalTest.java @@ -29,6 +29,7 @@ import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.jboss.logging.Logger; @@ -36,32 +37,34 @@ /** * @author Vlad Mihalcea */ +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey(value = "HHH-12738") -@Jpa( - annotatedClasses = { - ForeignGeneratorResourceLocalTest.Contract.class, - ForeignGeneratorResourceLocalTest.Customer.class, - ForeignGeneratorResourceLocalTest.CustomerContractRelation.class - } -) +@Jpa( annotatedClasses = { + ForeignGeneratorResourceLocalTest.Contract.class, + ForeignGeneratorResourceLocalTest.Customer.class, + ForeignGeneratorResourceLocalTest.CustomerContractRelation.class +}) public class ForeignGeneratorResourceLocalTest { private static final Logger log = Logger.getLogger( ForeignGeneratorResourceLocalTest.class ); + @AfterEach + void dropTestData(EntityManagerFactoryScope factoryScope) { + factoryScope.dropData(); + } + @Test public void baseline(EntityManagerFactoryScope scope) { - scope.inTransaction( - (entityManager) -> { - final Contract contract = new Contract(); - entityManager.persist( contract ); + scope.inTransaction( (entityManager) -> { + final Contract contract = new Contract(); + entityManager.persist( contract ); - final Customer customer = new Customer(); - entityManager.persist( customer ); + final Customer customer = new Customer(); + entityManager.persist( customer ); - final CustomerContractRelation relation = new CustomerContractRelation(); - relation.setContractId( customer.getId() ); - customer.addContractRelation( relation ); - } - ); + final CustomerContractRelation relation = new CustomerContractRelation(); + relation.setContractId( customer.getId() ); + customer.addContractRelation( relation ); + } ); } @Test @@ -70,43 +73,35 @@ public void addRelationImplicitFlush(EntityManagerFactoryScope scope) { } private void doIt(EntityManagerFactoryScope scope, boolean explicitFlush) { - final Long contractId = scope.fromTransaction( - (entityManager) -> { - Contract contract = new Contract(); - - entityManager.persist( contract ); - return contract.getId(); - } - ); - - final Long customerId = scope.fromTransaction( - (entityManager) -> { - Customer customer = new Customer(); + final Long contractId = scope.fromTransaction( (entityManager) -> { + var contract = new Contract(); + entityManager.persist( contract ); + return contract.getId(); + } ); + + final Long customerId = scope.fromTransaction( (entityManager) -> { + var customer = new Customer(); + entityManager.persist( customer ); + return customer.getId(); + } ); + + scope.inTransaction( (entityManager) -> { + final String qry = "SELECT c " + + "FROM Customer c " + + " LEFT JOIN FETCH c.contractRelations " + + " WHERE c.id = :customerId"; + final Customer customer = entityManager.createQuery( qry, Customer.class ) + .setParameter( "customerId", customerId ) + .getSingleResult(); - entityManager.persist( customer ); - return customer.getId(); - } - ); + final CustomerContractRelation relation = new CustomerContractRelation(); + relation.setContractId( contractId ); + customer.addContractRelation( relation ); - scope.inTransaction( - (entityManager) -> { - final String qry = "SELECT c " + - "FROM Customer c " + - " LEFT JOIN FETCH c.contractRelations " + - " WHERE c.id = :customerId"; - final Customer customer = entityManager.createQuery( qry, Customer.class ) - .setParameter( "customerId", customerId ) - .getSingleResult(); - - final CustomerContractRelation relation = new CustomerContractRelation(); - relation.setContractId( contractId ); - customer.addContractRelation( relation ); - - if ( explicitFlush ) { - entityManager.flush(); - } - } - ); + if ( explicitFlush ) { + entityManager.flush(); + } + } ); } @Test diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/identity/IdentityInsertSoleColumnTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/identity/IdentityInsertSoleColumnTest.java index bafc4c28dbe8..40e9dcc8d794 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/identity/IdentityInsertSoleColumnTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/identity/IdentityInsertSoleColumnTest.java @@ -10,16 +10,19 @@ import jakarta.persistence.Id; import org.hibernate.dialect.HANADialect; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; -import org.hibernate.testing.SkipForDialect; +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.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 static org.assertj.core.api.Assertions.assertThat; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertNotNull; /** * The purpose of this test is to insure that when an entity that contains a single column @@ -32,31 +35,35 @@ * * @author Chris Cranford */ +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey(value = "HHH-13104") -@RequiresDialectFeature(DialectChecks.SupportsIdentityColumns.class) -@SkipForDialect(value=HANADialect.class, comment="SAP HANA requires at least value in insert value-list clause.") -public class IdentityInsertSoleColumnTest extends BaseEntityManagerFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Animal.class }; +@RequiresDialectFeature(feature= DialectFeatureChecks.SupportsIdentityColumns.class) +@SkipForDialect(dialectClass=HANADialect.class, + reason="SAP HANA requires at least value in insert value-list clause.") +@DomainModel(annotatedClasses = IdentityInsertSoleColumnTest.Animal.class) +@SessionFactory +public class IdentityInsertSoleColumnTest { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test - public void testEntityInsertWithSingleIdentityAttributeColumn() { + public void testEntityInsertWithSingleIdentityAttributeColumn(SessionFactoryScope factoryScope) { // insert the entity - final Integer entityId = doInJPA( this::entityManagerFactory, entityManager -> { - final Animal animal = new Animal(); + final Integer entityId = factoryScope.fromTransaction( (entityManager) -> { + var animal = new Animal(); entityManager.persist( animal ); return animal.getId(); } ); // make sure the identifier was generated - assertNotNull( entityId ); + assertThat( entityId ).isNotNull(); // verify the entity can be fetched - doInJPA( this::entityManagerFactory, entityManager -> { - final Animal animal = entityManager.find( Animal.class, entityId ); - assertNotNull( animal ); + factoryScope.inTransaction( (entityManager) -> { + var animal = entityManager.find( Animal.class, entityId ); + assertThat( animal ).isNotNull(); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/identity/hhh10429/IdentityGeneratorExtendsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/identity/hhh10429/IdentityGeneratorExtendsTest.java index 92623489a1c6..2df84de81856 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/identity/hhh10429/IdentityGeneratorExtendsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/identity/hhh10429/IdentityGeneratorExtendsTest.java @@ -10,33 +10,27 @@ import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.Table; - import org.hibernate.annotations.GenericGenerator; import org.hibernate.boot.spi.MetadataImplementor; -import org.hibernate.dialect.Dialect; -import org.hibernate.dialect.H2Dialect; import org.hibernate.mapping.KeyValue; import org.hibernate.mapping.PersistentClass; - -import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.DomainModelScope; +import org.hibernate.testing.orm.junit.JiraKey; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Matthew Morrissette */ +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey(value = "HHH-10429") @DomainModel( annotatedClasses = IdentityGeneratorExtendsTest.EntityBean.class ) public class IdentityGeneratorExtendsTest { @Test public void testIdentifierGeneratorExtendsIdentityGenerator(DomainModelScope scope) { - // the Dialect is irrelevant here.. we just need a Dialect that supports IDENTITY - final Dialect dialect = new H2Dialect(); - final MetadataImplementor domainModel = scope.getDomainModel(); final PersistentClass entityBinding = domainModel.getEntityBinding( EntityBean.class.getName() ); final KeyValue identifier = entityBinding.getIdentifier(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/identity/hhh9983/SaveEntityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/identity/hhh9983/SaveEntityTest.java index 4926e936909b..7c64cb40f877 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/identity/hhh9983/SaveEntityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/identity/hhh9983/SaveEntityTest.java @@ -25,6 +25,7 @@ /** * @author Andrea Boriero */ +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey(value = "HHH-9983") @RequiresDialect( OracleDialect.class ) @RequiresDialectFeature( feature = DialectFeatureChecks.SupportsIdentityColumns.class ) @@ -33,11 +34,9 @@ public class SaveEntityTest { @Test public void testSave(SessionFactoryScope scope) { - scope.inTransaction( - (s) -> { - s.persist( new Company() ); - } - ); + scope.inTransaction( (s) -> { + s.persist( new Company() ); + } ); } @Entity diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/identity/joinedSubClass/JoinedSubclassHierarchyWithIdentityGenerationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/identity/joinedSubClass/JoinedSubclassHierarchyWithIdentityGenerationTest.java index edd2d682d95e..cdd82c7b5b8a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/identity/joinedSubClass/JoinedSubclassHierarchyWithIdentityGenerationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/identity/joinedSubClass/JoinedSubclassHierarchyWithIdentityGenerationTest.java @@ -17,21 +17,20 @@ * @author Andrey Vlasov * @author Steve Ebersole */ +@SuppressWarnings("JUnitMalformedDeclaration") @RequiresDialectFeature( feature = DialectFeatureChecks.SupportsIdentityColumns.class ) @DomainModel( annotatedClasses = Sub.class ) @SessionFactory public class JoinedSubclassHierarchyWithIdentityGenerationTest { @Test public void shouldPersistDebtorAccountWhenParentServiceAgreementPersisted(SessionFactoryScope scope) { - scope.inTransaction( - (s) -> { - s.persist( new Sub() ); - } - ); + scope.inTransaction( (s) -> { + s.persist( new Sub() ); + } ); } @AfterEach public void cleanTestData(SessionFactoryScope scope) { - scope.getSessionFactory().getSchemaManager().truncate(); + scope.dropData(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/n_ative/local/NativeGeneratorClassTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/n_ative/local/NativeGeneratorClassTest.java index 68ff7e8e118a..4ecaa6175dc3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/n_ative/local/NativeGeneratorClassTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/n_ative/local/NativeGeneratorClassTest.java @@ -16,6 +16,7 @@ import org.hibernate.testing.orm.junit.DomainModelScope; 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.Entity; @@ -24,10 +25,17 @@ import static org.assertj.core.api.Assertions.assertThat; +@SuppressWarnings("JUnitMalformedDeclaration") @SessionFactory @DomainModel(annotatedClasses = NativeGeneratorClassTest.NativeEntity.class) public class NativeGeneratorClassTest { - @Test void test(DomainModelScope domainModelScope, SessionFactoryScope scope) { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); + } + + @Test + void test(DomainModelScope domainModelScope, SessionFactoryScope scope) { scope.inTransaction(s -> s.persist(new NativeEntity())); final PersistentClass entityBinding = domainModelScope.getEntityBinding( NativeEntity.class ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/n_ative/local/NativeGeneratorMemberTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/n_ative/local/NativeGeneratorMemberTest.java index 19f0176b2a98..64c7a943daeb 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/n_ative/local/NativeGeneratorMemberTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/n_ative/local/NativeGeneratorMemberTest.java @@ -16,6 +16,7 @@ import org.hibernate.testing.orm.junit.DomainModelScope; 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.Entity; @@ -24,9 +25,15 @@ import static org.assertj.core.api.Assertions.assertThat; +@SuppressWarnings("JUnitMalformedDeclaration") @SessionFactory @DomainModel(annotatedClasses = NativeGeneratorMemberTest.NativeEntity.class) public class NativeGeneratorMemberTest { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); + } + @Test void test(DomainModelScope domainModelScope, SessionFactoryScope scope) { scope.inTransaction(s -> s.persist(new NativeEntity())); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/n_ative/pkg/NativeGeneratorPackageTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/n_ative/pkg/NativeGeneratorPackageTest.java index 5370b618abe9..bbfa18b49ac3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/n_ative/pkg/NativeGeneratorPackageTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/n_ative/pkg/NativeGeneratorPackageTest.java @@ -16,6 +16,7 @@ import org.hibernate.testing.orm.junit.DomainModelScope; 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.Entity; @@ -24,10 +25,17 @@ import static org.assertj.core.api.Assertions.assertThat; +@SuppressWarnings("JUnitMalformedDeclaration") @SessionFactory @DomainModel(annotatedClasses = NativeGeneratorPackageTest.NativeEntity.class) public class NativeGeneratorPackageTest { - @Test void test(DomainModelScope domainModelScope, SessionFactoryScope scope) { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); + } + + @Test + void test(DomainModelScope domainModelScope, SessionFactoryScope scope) { scope.inTransaction(s -> s.persist(new NativeEntity())); final PersistentClass entityBinding = domainModelScope.getEntityBinding( NativeEntity.class ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/BeforeExecutionAssignedValuesTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/BeforeExecutionAssignedValuesTest.java index 04f95fd62585..d040a8029f8c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/BeforeExecutionAssignedValuesTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/BeforeExecutionAssignedValuesTest.java @@ -32,6 +32,7 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; import static org.assertj.core.api.Assertions.assertThat; +@SuppressWarnings("JUnitMalformedDeclaration") @SessionFactory @DomainModel(annotatedClasses = { BeforeExecutionAssignedValuesTest.EntityWithGeneratedId.class, @@ -114,8 +115,8 @@ void testGeneratedPropertyAndUpdate(SessionFactoryScope scope) { } @AfterAll - public void tearDown(SessionFactoryScope scope) { - scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); + public void dropTestData(SessionFactoryScope scope) { + scope.dropData(); } @Entity(name = "EntityWithGeneratedId") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/ExportableValueGeneratorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/ExportableValueGeneratorTest.java index 5deee3c36eee..3752d0a792b3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/ExportableValueGeneratorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/ExportableValueGeneratorTest.java @@ -22,6 +22,7 @@ import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; import org.hibernate.testing.orm.junit.Jpa; import org.hibernate.testing.orm.junit.SkipForDialect; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import java.lang.annotation.Retention; @@ -31,12 +32,18 @@ import static org.junit.jupiter.api.Assertions.assertEquals; +@SuppressWarnings("JUnitMalformedDeclaration") @Jpa(annotatedClasses = ExportableValueGeneratorTest.WithExportableGenerator.class) @SkipForDialect( dialectClass = SybaseASEDialect.class ) @SkipForDialect( dialectClass = MySQLDialect.class) public class ExportableValueGeneratorTest { + @AfterEach + void dropTestData(EntityManagerFactoryScope factoryScope) { + factoryScope.dropData(); + } - @Test void test(EntityManagerFactoryScope scope) { + @Test + void test(EntityManagerFactoryScope scope) { final EntityManagerFactory entityManagerFactory = scope.getEntityManagerFactory(); final WithExportableGenerator first = new WithExportableGenerator(); entityManagerFactory.runInTransaction( entityManager -> entityManager.persist( first ) ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/IdGeneratorTypeWithBeanContainerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/IdGeneratorTypeWithBeanContainerTest.java index 867355b57d13..3b61b35d9bc3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/IdGeneratorTypeWithBeanContainerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/IdGeneratorTypeWithBeanContainerTest.java @@ -12,6 +12,7 @@ import org.hibernate.testing.orm.junit.SessionFactory; import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import jakarta.persistence.Entity; @@ -23,6 +24,7 @@ /** * @author Yanming Zhou */ +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey( "HHH-18164" ) @SessionFactory @ServiceRegistry( @@ -34,6 +36,11 @@ @DomainModel(annotatedClasses = IdGeneratorTypeWithBeanContainerTest.SimpleEntity.class) public class IdGeneratorTypeWithBeanContainerTest { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); + } + @Test void test(SessionFactoryScope scope) { SimpleEntity entity = new SimpleEntity(); scope.inTransaction(s -> s.persist(entity)); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/MixedTimingGeneratorsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/MixedTimingGeneratorsTest.java index 8622002e5394..c7cebb1e130c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/MixedTimingGeneratorsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/MixedTimingGeneratorsTest.java @@ -35,6 +35,7 @@ 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 jakarta.persistence.Entity; @@ -50,6 +51,7 @@ /** * @author Marco Belladelli */ +@SuppressWarnings("JUnitMalformedDeclaration") @DomainModel( annotatedClasses = { MixedTimingGeneratorsTest.AssignedEntity.class, MixedTimingGeneratorsTest.RandomEntity.class, @@ -59,6 +61,11 @@ @RequiresDialectFeature( feature = DialectFeatureChecks.SupportsIdentityColumns.class ) @Jira( "https://hibernate.atlassian.net/browse/HHH-17322" ) public class MixedTimingGeneratorsTest { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); + } + @Test @SkipForDialect( dialectClass = SQLServerDialect.class, reason = "SQLServer does not support setting explicit values for identity columns" ) @SkipForDialect( dialectClass = OracleDialect.class, reason = "Oracle does not support setting explicit values for identity columns" ) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/SequenceOrAssignedGeneratorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/SequenceOrAssignedGeneratorTest.java index 26ec4d970816..2b5edc5fff59 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/SequenceOrAssignedGeneratorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/SequenceOrAssignedGeneratorTest.java @@ -35,6 +35,7 @@ /** * @author Marco Belladelli */ +@SuppressWarnings("JUnitMalformedDeclaration") @DomainModel( annotatedClasses = { SequenceOrAssignedGeneratorTest.MyEntity.class, SequenceOrAssignedGeneratorTest.MyVersionedEntity.class, @@ -43,10 +44,7 @@ public class SequenceOrAssignedGeneratorTest { @AfterAll public void tearDown(SessionFactoryScope scope) { - scope.inTransaction( session -> { - session.createMutationQuery( "delete from MyEntity" ).executeUpdate(); - session.createMutationQuery( "delete from MyVersionedEntity" ).executeUpdate(); - } ); + scope.dropData(); } @Test diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateTableBackedSequenceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateTableBackedSequenceTest.java index b4c5180d2e74..a72332a9322c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateTableBackedSequenceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateTableBackedSequenceTest.java @@ -4,23 +4,17 @@ */ package org.hibernate.orm.test.schemaupdate; -import java.util.Collections; -import java.util.EnumSet; -import java.util.Map; - -import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.model.naming.Identifier; -import org.hibernate.boot.model.relational.Database; import org.hibernate.boot.model.relational.QualifiedTableName; import org.hibernate.boot.model.relational.SqlStringGenerationContext; import org.hibernate.boot.model.relational.internal.SqlStringGenerationContextImpl; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.AvailableSettings; import org.hibernate.engine.config.spi.ConfigurationService; import org.hibernate.id.enhanced.TableStructure; import org.hibernate.mapping.Table; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.ServiceRegistryScope; +import org.hibernate.testing.orm.junit.Setting; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.schema.TargetType; import org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl; @@ -30,41 +24,28 @@ import org.hibernate.tool.schema.spi.SchemaManagementTool; import org.hibernate.tool.schema.spi.ScriptTargetOutput; import org.hibernate.tool.schema.spi.TargetDescriptor; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; -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 java.util.Collections; +import java.util.EnumSet; +import java.util.Map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.hibernate.cfg.JdbcSettings.FORMAT_SQL; /** * @author Steve Ebersole */ -public class SchemaUpdateTableBackedSequenceTest extends BaseUnitTestCase { - private StandardServiceRegistry ssr; - - @Before - public void before() { - ssr = ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( AvailableSettings.FORMAT_SQL, false ) - .build(); - } - - @After - public void after() { - StandardServiceRegistryBuilder.destroy( ssr ); - } - +@SuppressWarnings("JUnitMalformedDeclaration") +@ServiceRegistry(settings = @Setting(name = FORMAT_SQL, value = "false")) +public class SchemaUpdateTableBackedSequenceTest { @Test - public void testCreateTableOnUpdate() { - Metadata metadata = new MetadataSources( ssr ).buildMetadata(); + public void testCreateTableOnUpdate(ServiceRegistryScope registryScope) { + final var registry = registryScope.getRegistry(); - Database database = metadata.getDatabase(); - - TableStructure tableStructure = new TableStructure( + final var metadata = new MetadataSources( registry ).buildMetadata(); + final var database = metadata.getDatabase(); + final var tableStructure = new TableStructure( "orm", new QualifiedTableName( null, null, Identifier.toIdentifier( "test_seq" ) ), Identifier.toIdentifier( "nextval" ), @@ -75,14 +56,15 @@ public void testCreateTableOnUpdate() { tableStructure.registerExportables( database ); // let's make sure the InitCommand is there - assertEquals( 1, database.getDefaultNamespace().getTables().size() ); + Assertions.assertEquals( 1, database.getDefaultNamespace().getTables().size() ); Table table = database.getDefaultNamespace().getTables().iterator().next(); SqlStringGenerationContext context = SqlStringGenerationContextImpl.forTests( database.getJdbcEnvironment(), null, null ); - assertEquals( 1, table.getInitCommands( context ).size() ); + Assertions.assertEquals( 1, table.getInitCommands( context ).size() ); final TargetImpl target = new TargetImpl(); - ssr.getService( SchemaManagementTool.class ).getSchemaMigrator( Collections.emptyMap() ).doMigration( + final var migrator = registry.requireService( SchemaManagementTool.class ).getSchemaMigrator( Collections.emptyMap() ); + migrator.doMigration( metadata, new ExecutionOptions() { @Override @@ -92,7 +74,7 @@ public boolean shouldManageNamespaces() { @Override public Map getConfigurationValues() { - return ssr.requireService( ConfigurationService.class ).getSettings(); + return registry.requireService( ConfigurationService.class ).getSettings(); } @Override @@ -114,17 +96,16 @@ public ScriptTargetOutput getScriptTargetOutput() { } ); - assertTrue( target.found ); + Assertions.assertTrue( target.found ); new SchemaExport().drop( EnumSet.of( TargetType.DATABASE ), metadata ); } - class TargetImpl implements ScriptTargetOutput { + static class TargetImpl implements ScriptTargetOutput { boolean found = false; @Override public void prepare() { - } @Override @@ -136,7 +117,6 @@ public void accept(String action) { @Override public void release() { - } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/ternary/Employee.java b/hibernate-core/src/test/java/org/hibernate/orm/test/ternary/Employee.java index 032a42944e7d..b7fd6bbc679b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/ternary/Employee.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/ternary/Employee.java @@ -15,17 +15,17 @@ public class Employee { private String name; private Date hireDate; - private Map managerBySite = new HashMap(); - private Set underlings = new HashSet(); + private Map managerBySite = new HashMap<>(); + private Set underlings = new HashSet<>(); Employee() {} public Employee(String name) { this.name=name; } - public Map getManagerBySite() { + public Map getManagerBySite() { return managerBySite; } - public void setManagerBySite(Map managerBySite) { + public void setManagerBySite(Map managerBySite) { this.managerBySite = managerBySite; } public String getName() { @@ -34,10 +34,10 @@ public String getName() { public void setName(String name) { this.name = name; } - public Set getUnderlings() { + public Set getUnderlings() { return underlings; } - public void setUnderlings(Set underlings) { + public void setUnderlings(Set underlings) { this.underlings = underlings; } public Date getHireDate() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/ternary/TernaryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/ternary/TernaryTest.java index df8f0926cce5..b0628da8cc66 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/ternary/TernaryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/ternary/TernaryTest.java @@ -4,7 +4,6 @@ */ package org.hibernate.orm.test.ternary; -import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; @@ -12,14 +11,16 @@ import java.util.Set; import org.hibernate.Hibernate; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import static org.hibernate.cfg.CacheSettings.USE_SECOND_LEVEL_CACHE; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; @@ -28,107 +29,96 @@ /** * @author Gavin King */ -public class TernaryTest extends BaseCoreFunctionalTestCase { - @Override - public String[] getMappings() { - return new String[] { "ternary/Ternary.hbm.xml" }; - } - - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - configuration.setProperty( AvailableSettings.USE_SECOND_LEVEL_CACHE, false ); +@SuppressWarnings("JUnitMalformedDeclaration") +@ServiceRegistry(settings = @Setting(name = USE_SECOND_LEVEL_CACHE, value = "false")) +@DomainModel(xmlMappings = "mappings/map/Ternary.hbm.xml") +@SessionFactory +public class TernaryTest { + @AfterEach + public void dropTestData(SessionFactoryScope factoryScope) throws Exception { + factoryScope.dropData(); } @Test - public void testTernary() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Employee bob = new Employee("Bob"); - Employee tom = new Employee("Tom"); - Employee jim = new Employee("Jim"); - Employee tim = new Employee("Tim"); - Site melb = new Site("Melbourne"); - Site geel = new Site("Geelong"); - s.persist(bob); - s.persist(tom); - s.persist(jim); - s.persist(tim); - s.persist(melb); - s.persist(geel); - bob.getManagerBySite().put(melb, tom); - bob.getManagerBySite().put(geel, jim); - tim.getManagerBySite().put(melb, tom); - t.commit(); - s.close(); + public void testTernary(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + var bob = new Employee("Bob"); + var tom = new Employee("Tom"); + var jim = new Employee("Jim"); + var tim = new Employee("Tim"); + var melb = new Site("Melbourne"); + var geel = new Site("Geelong"); + session.persist(bob); + session.persist(tom); + session.persist(jim); + session.persist(tim); + session.persist(melb); + session.persist(geel); + bob.getManagerBySite().put(melb, tom); + bob.getManagerBySite().put(geel, jim); + tim.getManagerBySite().put(melb, tom); + } ); + + factoryScope.inTransaction( (session) -> { + var tom = session.find( Employee.class, "Tom" ); + assertFalse( Hibernate.isInitialized(tom.getUnderlings()) ); + assertEquals( 2, tom.getUnderlings().size() ); + + var bob = session.find( Employee.class, "Bob" ); + assertFalse( Hibernate.isInitialized(bob.getManagerBySite()) ); + assertTrue( tom.getUnderlings().contains(bob) ); - s = openSession(); - t = s.beginTransaction(); - tom = (Employee) s.get(Employee.class, "Tom"); - assertFalse( Hibernate.isInitialized(tom.getUnderlings()) ); - assertEquals( tom.getUnderlings().size(), 2 ); - bob = (Employee) s.get(Employee.class, "Bob"); - assertFalse( Hibernate.isInitialized(bob.getManagerBySite()) ); - assertTrue( tom.getUnderlings().contains(bob) ); - melb = (Site) s.get(Site.class, "Melbourne"); - assertSame( bob.getManagerBySite().get(melb), tom ); - assertTrue( melb.getEmployees().contains(bob) ); - assertTrue( melb.getManagers().contains(tom) ); - t.commit(); - s.close(); + var melb = session.find( Site.class, "Melbourne" ); + assertSame( bob.getManagerBySite().get(melb), tom ); + assertTrue( melb.getEmployees().contains(bob) ); + assertTrue( melb.getManagers().contains(tom) ); - s = openSession(); - t = s.beginTransaction(); - List l = s.createQuery("from Employee e join e.managerBySite m where m.name='Bob'", Object[].class).list(); - assertEquals( l.size(), 0 ); - l = s.createQuery("from Employee e join e.managerBySite m where m.name='Tom'", Object[].class).list(); - assertEquals( l.size(), 2 ); - t.commit(); - s.close(); + } ); - s = openSession(); - t = s.beginTransaction(); - l = s.createQuery("from Employee e left join fetch e.managerBySite").list(); - assertEquals( l.size(), 4 ); - Set set = new HashSet(l); - assertEquals( set.size(), 4 ); - Iterator iter = set.iterator(); - int total=0; - while ( iter.hasNext() ) { - Map map = ( (Employee) iter.next() ).getManagerBySite(); - assertTrue( Hibernate.isInitialized(map) ); - total += map.size(); - } - assertTrue(total==3); + factoryScope.inTransaction( (session) -> { + var qry = """ + from Employee e + join e.managerBySite m + where m.name='Bob' + """; + List l = session.createQuery( qry, Object[].class).list(); + assertEquals( 0, l.size() ); - l = s.createQuery("from Employee e left join e.managerBySite m left join m.managerBySite m2", Object[].class).list(); + qry = """ + from Employee e + join e.managerBySite m + where m.name='Tom' + """; + l = session.createQuery(qry, Object[].class).list(); + assertEquals( 2, l.size() ); + } ); - // clean up... - l = s.createQuery("from Employee e left join fetch e.managerBySite").list(); - Iterator itr = l.iterator(); - while ( itr.hasNext() ) { - Employee emp = ( Employee ) itr.next(); - emp.setManagerBySite( new HashMap() ); - s.remove( emp ); - } - for ( Object entity : s.createQuery( "from Site" ).list() ) { - s.remove( entity ); - } - t.commit(); - s.close(); + factoryScope.inTransaction( (session) -> { + var qry = "from Employee e left join fetch e.managerBySite"; + List l = session.createQuery( qry, Employee.class ).list(); + assertEquals( 4, l.size() ); + Set set = new HashSet<>(l); + assertEquals( 4, set.size() ); + Iterator iter = set.iterator(); + int total=0; + while ( iter.hasNext() ) { + Map map = iter.next().getManagerBySite(); + assertTrue( Hibernate.isInitialized(map) ); + total += map.size(); + } + assertEquals( 3, total ); + } ); } @Test - public void testIndexRelatedFunctions() { - Session session = openSession(); - session.beginTransaction(); - session.createQuery( "from Employee e join e.managerBySite as m where index(m) is not null", Object[].class ) - .list(); - session.createQuery( "from Employee e where minIndex(e.managerBySite) is not null" ) - .list(); - session.createQuery( "from Employee e where maxIndex(e.managerBySite) is not null" ) - .list(); - session.getTransaction().commit(); - session.close(); + public void testIndexRelatedFunctions(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + session.createQuery( "from Employee e join e.managerBySite as m where index(m) is not null", Object[].class ) + .list(); + session.createQuery( "from Employee e where minIndex(e.managerBySite) is not null" ) + .list(); + session.createQuery( "from Employee e where maxIndex(e.managerBySite) is not null" ) + .list(); + } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/util/BytesHelperTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/util/BytesHelperTest.java index b31232c815b4..e1f908c45ab8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/util/BytesHelperTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/util/BytesHelperTest.java @@ -4,24 +4,27 @@ */ package org.hibernate.orm.test.util; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - import org.hibernate.internal.util.BytesHelper; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.BaseUnitTest; +import org.hibernate.testing.orm.junit.ExpectedException; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Benoit W */ -public class BytesHelperTest extends BaseUnitTestCase { +@BaseUnitTest +public class BytesHelperTest { @Test public void testAsLongNullArray() { assertEquals(0, BytesHelper.asLong(null, 0)); } - @Test(expected=IllegalArgumentException.class) + @Test() + @ExpectedException(IllegalArgumentException.class) public void testAsLongArrayTooSmall() { byte[] src = new byte[16]; assertEquals(0, BytesHelper.asLong(src, 9)); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/util/PropertiesHelperTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/util/PropertiesHelperTest.java index 7547a38be8fc..36780f6c6c05 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/util/PropertiesHelperTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/util/PropertiesHelperTest.java @@ -3,28 +3,29 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.util; -import java.util.Properties; - -import org.junit.Before; -import org.junit.Test; import org.hibernate.internal.util.config.ConfigurationHelper; -import org.hibernate.testing.junit4.BaseUnitTestCase; +import org.hibernate.testing.orm.junit.BaseUnitTest; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Properties; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -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.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Steve Ebersole */ -public class PropertiesHelperTest extends BaseUnitTestCase { +@BaseUnitTest +public class PropertiesHelperTest { private Properties props; - @Before - public void setUp() throws Exception { + @BeforeEach + public void setUp() { props = new Properties(); props.setProperty( "my.nonexistent.prop", "${}" ); @@ -58,20 +59,20 @@ public void testPlaceholderReplacement() { str = ConfigurationHelper.getString( "my.nonexistent.prop", props ); assertNull( str ); str = ConfigurationHelper.getString( "my.string.prop", props, "na" ); - assertEquals( "replacement did not occur", "string", str ); + assertEquals( "string", str, "replacement did not occur" ); str = ConfigurationHelper.getString( "my.string.prop", props, "did.not.exist" ); - assertEquals( "replacement did not occur", "string", str ); + assertEquals( "string", str, "replacement did not occur" ); boolean bool = ConfigurationHelper.getBoolean( "my.nonexistent.prop", props ); - assertFalse( "non-exists as boolean", bool ); + assertFalse( bool, "non-exists as boolean" ); bool = ConfigurationHelper.getBoolean( "my.nonexistent.prop", props, false ); - assertFalse( "non-exists as boolean", bool ); + assertFalse( bool, "non-exists as boolean" ); bool = ConfigurationHelper.getBoolean( "my.nonexistent.prop", props, true ); - assertTrue( "non-exists as boolean", bool ); + assertTrue( bool, "non-exists as boolean" ); bool = ConfigurationHelper.getBoolean( "my.boolean.prop", props ); - assertTrue( "boolean replacement did not occur", bool ); + assertTrue( bool, "boolean replacement did not occur" ); bool = ConfigurationHelper.getBoolean( "my.boolean.prop", props, false ); - assertTrue( "boolean replacement did not occur", bool ); + assertTrue( bool, "boolean replacement did not occur" ); int i = ConfigurationHelper.getInt( "my.nonexistent.prop", props, -1 ); assertEquals( -1, i ); @@ -81,19 +82,19 @@ public void testPlaceholderReplacement() { Integer I = ConfigurationHelper.getInteger( "my.nonexistent.prop", props ); assertNull( I ); I = ConfigurationHelper.getInteger( "my.integer.prop", props ); - assertEquals( I, new Integer( 1 ) ); + assertEquals( Integer.valueOf( 1 ), I ); str = props.getProperty( "partial.prop1" ); - assertEquals( "partial replacement (ends)", "tmp/middle/dir/tmp.txt", str ); + assertEquals( "tmp/middle/dir/tmp.txt", str, "partial replacement (ends)" ); str = props.getProperty( "partial.prop2" ); - assertEquals( "partial replacement (midst)", "basedir/tmp/myfile.txt", str ); + assertEquals( "basedir/tmp/myfile.txt", str, "partial replacement (midst)" ); } @Test public void testParseExceptions() { boolean b = ConfigurationHelper.getBoolean( "parse.error", props ); - assertFalse( "parse exception case - boolean", b ); + assertFalse( b, "parse exception case - boolean" ); try { ConfigurationHelper.getInt( "parse.error", props, 20 ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/util/RowVersionComparatorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/util/RowVersionComparatorTest.java index 093f2e4733ab..2442756bfe5e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/util/RowVersionComparatorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/util/RowVersionComparatorTest.java @@ -4,19 +4,19 @@ */ package org.hibernate.orm.test.util; -import org.junit.Test; - import org.hibernate.internal.util.compare.RowVersionComparator; -import org.hibernate.testing.junit4.BaseUnitTestCase; +import org.hibernate.testing.orm.junit.BaseUnitTest; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Gail Badner */ -public class RowVersionComparatorTest extends BaseUnitTestCase { +@BaseUnitTest +public class RowVersionComparatorTest { @Test public void testNull() { @@ -47,52 +47,37 @@ public void testNull() { @Test public void testArraysSameLength() { - assertEquals( - 0, - RowVersionComparator.INSTANCE.compare( - new byte[] {}, - new byte[] {} - ) - ); - assertEquals( - 0, - RowVersionComparator.INSTANCE.compare( - new byte[] { 1 }, - new byte[] { 1 } - ) - ); - assertEquals( - 0, - RowVersionComparator.INSTANCE.compare( - new byte[] { 1, 2 }, - new byte[] { 1, 2 } - ) - ); - assertTrue( - RowVersionComparator.INSTANCE.compare( - new byte[] { 0, 2 }, - new byte[] { 1, 2 } - ) < 0 - ); + assertEquals( 0, RowVersionComparator.INSTANCE.compare( + new byte[] {}, + new byte[] {} + ) ); + assertEquals( 0, RowVersionComparator.INSTANCE.compare( + new byte[] { 1 }, + new byte[] { 1 } + ) ); + assertEquals( 0, RowVersionComparator.INSTANCE.compare( + new byte[] { 1, 2 }, + new byte[] { 1, 2 } + ) ); + assertTrue( RowVersionComparator.INSTANCE.compare( + new byte[] { 0, 2 }, + new byte[] { 1, 2 } + ) < 0 ); - assertTrue( - RowVersionComparator.INSTANCE.compare( - new byte[] { 1, 1 }, - new byte[] { 1, 2 } - ) < 0 - ); + assertTrue( RowVersionComparator.INSTANCE.compare( + new byte[] { 1, 1 }, + new byte[] { 1, 2 } + ) < 0 ); assertTrue( RowVersionComparator.INSTANCE.compare( new byte[] { 2, 2 }, new byte[] { 1, 2 } - ) > 0 - ); + ) > 0 ); assertTrue( RowVersionComparator.INSTANCE.compare( new byte[] { 2, 2 }, new byte[] { 2, 1 } - ) > 0 - ); + ) > 0 ); } @Test @@ -100,37 +85,30 @@ public void testArraysDifferentLength() { assertTrue( RowVersionComparator.INSTANCE.compare( new byte[] {}, new byte[] { 1 } - ) < 0 - ); + ) < 0 ); assertTrue( RowVersionComparator.INSTANCE.compare( new byte[] { 1 }, new byte[] {} - ) > 0 - ); + ) > 0 ); assertTrue( RowVersionComparator.INSTANCE.compare( new byte[] { 1 }, new byte[] { 1, 2 } - ) < 0 - ); + ) < 0 ); assertTrue( RowVersionComparator.INSTANCE.compare( new byte[] { 1, 2 }, new byte[] { 1 } - ) > 0 - ); + ) > 0 ); assertTrue( RowVersionComparator.INSTANCE.compare( new byte[] { 2 }, new byte[] { 1, 2 } - ) > 0 - ); + ) > 0 ); assertTrue( RowVersionComparator.INSTANCE.compare( new byte[] { 1, 2 }, new byte[] { 2 } - ) < 0 - ); - + ) < 0 ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/util/SerializationHelperTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/util/SerializationHelperTest.java index 6ce03ded2b7b..d7cfa66588b3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/util/SerializationHelperTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/util/SerializationHelperTest.java @@ -6,17 +6,17 @@ import java.io.InputStream; import java.io.Serializable; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.BaseUnitTest; import org.hibernate.LockMode; import org.hibernate.bytecode.spi.ByteCodeHelper; import org.hibernate.internal.util.SerializationHelper; -import org.hibernate.testing.junit4.BaseUnitTestCase; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; /** * This is basically a test to assert the expectations of {@link org.hibernate.type.SerializableType} @@ -24,27 +24,29 @@ * * @author Steve Ebersole */ -public class SerializationHelperTest extends BaseUnitTestCase { +@BaseUnitTest +public class SerializationHelperTest { private ClassLoader original; private CustomClassLoader custom; - @Before - public void setUp() throws Exception { + @BeforeEach + public void setUp() { original = Thread.currentThread().getContextClassLoader(); custom = new CustomClassLoader( original ); Thread.currentThread().setContextClassLoader( custom ); } - @After + @AfterEach public void tearDown() throws Exception { Thread.currentThread().setContextClassLoader( original ); + custom = null; } @Test public void testSerializeDeserialize() throws Exception { - Class clazz = Thread.currentThread().getContextClassLoader().loadClass( + Class clazz = Thread.currentThread().getContextClassLoader().loadClass( "org.hibernate.orm.test.util.SerializableThing" ); - Object instance = clazz.newInstance(); + Object instance = clazz.getDeclaredConstructor().newInstance(); // SerializableType.toBytes() logic, as called from SerializableType.disassemble() byte[] bytes = SerializationHelper.serialize( (Serializable) instance ); @@ -59,7 +61,8 @@ public void testSerializeDeserialize() throws Exception { assertEquals( custom, instance2.getClass().getClassLoader() ); } - public void testSerDeserClassUnknownToCustomLoader() throws Exception { + @Test + public void testSerDeserClassUnknownToCustomLoader() { Object instance = LockMode.OPTIMISTIC; assertSame( SerializationHelper.hibernateClassLoader(), @@ -84,7 +87,7 @@ public CustomClassLoader(ClassLoader parent) { super( parent ); } - public Class loadClass(String name) throws ClassNotFoundException { + public Class loadClass(String name) throws ClassNotFoundException { if ( name.equals( "org.hibernate.LockMode" ) ) { throw new ClassNotFoundException( "Could not find "+ name ); } @@ -92,7 +95,7 @@ public Class loadClass(String name) throws ClassNotFoundException { return getParent().loadClass( name ); } - Class c = findLoadedClass( name ); + Class c = findLoadedClass( name ); if ( c != null ) { return c; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/util/StringHelperTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/util/StringHelperTest.java index f83b38e67edd..31dce07c96df 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/util/StringHelperTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/util/StringHelperTest.java @@ -4,25 +4,24 @@ */ package org.hibernate.orm.test.util; -import java.util.Arrays; - -import org.junit.Assert; -import org.junit.Test; - import org.hibernate.dialect.H2Dialect; import org.hibernate.dialect.SQLServerDialect; import org.hibernate.internal.util.StringHelper; -import org.hibernate.testing.junit4.BaseUnitTestCase; +import org.hibernate.testing.orm.junit.BaseUnitTest; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Steve Ebersole */ -public class StringHelperTest extends BaseUnitTestCase { +@BaseUnitTest +public class StringHelperTest { private static final String BASE_PACKAGE = "org.hibernate"; private static final String STRING_HELPER_FQN = "org.hibernate.internal.util.StringHelper"; @@ -63,17 +62,18 @@ public void testBasePackageCollapsing() { @Test public void testFindIdentifierWord() { - assertEquals( StringHelper.indexOfIdentifierWord( "", "word" ), -1 ); - assertEquals( StringHelper.indexOfIdentifierWord( null, "word" ), -1 ); - assertEquals( StringHelper.indexOfIdentifierWord( "sentence", null ), -1 ); - assertEquals( StringHelper.indexOfIdentifierWord( "where name=?13 and description=?1", "?1" ), 31 ); - assertEquals( StringHelper.indexOfIdentifierWord( "where name=?13 and description=?1 and category_id=?4", "?1" ), 31 ); - assertEquals( StringHelper.indexOfIdentifierWord( "?1", "?1" ), 0 ); - assertEquals( StringHelper.indexOfIdentifierWord( "no identifier here", "?1" ), -1 ); - assertEquals( StringHelper.indexOfIdentifierWord( "some text ?", "?" ), 10 ); + assertEquals( -1, StringHelper.indexOfIdentifierWord( "", "word" ) ); + assertEquals( -1, StringHelper.indexOfIdentifierWord( null, "word" ) ); + assertEquals( -1, StringHelper.indexOfIdentifierWord( "sentence", null ) ); + assertEquals( 31, StringHelper.indexOfIdentifierWord( "where name=?13 and description=?1", "?1" ) ); + assertEquals( 31, StringHelper.indexOfIdentifierWord( "where name=?13 and description=?1 and category_id=?4", "?1" ) ); + assertEquals( 0, StringHelper.indexOfIdentifierWord( "?1", "?1" ) ); + assertEquals( -1, StringHelper.indexOfIdentifierWord( "no identifier here", "?1" ) ); + assertEquals( 10, StringHelper.indexOfIdentifierWord( "some text ?", "?" ) ); } - private static H2Dialect DIALECT = new H2Dialect(); + private static final H2Dialect DIALECT = new H2Dialect(); + @Test public void testArrayUnquoting() { assertNull( StringHelper.unquote( (String[]) null, DIALECT ) ); @@ -87,27 +87,27 @@ public void testArrayUnquoting() { private static void unchanged(String[] input) { final String[] output = StringHelper.unquote( input, DIALECT ); - assertTrue( input == output ); + assertSame( input, output ); } private static void helperEquals(String[] expectation, String[] input) { final String[] output = StringHelper.unquote( input, DIALECT ); - assertTrue( Arrays.equals( expectation, output ) ); + assertArrayEquals( expectation, output ); } @Test public void testIsQuotedWithDialect() { - Assert.assertFalse( StringHelper.isQuoted( "a", DIALECT ) ); - Assert.assertTrue( StringHelper.isQuoted( "`a`", DIALECT ) ); + assertFalse( StringHelper.isQuoted( "a", DIALECT ) ); + assertTrue( StringHelper.isQuoted( "`a`", DIALECT ) ); //This dialect has a different "open" than "close" quoting symbol: final SQLServerDialect sqlServerDialect = new SQLServerDialect(); - Assert.assertTrue( StringHelper.isQuoted( "[a]", sqlServerDialect ) ); - Assert.assertFalse( StringHelper.isQuoted( "`a]", sqlServerDialect ) ); - Assert.assertFalse( StringHelper.isQuoted( "[a`", sqlServerDialect ) ); - Assert.assertFalse( StringHelper.isQuoted( "\"a`", sqlServerDialect ) ); - Assert.assertFalse( StringHelper.isQuoted( "`a\"", sqlServerDialect ) ); - Assert.assertFalse( StringHelper.isQuoted( "a", sqlServerDialect ) ); + assertTrue( StringHelper.isQuoted( "[a]", sqlServerDialect ) ); + assertFalse( StringHelper.isQuoted( "`a]", sqlServerDialect ) ); + assertFalse( StringHelper.isQuoted( "[a`", sqlServerDialect ) ); + assertFalse( StringHelper.isQuoted( "\"a`", sqlServerDialect ) ); + assertFalse( StringHelper.isQuoted( "`a\"", sqlServerDialect ) ); + assertFalse( StringHelper.isQuoted( "a", sqlServerDialect ) ); } @Test diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/util/dtd/EntityResolverTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/util/dtd/EntityResolverTest.java index 78dfe3378e9d..a1e1bd3c7637 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/util/dtd/EntityResolverTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/util/dtd/EntityResolverTest.java @@ -5,35 +5,26 @@ package org.hibernate.orm.test.util.dtd; 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.BaseUnitTestCase; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import org.hibernate.testing.orm.junit.BaseUnitTest; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.ServiceRegistryScope; +import org.junit.jupiter.api.Test; /** * @author Steve Ebersole */ -public class EntityResolverTest extends BaseUnitTestCase { +@SuppressWarnings("JUnitMalformedDeclaration") +@ServiceRegistry +@BaseUnitTest +public class EntityResolverTest { @Test - public void testEntityIncludeResolution() { + public void testEntityIncludeResolution(ServiceRegistryScope registryScope) { // Parent.hbm.xml contains the following entity include: // // which we are expecting the Hibernate custom entity resolver to be able to resolve // locally via classpath lookup. - final MetadataSources metadataSources = new MetadataSources( ServiceRegistryUtil.serviceRegistry() ) - .addResource( "org/hibernate/orm/test/util/dtd/Parent.hbm.xml" ); - - try { - metadataSources.buildMetadata(); - } - finally { - ServiceRegistry metaServiceRegistry = metadataSources.getServiceRegistry(); - if(metaServiceRegistry instanceof BootstrapServiceRegistry ) { - BootstrapServiceRegistryBuilder.destroy( metaServiceRegistry ); - } - } + new MetadataSources( registryScope.getRegistry() ) + .addResource( "org/hibernate/orm/test/util/dtd/Parent.hbm.xml" ) + .buildMetadata(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/version/InstantVersionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/version/InstantVersionTest.java index a22bab7ac229..9538d49fa146 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/version/InstantVersionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/version/InstantVersionTest.java @@ -10,47 +10,41 @@ import jakarta.persistence.Table; import jakarta.persistence.Version; -import org.hibernate.Session; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Steve Ebersole */ +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey( value = "HHH-10026" ) -public class InstantVersionTest extends BaseNonConfigCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { TheEntity.class }; +@DomainModel(annotatedClasses = InstantVersionTest.TheEntity.class) +@SessionFactory +public class InstantVersionTest { + + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test - public void testInstantUsageAsVersion() { - Session session = openSession(); - session.getTransaction().begin(); - TheEntity e = new TheEntity( 1 ); - session.persist( e ); - session.getTransaction().commit(); - session.close(); - - session = openSession(); - session.getTransaction().begin(); - e = session.byId( TheEntity.class ).load( 1 ); - assertThat( e.getTs(), notNullValue() ); - session.getTransaction().commit(); - session.close(); - - session = openSession(); - session.getTransaction().begin(); - e = session.byId( TheEntity.class ).load( 1 ); - session.remove( e ); - session.getTransaction().commit(); - session.close(); + public void testInstantUsageAsVersion(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + var e = new TheEntity( 1 ); + session.persist( e ); + } ); + + factoryScope.inTransaction( (session) -> { + var e = session.find( TheEntity.class, 1 ); + assertThat( e.getTs() ).isNotNull(); + } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/version/LocalDateTimeVersionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/version/LocalDateTimeVersionTest.java index 9362d1b02051..994fb2c2233a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/version/LocalDateTimeVersionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/version/LocalDateTimeVersionTest.java @@ -10,48 +10,38 @@ import jakarta.persistence.Table; import jakarta.persistence.Version; -import org.hibernate.Session; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Steve Ebersole */ -@JiraKey( value = "HHH-10026" ) -public class LocalDateTimeVersionTest extends BaseNonConfigCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { TheEntity.class }; +@SuppressWarnings("JUnitMalformedDeclaration") +@JiraKey("HHH-10026") +@DomainModel(annotatedClasses = LocalDateTimeVersionTest.TheEntity.class) +@SessionFactory +public class LocalDateTimeVersionTest { + @Test + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test - public void testInstantUsageAsVersion() { - Session session = openSession(); - session.getTransaction().begin(); - TheEntity e = new TheEntity( 1 ); - session.persist( e ); - session.getTransaction().commit(); - session.close(); - - session = openSession(); - session.getTransaction().begin(); - e = session.byId( TheEntity.class ).load( 1 ); - assertThat( e.getTs(), notNullValue() ); - session.getTransaction().commit(); - session.close(); - - session = openSession(); - session.getTransaction().begin(); - e = session.byId( TheEntity.class ).load( 1 ); - session.remove( e ); - session.getTransaction().commit(); - session.close(); + public void testInstantUsageAsVersion(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + session.persist( new TheEntity( 1 ) ); + } ); + + factoryScope.inTransaction( (session) -> { + var e = session.find( TheEntity.class, 1 ); + assertNotNull( e.getTs() ); + } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/version/OffsetDateTimeVersionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/version/OffsetDateTimeVersionTest.java index b88231d77bcc..ed89f4a13e49 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/version/OffsetDateTimeVersionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/version/OffsetDateTimeVersionTest.java @@ -4,54 +4,45 @@ */ package org.hibernate.orm.test.version; -import java.time.OffsetDateTime; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; import jakarta.persistence.Version; - -import org.hibernate.Session; - +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; +import java.time.OffsetDateTime; + +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Steve Ebersole */ +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey( value = "HHH-10026" ) -public class OffsetDateTimeVersionTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel(annotatedClasses = OffsetDateTimeVersionTest.TheEntity.class) +@SessionFactory +public class OffsetDateTimeVersionTest { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { TheEntity.class }; + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test - public void testInstantUsageAsVersion() { - Session session = openSession(); - session.getTransaction().begin(); - TheEntity e = new TheEntity( 1 ); - session.persist( e ); - session.getTransaction().commit(); - session.close(); - - session = openSession(); - session.getTransaction().begin(); - e = session.byId( TheEntity.class ).load( 1 ); - assertThat( e.getTs(), notNullValue() ); - session.getTransaction().commit(); - session.close(); - - session = openSession(); - session.getTransaction().begin(); - e = session.byId( TheEntity.class ).load( 1 ); - session.remove( e ); - session.getTransaction().commit(); - session.close(); + public void testInstantUsageAsVersion(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + session.persist( new TheEntity( 1 ) ); + } ); + + factoryScope.inTransaction( (session) -> { + var e = session.find( TheEntity.class, 1 ); + assertNotNull( e.getTs() ); + } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/version/UserVersionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/version/UserVersionTest.java index 8563d08a48e1..c4a5dac1d95a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/version/UserVersionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/version/UserVersionTest.java @@ -4,70 +4,57 @@ */ package org.hibernate.orm.test.version; -import java.io.Serializable; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; -import java.util.Objects; - +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Version; import org.hibernate.HibernateException; -import org.hibernate.boot.MetadataBuilder; +import org.hibernate.annotations.TypeRegistration; import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.type.descriptor.WrapperOptions; import org.hibernate.usertype.UserVersionType; - -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.orm.junit.BaseSessionFactoryFunctionalTest; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; -import jakarta.persistence.Column; -import jakarta.persistence.Entity; -import jakarta.persistence.Id; -import jakarta.persistence.Version; -import org.hamcrest.CoreMatchers; - -import static org.hamcrest.MatcherAssert.assertThat; - -@JiraKey( value = "HHH-15240") -public class UserVersionTest extends BaseSessionFactoryFunctionalTest { +import java.io.Serializable; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.Objects; - private static long versionValue; +import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - TestEntity.class - }; - } - @Override - protected void applyMetadataBuilder(MetadataBuilder metadataBuilder) { - metadataBuilder.applyBasicType( - new CustomVersionUserVersionType(), - CustomVersion.class.getName() - ); +@SuppressWarnings("JUnitMalformedDeclaration") +@JiraKey("HHH-15240") +@DomainModel(annotatedClasses = UserVersionTest.TestEntity.class) +@SessionFactory +public class UserVersionTest { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test - public void testIt() { - inTransaction( - session -> { - TestEntity testEntity = new TestEntity( 1 ); - session.persist( testEntity ); - } - ); - - inTransaction( - session -> { - TestEntity testEntity = session.get( TestEntity.class, 1 ); - assertThat( testEntity.getVersion().getRev(), CoreMatchers.is( versionValue ) ); - } - ); + public void testIt(SessionFactoryScope factoryScope) { + factoryScope.inTransaction(session -> { + session.persist( new TestEntity( 1 ) ); + } ); + + factoryScope.inTransaction( session -> { + TestEntity testEntity = session.find( TestEntity.class, 1 ); + assertThat( testEntity.getVersion().getRev() ).isEqualTo( CustomVersionUserVersionType.versionValue ); + } ); } @Entity(name = "TestEntity") + @TypeRegistration(basicClass = CustomVersion.class, userType = CustomVersionUserVersionType.class) public static class TestEntity { @Id public int id; @@ -123,6 +110,7 @@ public int hashCode() { } public static class CustomVersionUserVersionType implements UserVersionType { + public static long versionValue; @Override public int getSqlType() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/version/VersionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/version/VersionTest.java index e29f380df03e..7c9d762c4148 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/version/VersionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/version/VersionTest.java @@ -5,150 +5,120 @@ package org.hibernate.orm.test.version; -import org.junit.Test; - import org.hibernate.Hibernate; -import org.hibernate.Session; -import org.hibernate.Transaction; - +import org.hibernate.internal.util.MutableObject; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Max Rydahl Andersen */ -public class VersionTest extends BaseCoreFunctionalTestCase { - @Override - public String[] getMappings() { - return new String[] { "org/hibernate/orm/test/version/PersonThing.hbm.xml" }; - } - - @Override - protected String getBaseForMappings() { - return ""; +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(xmlMappings = "org/hibernate/orm/test/version/PersonThing.hbm.xml") +@SessionFactory +public class VersionTest { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test - public void testVersionShortCircuitFlush() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Person gavin = new Person("Gavin"); - new Thing("Passport", gavin); - s.persist(gavin); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - Thing passp = (Thing) s.get(Thing.class, "Passport"); - passp.setLongDescription("blah blah blah"); - s.createQuery("from Person").list(); - s.createQuery("from Person").list(); - s.createQuery("from Person").list(); - t.commit(); - s.close(); - - assertEquals( 1, passp.getVersion() ); - - s = openSession(); - t = s.beginTransaction(); - s.createQuery("delete from Thing").executeUpdate(); - s.createQuery("delete from Person").executeUpdate(); - t.commit(); - s.close(); + public void testVersionShortCircuitFlush(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + Person gavin = new Person("Gavin"); + new Thing("Passport", gavin); + session.persist(gavin); + } ); + + var passp = factoryScope.fromTransaction( (session) -> { + Thing loaded = session.find( Thing.class, "Passport" ); + loaded.setLongDescription("blah blah blah"); + session.createQuery("from Person").list(); + session.createQuery("from Person").list(); + session.createQuery("from Person").list(); + return loaded; + } ); + + assertThat( passp.getVersion() ).isEqualTo( 1 ); } @Test @JiraKey( value = "HHH-11549") - public void testMetamodelContainsHbmVersion() { - try (Session session = openSession()) { + public void testMetamodelContainsHbmVersion(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { session.getMetamodel().entity( Person.class ).getAttribute( "version" ); - } + } ); } @Test - public void testCollectionVersion() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Person gavin = new Person("Gavin"); - new Thing("Passport", gavin); - s.persist(gavin); - t.commit(); - s.close(); - - assertEquals(0, gavin.getVersion()); - - s = openSession(); - t = s.beginTransaction(); - gavin = getPerson( s ); - new Thing("Laptop", gavin); - t.commit(); - s.close(); - - assertEquals(1, gavin.getVersion()); - assertFalse( Hibernate.isInitialized( gavin.getThings() ) ); - - s = openSession(); - t = s.beginTransaction(); - gavin = getPerson( s ); - gavin.getThings().clear(); - t.commit(); - s.close(); - - assertEquals(2, gavin.getVersion()); - assertTrue( Hibernate.isInitialized( gavin.getThings() ) ); - - s = openSession(); - t = s.beginTransaction(); - s.remove(gavin); - t.commit(); - s.close(); + public void testCollectionVersion(SessionFactoryScope factoryScope) { + final MutableObject gavinRef = new MutableObject<>(); + + factoryScope.inTransaction( (session) -> { + Person gavin = new Person("Gavin"); + new Thing("Passport", gavin); + session.persist(gavin); + gavinRef.set( gavin ); + } ); + + assertThat( gavinRef.get().getVersion() ).isEqualTo( 0 ); + + factoryScope.inTransaction( (session) -> { + final Person gavin = session.find( Person.class, "Gavin" ); + gavinRef.set( gavin ); + new Thing("Laptop", gavin); + } ); + + assertThat( gavinRef.get().getVersion() ).isEqualTo( 1 ); + assertFalse( Hibernate.isInitialized( gavinRef.get().getThings() ) ); + + factoryScope.inTransaction( (session) -> { + final Person gavin = session.find( Person.class, "Gavin" ); + gavinRef.set( gavin ); + gavin.getThings().clear(); + } ); + + assertThat( gavinRef.get().getVersion() ).isEqualTo( 2 ); + assertTrue( Hibernate.isInitialized( gavinRef.get().getThings() ) ); } @Test - public void testCollectionNoVersion() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Person gavin = new Person("Gavin"); - new Task("Code", gavin); - s.persist(gavin); - t.commit(); - s.close(); - - assertEquals(0, gavin.getVersion()); - - s = openSession(); - t = s.beginTransaction(); - gavin = getPerson( s ); - new Task("Document", gavin); - t.commit(); - s.close(); - - assertEquals(0, gavin.getVersion()); - assertFalse( Hibernate.isInitialized( gavin.getTasks() ) ); - - s = openSession(); - t = s.beginTransaction(); - gavin = getPerson( s ); - gavin.getTasks().clear(); - t.commit(); - s.close(); - - assertEquals(0, gavin.getVersion()); - assertTrue( Hibernate.isInitialized( gavin.getTasks() ) ); - - s = openSession(); - t = s.beginTransaction(); - s.remove(gavin); - t.commit(); - s.close(); - } - - private Person getPerson(Session s) { - return session.createQuery( "select p from Person p", Person.class ).uniqueResult(); + public void testCollectionNoVersion(SessionFactoryScope factoryScope) { + final MutableObject gavinRef = new MutableObject<>(); + + factoryScope.inTransaction( (session) -> { + Person gavin = new Person("Gavin"); + new Task("Code", gavin); + session.persist(gavin); + gavinRef.set( gavin ); + } ); + + assertThat( gavinRef.get().getVersion() ).isEqualTo( 0 ); + + factoryScope.inTransaction( (session) -> { + final Person gavin = session.find( Person.class, "Gavin" ); + gavinRef.set( gavin ); + new Task("Document", gavin); + } ); + + assertThat( gavinRef.get().getVersion() ).isEqualTo( 0 ); + assertFalse( Hibernate.isInitialized( gavinRef.get().getTasks() ) ); + + factoryScope.inTransaction( (session) -> { + final Person gavin = session.find( Person.class, "Gavin" ); + gavinRef.set( gavin ); + gavin.getTasks().clear(); + } ); + + assertThat( gavinRef.get().getVersion() ).isEqualTo( 0 ); + assertTrue( Hibernate.isInitialized( gavinRef.get().getTasks() ) ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/version/ZonedDateTimeVersionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/version/ZonedDateTimeVersionTest.java index c14c1970a35c..d6bc8fa4375f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/version/ZonedDateTimeVersionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/version/ZonedDateTimeVersionTest.java @@ -4,54 +4,44 @@ */ package org.hibernate.orm.test.version; -import java.time.ZonedDateTime; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; import jakarta.persistence.Version; - -import org.hibernate.Session; - +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import java.time.ZonedDateTime; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Steve Ebersole */ -@JiraKey( value = "HHH-10026" ) -public class ZonedDateTimeVersionTest extends BaseNonConfigCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { TheEntity.class }; +@SuppressWarnings("JUnitMalformedDeclaration") +@JiraKey("HHH-10026") +@DomainModel(annotatedClasses = ZonedDateTimeVersionTest.TheEntity.class) +@SessionFactory +public class ZonedDateTimeVersionTest { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test - public void testInstantUsageAsVersion() { - Session session = openSession(); - session.getTransaction().begin(); - TheEntity e = new TheEntity( 1 ); - session.persist( e ); - session.getTransaction().commit(); - session.close(); - - session = openSession(); - session.getTransaction().begin(); - e = session.byId( TheEntity.class ).load( 1 ); - assertThat( e.getTs(), notNullValue() ); - session.getTransaction().commit(); - session.close(); - - session = openSession(); - session.getTransaction().begin(); - e = session.byId( TheEntity.class ).load( 1 ); - session.remove( e ); - session.getTransaction().commit(); - session.close(); + public void testInstantUsageAsVersion(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + session.persist( new TheEntity( 1 ) ); + } ); + + factoryScope.inTransaction( (session) -> { + var e = session.find( TheEntity.class, 1 ); + assertNotNull( e.getTs() ); + } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/version/db/DbVersionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/version/db/DbVersionTest.java index b65dbf084f2e..89bab1ba818c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/version/db/DbVersionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/version/db/DbVersionTest.java @@ -4,123 +4,124 @@ */ package org.hibernate.orm.test.version.db; -import java.sql.Timestamp; - -import org.junit.Test; - -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; - +import org.hibernate.dialect.Dialect; import org.hibernate.dialect.SybaseDialect; +import org.hibernate.internal.util.MutableObject; +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.descriptor.java.JdbcTimestampJavaType; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import java.sql.Timestamp; /** * @author Steve Ebersole */ -public class DbVersionTest extends BaseCoreFunctionalTestCase { - @Override - public String[] getMappings() { - return new String[] { "version/db/User.hbm.xml" }; - } - - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(xmlMappings = "org/hibernate/orm/test/version/db/User.hbm.xml") +@SessionFactory +public class DbVersionTest { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test - public void testCollectionVersion() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - User steve = new User( "steve" ); - s.persist( steve ); - Group admin = new Group( "admin" ); - s.persist( admin ); - t.commit(); - s.close(); - - Timestamp steveTimestamp = steve.getTimestamp(); + public void testCollectionVersion(SessionFactoryScope factoryScope) throws Exception { + final var tsJavaType = JdbcTimestampJavaType.INSTANCE; + final MutableObject steveRef = new MutableObject<>(); + + factoryScope.inTransaction( (session) -> { + var steve = new User( 1, "steve" ); + session.persist( steve ); + var admin = new Group( 1, "admin" ); + session.persist( admin ); + + steveRef.set( steve ); + } ); + + Timestamp steveTimestamp = steveRef.get().getTimestamp(); // For dialects (Oracle8 for example) which do not return "true // timestamps" sleep for a bit to allow the db date-time increment... Thread.sleep( 1500 ); - s = openSession(); - t = s.beginTransaction(); - steve = ( User ) s.get( User.class, steve.getId() ); - admin = ( Group ) s.get( Group.class, admin.getId() ); - steve.getGroups().add( admin ); - admin.getUsers().add( steve ); - t.commit(); - s.close(); + factoryScope.inTransaction( (session) -> { + var steve = session.find( User.class, 1 ); + var admin = session.find( Group.class, 1 ); + steve.getGroups().add( admin ); + admin.getUsers().add( steve ); + steveRef.set( steve ); + } ); - assertFalse( "owner version not incremented", JdbcTimestampJavaType.INSTANCE.areEqual( steveTimestamp, steve.getTimestamp() ) ); + Assertions.assertFalse( tsJavaType.areEqual( steveTimestamp, steveRef.get().getTimestamp() ), + "owner version not incremented" ); - steveTimestamp = steve.getTimestamp(); + steveTimestamp = steveRef.get().getTimestamp(); Thread.sleep( 1500 ); - s = openSession(); - t = s.beginTransaction(); - steve = ( User ) s.get( User.class, steve.getId() ); - steve.getGroups().clear(); - t.commit(); - s.close(); - - assertFalse( "owner version not incremented", JdbcTimestampJavaType.INSTANCE.areEqual( steveTimestamp, steve.getTimestamp() ) ); - - s = openSession(); - t = s.beginTransaction(); - s.remove( s.getReference( User.class, steve.getId() ) ); - s.remove( s.getReference( Group.class, admin.getId() ) ); - t.commit(); - s.close(); + factoryScope.inTransaction( (session) -> { + var steve = session.find( User.class, 1 ); + steve.getGroups().clear(); + steveRef.set( steve ); + } ); + + Assertions.assertFalse( tsJavaType.areEqual( steveTimestamp, steveRef.get().getTimestamp() ), + "owner version not incremented" ); } @Test - public void testCollectionNoVersion() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - User steve = new User( "steve" ); - s.persist( steve ); - Permission perm = new Permission( "silly", "user", "rw" ); - s.persist( perm ); - t.commit(); - s.close(); - - Timestamp steveTimestamp = steve.getTimestamp(); - if ( getDialect() instanceof SybaseDialect ) { + public void testCollectionNoVersion(SessionFactoryScope factoryScope) throws Exception { + final var dialect = factoryScope.getSessionFactory().getJdbcServices().getDialect(); + final var tsJavaType = JdbcTimestampJavaType.INSTANCE; + final MutableObject steveRef = new MutableObject<>(); + + factoryScope.inTransaction( (session) -> { + var steve = new User( 1, "steve" ); + session.persist( steve ); + var perm = new Permission( 1, "silly", "user", "rw" ); + session.persist( perm ); + + steveRef.set( steve ); + } ); + + var steveTimestamp = determineTimestamp( steveRef, dialect ); + + factoryScope.inTransaction( (session) -> { + var steve = session.find( User.class, 1 ); + var perm = session.find( Permission.class, 1 ); + steve.getPermissions().add( perm ); + + steveRef.set( steve ); + } ); + + Assertions.assertTrue( tsJavaType.areEqual( steveTimestamp, steveRef.get().getTimestamp() ), + "owner version was incremented" ); + + steveTimestamp = determineTimestamp( steveRef, dialect ); + + factoryScope.inTransaction( (session) -> { + var steve = session.find( User.class, 1 ); + steve.getPermissions().clear(); + + steveRef.set( steve ); + } ); + + Assertions.assertTrue( tsJavaType.areEqual( steveTimestamp, steveRef.get().getTimestamp() ), + "owner version was incremented" ); + } + + private Timestamp determineTimestamp(MutableObject steveRef, Dialect dialect) { + var timestamp = steveRef.get().getTimestamp(); + + if ( dialect instanceof SybaseDialect ) { // Sybase has 1/300th sec precision, but not for the `getdate()` function which we use for DB generation - steveTimestamp = new Timestamp( steveTimestamp.getTime() ); + timestamp = new Timestamp( timestamp.getTime() ); } - s = openSession(); - t = s.beginTransaction(); - steve = ( User ) s.get( User.class, steve.getId() ); - perm = ( Permission ) s.get( Permission.class, perm.getId() ); - steve.getPermissions().add( perm ); - t.commit(); - s.close(); - - assertTrue( "owner version was incremented", JdbcTimestampJavaType.INSTANCE.areEqual( steveTimestamp, steve.getTimestamp() ) ); - - s = openSession(); - t = s.beginTransaction(); - steve = ( User ) s.get( User.class, steve.getId() ); - steve.getPermissions().clear(); - t.commit(); - s.close(); - - assertTrue( "owner version was incremented", JdbcTimestampJavaType.INSTANCE.areEqual( steveTimestamp, steve.getTimestamp() ) ); - - s = openSession(); - t = s.beginTransaction(); - s.remove( s.getReference( User.class, steve.getId() ) ); - s.remove( s.getReference( Permission.class, perm.getId() ) ); - t.commit(); - s.close(); + return timestamp; } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/version/db/Group.java b/hibernate-core/src/test/java/org/hibernate/orm/test/version/db/Group.java index bb01f6cb2752..ffd9968e2c9d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/version/db/Group.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/version/db/Group.java @@ -7,12 +7,10 @@ import java.util.Set; /** - * Implementation of Group. - * * @author Steve Ebersole */ public class Group { - private Long id; + private Integer id; private Date timestamp; private String name; private Set users; @@ -20,15 +18,16 @@ public class Group { public Group() { } - public Group(String name) { + public Group(Integer id, String name) { + this.id = id; this.name = name; } - public Long getId() { + public Integer getId() { return id; } - public void setId(Long id) { + public void setId(Integer id) { this.id = id; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/version/db/Permission.java b/hibernate-core/src/test/java/org/hibernate/orm/test/version/db/Permission.java index b367bd1fecdd..8b8434ecd6a0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/version/db/Permission.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/version/db/Permission.java @@ -6,12 +6,10 @@ import java.util.Date; /** - * Implementation of Permission. - * * @author Steve Ebersole */ public class Permission { - private Long id; + private Integer id; private Date timestamp; private String name; private String context; @@ -20,17 +18,18 @@ public class Permission { public Permission() { } - public Permission(String name, String context, String access) { + public Permission(Integer id, String name, String context, String access) { + this.id = id; this.name = name; this.context = context; this.access = access; } - public Long getId() { + public Integer getId() { return id; } - public void setId(Long id) { + public void setId(Integer id) { this.id = id; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/version/db/User.java b/hibernate-core/src/test/java/org/hibernate/orm/test/version/db/User.java index 844a24ed89f9..2a7831fa62e2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/version/db/User.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/version/db/User.java @@ -7,12 +7,10 @@ import java.util.Set; /** - * Implementation of User. - * * @author Steve Ebersole */ public class User { - private Long id; + private Integer id; private Timestamp timestamp; private String username; private Set groups; @@ -21,15 +19,16 @@ public class User { public User() { } - public User(String username) { + public User(Integer id, String username) { + this.id = id; this.username = username; } - public Long getId() { + public Integer getId() { return id; } - public void setId(Long id) { + public void setId(Integer id) { this.id = id; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/EagerManyToOneFetchModeJoinWhereTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/EagerManyToOneFetchModeJoinWhereTest.java index 5e6ebea16177..96ecb7f3fc0d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/EagerManyToOneFetchModeJoinWhereTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/EagerManyToOneFetchModeJoinWhereTest.java @@ -4,8 +4,6 @@ */ package org.hibernate.orm.test.where.annotations; -import java.util.HashSet; -import java.util.Set; import jakarta.persistence.CascadeType; import jakarta.persistence.ElementCollection; import jakarta.persistence.Embeddable; @@ -16,97 +14,90 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; - import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import org.hibernate.annotations.NotFound; import org.hibernate.annotations.NotFoundAction; import org.hibernate.annotations.SQLRestriction; - -import org.hibernate.testing.FailureExpected; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.FailureExpected; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +import java.util.HashSet; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; /** * @author Gail Badner */ -public class EagerManyToOneFetchModeJoinWhereTest extends BaseNonConfigCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Product.class, Category.class }; +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(annotatedClasses = { + EagerManyToOneFetchModeJoinWhereTest.Product.class, + EagerManyToOneFetchModeJoinWhereTest.Category.class +}) +@SessionFactory +public class EagerManyToOneFetchModeJoinWhereTest { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test - @JiraKey( value = "HHH-12104" ) - @FailureExpected( jiraKey = "HHH-12104") - public void testAssociatedWhereClause() { - Product product = new Product(); - Category category = new Category(); + @JiraKey(value = "HHH-12104") + @FailureExpected + public void testAssociatedWhereClause(SessionFactoryScope factoryScope) { + var product = new Product(); + var category = new Category(); category.name = "flowers"; product.category = category; product.containedCategory = new ContainedCategory(); product.containedCategory.category = category; product.containedCategories.add( new ContainedCategory( category ) ); - doInHibernate( - this::sessionFactory, - session -> { - session.persist( product ); - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Product p = session.get( Product.class, product.id ); - assertNotNull( p ); - assertNotNull( p.category ); - assertNotNull( p.containedCategory.category ); - assertEquals( 1, p.containedCategories.size() ); - assertSame( p.category, p.containedCategory.category ); - assertSame( p.category, p.containedCategories.iterator().next().category ); - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Category c = session.get( Category.class, category.id ); - assertNotNull( c ); - c.inactive = 1; - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Category c = session.get( Category.class, category.id ); - assertNull( c ); - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - // Entity's where clause is ignored when to-one associations to that - // association is loaded eagerly using FetchMode.JOIN, so the result - // should be the same as before the Category was made inactive. - Product p = session.get( Product.class, product.id ); - assertNotNull( p ); - assertNull( p.category ); - assertNull( p.containedCategory.category ); - assertEquals( 1, p.containedCategories.size() ); - assertNull( p.containedCategories.iterator().next().category ); - } - ); + factoryScope.inTransaction( (session) -> { + session.persist( product ); + } ); + + factoryScope.inTransaction( (session) -> { + var p = session.find( Product.class, product.id ); + assertNotNull( p ); + assertNotNull( p.category ); + assertNotNull( p.containedCategory.category ); + assertEquals( 1, p.containedCategories.size() ); + Assertions.assertSame( p.category, p.containedCategory.category ); + Assertions.assertSame( p.category, p.containedCategories.iterator().next().category ); + } ); + + factoryScope.inTransaction( (session) -> { + var c = session.find( Category.class, category.id ); + assertNotNull( c ); + c.inactive = 1; + } ); + + factoryScope.inTransaction( (session) -> { + var c = session.find( Category.class, category.id ); + assertNull( c ); + } ); + + factoryScope.inTransaction( (session) -> { + // Entity-level where clause is ignored when to-one associations to that + // association is loaded eagerly using FetchMode.JOIN, so the result + // should be the same as before the Category was made inactive. + var p = session.find( Product.class, product.id ); + assertNotNull( p ); + assertNull( p.category ); + assertNull( p.containedCategory.category ); + assertEquals( 1, p.containedCategories.size() ); + assertNull( p.containedCategories.iterator().next().category ); + } ); } @Entity(name = "Product") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/EagerToManyWhereTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/EagerToManyWhereTest.java index a35ee99a4ab0..cc7ffafb146b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/EagerToManyWhereTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/EagerToManyWhereTest.java @@ -4,9 +4,6 @@ */ package org.hibernate.orm.test.where.annotations; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; @@ -16,15 +13,19 @@ import jakarta.persistence.ManyToMany; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; - import org.hibernate.annotations.SQLJoinTableRestriction; import org.hibernate.annotations.SQLRestriction; - +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; -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; @@ -36,19 +37,20 @@ * * @author Gail Badner */ -public class EagerToManyWhereTest extends BaseNonConfigCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Product.class, Category.class }; +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(annotatedClasses = { EagerToManyWhereTest.Product.class, EagerToManyWhereTest.Category.class }) +@SessionFactory +public class EagerToManyWhereTest { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test @JiraKey( value = "HHH-13011" ) - public void testAssociatedWhereClause() { - - Product product = new Product(); - Category flowers = new Category(); + public void testAssociatedWhereClause(SessionFactoryScope factoryScope) { + var product = new Product(); + var flowers = new Category(); flowers.id = 1; flowers.name = "flowers"; flowers.description = "FLOWERS"; @@ -57,7 +59,7 @@ public void testAssociatedWhereClause() { product.categoriesManyToMany.add( flowers ); product.categoriesWithDescManyToMany.add( flowers ); product.categoriesWithDescIdLt4ManyToMany.add( flowers ); - Category vegetables = new Category(); + var vegetables = new Category(); vegetables.id = 2; vegetables.name = "vegetables"; vegetables.description = "VEGETABLES"; @@ -66,7 +68,7 @@ public void testAssociatedWhereClause() { product.categoriesManyToMany.add( vegetables ); product.categoriesWithDescManyToMany.add( vegetables ); product.categoriesWithDescIdLt4ManyToMany.add( vegetables ); - Category dogs = new Category(); + var dogs = new Category(); dogs.id = 3; dogs.name = "dogs"; dogs.description = null; @@ -75,7 +77,7 @@ public void testAssociatedWhereClause() { product.categoriesManyToMany.add( dogs ); product.categoriesWithDescManyToMany.add( dogs ); product.categoriesWithDescIdLt4ManyToMany.add( dogs ); - Category building = new Category(); + var building = new Category(); building.id = 4; building.name = "building"; building.description = "BUILDING"; @@ -85,69 +87,54 @@ public void testAssociatedWhereClause() { product.categoriesWithDescManyToMany.add( building ); product.categoriesWithDescIdLt4ManyToMany.add( building ); - doInHibernate( - this::sessionFactory, - session -> { - session.persist( flowers ); - session.persist( vegetables ); - session.persist( dogs ); - session.persist( building ); - session.persist( product ); - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Product p = session.get( Product.class, product.id ); - assertNotNull( p ); - assertEquals( 4, p.categoriesOneToMany.size() ); - checkIds( p.categoriesOneToMany, new Integer[] { 1, 2, 3, 4 } ); - assertEquals( 3, p.categoriesWithDescOneToMany.size() ); - checkIds( p.categoriesWithDescOneToMany, new Integer[] { 1, 2, 4 } ); - assertEquals( 4, p.categoriesManyToMany.size() ); - checkIds( p.categoriesManyToMany, new Integer[] { 1, 2, 3, 4 } ); - assertEquals( 3, p.categoriesWithDescManyToMany.size() ); - checkIds( p.categoriesWithDescManyToMany, new Integer[] { 1, 2, 4 } ); - assertEquals( 2, p.categoriesWithDescIdLt4ManyToMany.size() ); - checkIds( p.categoriesWithDescIdLt4ManyToMany, new Integer[] { 1, 2 } ); - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Category c = session.get( Category.class, flowers.id ); - assertNotNull( c ); - c.inactive = 1; - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Category c = session.get( Category.class, flowers.id ); - assertNull( c ); - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Product p = session.get( Product.class, product.id ); - assertNotNull( p ); - assertEquals( 3, p.categoriesOneToMany.size() ); - checkIds( p.categoriesOneToMany, new Integer[] { 2, 3, 4 } ); - assertEquals( 2, p.categoriesWithDescOneToMany.size() ); - checkIds( p.categoriesWithDescOneToMany, new Integer[] { 2, 4 } ); - assertEquals( 3, p.categoriesManyToMany.size() ); - checkIds( p.categoriesManyToMany, new Integer[] { 2, 3, 4 } ); - assertEquals( 2, p.categoriesWithDescManyToMany.size() ); - checkIds( p.categoriesWithDescManyToMany, new Integer[] { 2, 4 } ); - assertEquals( 1, p.categoriesWithDescIdLt4ManyToMany.size() ); - checkIds( p.categoriesWithDescIdLt4ManyToMany, new Integer[] { 2 } ); - } - ); + factoryScope.inTransaction( (session) -> { + session.persist( flowers ); + session.persist( vegetables ); + session.persist( dogs ); + session.persist( building ); + session.persist( product ); + } ); + + factoryScope.inTransaction( (session) -> { + var p = session.find( Product.class, product.id ); + assertNotNull( p ); + assertEquals( 4, p.categoriesOneToMany.size() ); + checkIds( p.categoriesOneToMany, new Integer[] { 1, 2, 3, 4 } ); + assertEquals( 3, p.categoriesWithDescOneToMany.size() ); + checkIds( p.categoriesWithDescOneToMany, new Integer[] { 1, 2, 4 } ); + assertEquals( 4, p.categoriesManyToMany.size() ); + checkIds( p.categoriesManyToMany, new Integer[] { 1, 2, 3, 4 } ); + assertEquals( 3, p.categoriesWithDescManyToMany.size() ); + checkIds( p.categoriesWithDescManyToMany, new Integer[] { 1, 2, 4 } ); + assertEquals( 2, p.categoriesWithDescIdLt4ManyToMany.size() ); + checkIds( p.categoriesWithDescIdLt4ManyToMany, new Integer[] { 1, 2 } ); + } ); + + factoryScope.inTransaction( (session) -> { + var c = session.find( Category.class, flowers.id ); + assertNotNull( c ); + c.inactive = 1; + } ); + + factoryScope.inTransaction( (session) -> { + var c = session.find( Category.class, flowers.id ); + assertNull( c ); + } ); + + factoryScope.inTransaction( (session) -> { + var p = session.find( Product.class, product.id ); + assertNotNull( p ); + assertEquals( 3, p.categoriesOneToMany.size() ); + checkIds( p.categoriesOneToMany, new Integer[] { 2, 3, 4 } ); + assertEquals( 2, p.categoriesWithDescOneToMany.size() ); + checkIds( p.categoriesWithDescOneToMany, new Integer[] { 2, 4 } ); + assertEquals( 3, p.categoriesManyToMany.size() ); + checkIds( p.categoriesManyToMany, new Integer[] { 2, 3, 4 } ); + assertEquals( 2, p.categoriesWithDescManyToMany.size() ); + checkIds( p.categoriesWithDescManyToMany, new Integer[] { 2, 4 } ); + assertEquals( 1, p.categoriesWithDescIdLt4ManyToMany.size() ); + checkIds( p.categoriesWithDescIdLt4ManyToMany, new Integer[] { 2 } ); + } ); } private void checkIds(Set categories, Integer[] expectedIds) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/EagerToManyWhereUseClassWhereTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/EagerToManyWhereUseClassWhereTest.java index c8f1d909840a..a776b9184713 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/EagerToManyWhereUseClassWhereTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/EagerToManyWhereUseClassWhereTest.java @@ -4,17 +4,6 @@ */ package org.hibernate.orm.test.where.annotations; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -import org.hibernate.annotations.SQLJoinTableRestriction; -import org.hibernate.annotations.SQLRestriction; - -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; - import jakarta.persistence.Entity; import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; @@ -24,29 +13,45 @@ import jakarta.persistence.ManyToMany; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; +import org.hibernate.annotations.SQLJoinTableRestriction; +import org.hibernate.annotations.SQLRestriction; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; /** * @author Gail Badner */ -public class EagerToManyWhereUseClassWhereTest extends BaseNonConfigCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Product.class, Category.class }; +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(annotatedClasses = { + EagerToManyWhereUseClassWhereTest.Product.class, + EagerToManyWhereUseClassWhereTest.Category.class +}) +@SessionFactory +public class EagerToManyWhereUseClassWhereTest { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test @JiraKey("HHH-13011") - public void testAssociatedWhereClause() { - - Product product = new Product(); - Category flowers = new Category(); + public void testAssociatedWhereClause(SessionFactoryScope factoryScope) { + var product = new Product(); + var flowers = new Category(); flowers.id = 1; flowers.name = "flowers"; flowers.description = "FLOWERS"; @@ -55,7 +60,7 @@ public void testAssociatedWhereClause() { product.categoriesManyToMany.add( flowers ); product.categoriesWithDescManyToMany.add( flowers ); product.categoriesWithDescIdLt4ManyToMany.add( flowers ); - Category vegetables = new Category(); + var vegetables = new Category(); vegetables.id = 2; vegetables.name = "vegetables"; vegetables.description = "VEGETABLES"; @@ -64,7 +69,7 @@ public void testAssociatedWhereClause() { product.categoriesManyToMany.add( vegetables ); product.categoriesWithDescManyToMany.add( vegetables ); product.categoriesWithDescIdLt4ManyToMany.add( vegetables ); - Category dogs = new Category(); + var dogs = new Category(); dogs.id = 3; dogs.name = "dogs"; dogs.description = null; @@ -73,7 +78,7 @@ public void testAssociatedWhereClause() { product.categoriesManyToMany.add( dogs ); product.categoriesWithDescManyToMany.add( dogs ); product.categoriesWithDescIdLt4ManyToMany.add( dogs ); - Category building = new Category(); + var building = new Category(); building.id = 4; building.name = "building"; building.description = "BUILDING"; @@ -83,69 +88,54 @@ public void testAssociatedWhereClause() { product.categoriesWithDescManyToMany.add( building ); product.categoriesWithDescIdLt4ManyToMany.add( building ); - doInHibernate( - this::sessionFactory, - session -> { - session.persist( flowers ); - session.persist( vegetables ); - session.persist( dogs ); - session.persist( building ); - session.persist( product ); - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Product p = session.get( Product.class, product.id ); - assertNotNull( p ); - assertEquals( 4, p.categoriesOneToMany.size() ); - checkIds( p.categoriesOneToMany, new Integer[] { 1, 2, 3, 4 } ); - assertEquals( 3, p.categoriesWithDescOneToMany.size() ); - checkIds( p.categoriesWithDescOneToMany, new Integer[] { 1, 2, 4 } ); - assertEquals( 4, p.categoriesManyToMany.size() ); - checkIds( p.categoriesManyToMany, new Integer[] { 1, 2, 3, 4 } ); - assertEquals( 3, p.categoriesWithDescManyToMany.size() ); - checkIds( p.categoriesWithDescManyToMany, new Integer[] { 1, 2, 4 } ); - assertEquals( 2, p.categoriesWithDescIdLt4ManyToMany.size() ); - checkIds( p.categoriesWithDescIdLt4ManyToMany, new Integer[] { 1, 2 } ); - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Category c = session.get( Category.class, flowers.id ); - assertNotNull( c ); - c.inactive = 1; - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Category c = session.get( Category.class, flowers.id ); - assertNull( c ); - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Product p = session.get( Product.class, product.id ); - assertNotNull( p ); - assertEquals( 3, p.categoriesOneToMany.size() ); - checkIds( p.categoriesOneToMany, new Integer[] { 2, 3, 4 } ); - assertEquals( 2, p.categoriesWithDescOneToMany.size() ); - checkIds( p.categoriesWithDescOneToMany, new Integer[] { 2, 4 } ); - assertEquals( 3, p.categoriesManyToMany.size() ); - checkIds( p.categoriesManyToMany, new Integer[] { 2, 3, 4 } ); - assertEquals( 2, p.categoriesWithDescManyToMany.size() ); - checkIds( p.categoriesWithDescManyToMany, new Integer[] { 2, 4 } ); - assertEquals( 1, p.categoriesWithDescIdLt4ManyToMany.size() ); - checkIds( p.categoriesWithDescIdLt4ManyToMany, new Integer[] { 2 } ); - } - ); + factoryScope.inTransaction( (session) -> { + session.persist( flowers ); + session.persist( vegetables ); + session.persist( dogs ); + session.persist( building ); + session.persist( product ); + } ); + + factoryScope.inTransaction( (session) -> { + var p = session.find( Product.class, product.id ); + assertNotNull( p ); + assertEquals( 4, p.categoriesOneToMany.size() ); + checkIds( p.categoriesOneToMany, new Integer[] { 1, 2, 3, 4 } ); + assertEquals( 3, p.categoriesWithDescOneToMany.size() ); + checkIds( p.categoriesWithDescOneToMany, new Integer[] { 1, 2, 4 } ); + assertEquals( 4, p.categoriesManyToMany.size() ); + checkIds( p.categoriesManyToMany, new Integer[] { 1, 2, 3, 4 } ); + assertEquals( 3, p.categoriesWithDescManyToMany.size() ); + checkIds( p.categoriesWithDescManyToMany, new Integer[] { 1, 2, 4 } ); + assertEquals( 2, p.categoriesWithDescIdLt4ManyToMany.size() ); + checkIds( p.categoriesWithDescIdLt4ManyToMany, new Integer[] { 1, 2 } ); + } ); + + factoryScope.inTransaction( (session) -> { + var c = session.find( Category.class, flowers.id ); + assertNotNull( c ); + c.inactive = 1; + } ); + + factoryScope.inTransaction( (session) -> { + var c = session.find( Category.class, flowers.id ); + assertNull( c ); + } ); + + factoryScope.inTransaction( (session) -> { + var p = session.find( Product.class, product.id ); + assertNotNull( p ); + assertEquals( 3, p.categoriesOneToMany.size() ); + checkIds( p.categoriesOneToMany, new Integer[] { 2, 3, 4 } ); + assertEquals( 2, p.categoriesWithDescOneToMany.size() ); + checkIds( p.categoriesWithDescOneToMany, new Integer[] { 2, 4 } ); + assertEquals( 3, p.categoriesManyToMany.size() ); + checkIds( p.categoriesManyToMany, new Integer[] { 2, 3, 4 } ); + assertEquals( 2, p.categoriesWithDescManyToMany.size() ); + checkIds( p.categoriesWithDescManyToMany, new Integer[] { 2, 4 } ); + assertEquals( 1, p.categoriesWithDescIdLt4ManyToMany.size() ); + checkIds( p.categoriesWithDescIdLt4ManyToMany, new Integer[] { 2 } ); + } ); } private void checkIds(Set categories, Integer[] expectedIds) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/EagerToManyWhereUseClassWhereViaAnnotationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/EagerToManyWhereUseClassWhereViaAnnotationTest.java index 409277a7a47f..90cccfca5254 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/EagerToManyWhereUseClassWhereViaAnnotationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/EagerToManyWhereUseClassWhereViaAnnotationTest.java @@ -15,38 +15,44 @@ import jakarta.persistence.Table; import org.hibernate.annotations.SQLJoinTableRestriction; import org.hibernate.annotations.SQLRestriction; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.HashSet; import java.util.Set; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests association collections with AvailableSettings.USE_ENTITY_WHERE_CLAUSE_FOR_COLLECTIONS = true * * @author Gail Badner */ -public class EagerToManyWhereUseClassWhereViaAnnotationTest extends BaseNonConfigCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Product.class, Category.class }; +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(annotatedClasses = { + EagerToManyWhereUseClassWhereViaAnnotationTest.Product.class, + EagerToManyWhereUseClassWhereViaAnnotationTest.Category.class +}) +@SessionFactory +public class EagerToManyWhereUseClassWhereViaAnnotationTest { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test @JiraKey( value = "HHH-15936" ) - public void testAssociatedWhereClause() { - - Product product = new Product(); - Category flowers = new Category(); + public void testAssociatedWhereClause(SessionFactoryScope factoryScope) { + var product = new Product(); + var flowers = new Category(); flowers.id = 1; flowers.name = "flowers"; flowers.description = "FLOWERS"; @@ -55,7 +61,7 @@ public void testAssociatedWhereClause() { product.categoriesManyToMany.add( flowers ); product.categoriesWithDescManyToMany.add( flowers ); product.categoriesWithDescIdLt4ManyToMany.add( flowers ); - Category vegetables = new Category(); + var vegetables = new Category(); vegetables.id = 2; vegetables.name = "vegetables"; vegetables.description = "VEGETABLES"; @@ -64,7 +70,7 @@ public void testAssociatedWhereClause() { product.categoriesManyToMany.add( vegetables ); product.categoriesWithDescManyToMany.add( vegetables ); product.categoriesWithDescIdLt4ManyToMany.add( vegetables ); - Category dogs = new Category(); + var dogs = new Category(); dogs.id = 3; dogs.name = "dogs"; dogs.description = null; @@ -73,7 +79,7 @@ public void testAssociatedWhereClause() { product.categoriesManyToMany.add( dogs ); product.categoriesWithDescManyToMany.add( dogs ); product.categoriesWithDescIdLt4ManyToMany.add( dogs ); - Category building = new Category(); + var building = new Category(); building.id = 4; building.name = "building"; building.description = "BUILDING"; @@ -83,69 +89,54 @@ public void testAssociatedWhereClause() { product.categoriesWithDescManyToMany.add( building ); product.categoriesWithDescIdLt4ManyToMany.add( building ); - doInHibernate( - this::sessionFactory, - session -> { - session.persist( flowers ); - session.persist( vegetables ); - session.persist( dogs ); - session.persist( building ); - session.persist( product ); - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Product p = session.get( Product.class, product.id ); - assertNotNull( p ); - assertEquals( 4, p.categoriesOneToMany.size() ); - checkIds( p.categoriesOneToMany, new Integer[] { 1, 2, 3, 4 } ); - assertEquals( 3, p.categoriesWithDescOneToMany.size() ); - checkIds( p.categoriesWithDescOneToMany, new Integer[] { 1, 2, 4 } ); - assertEquals( 4, p.categoriesManyToMany.size() ); - checkIds( p.categoriesManyToMany, new Integer[] { 1, 2, 3, 4 } ); - assertEquals( 3, p.categoriesWithDescManyToMany.size() ); - checkIds( p.categoriesWithDescManyToMany, new Integer[] { 1, 2, 4 } ); - assertEquals( 2, p.categoriesWithDescIdLt4ManyToMany.size() ); - checkIds( p.categoriesWithDescIdLt4ManyToMany, new Integer[] { 1, 2 } ); - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Category c = session.get( Category.class, flowers.id ); - assertNotNull( c ); - c.inactive = 1; - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Category c = session.get( Category.class, flowers.id ); - assertNull( c ); - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Product p = session.get( Product.class, product.id ); - assertNotNull( p ); - assertEquals( 3, p.categoriesOneToMany.size() ); - checkIds( p.categoriesOneToMany, new Integer[] { 2, 3, 4 } ); - assertEquals( 2, p.categoriesWithDescOneToMany.size() ); - checkIds( p.categoriesWithDescOneToMany, new Integer[] { 2, 4 } ); - assertEquals( 3, p.categoriesManyToMany.size() ); - checkIds( p.categoriesManyToMany, new Integer[] { 2, 3, 4 } ); - assertEquals( 2, p.categoriesWithDescManyToMany.size() ); - checkIds( p.categoriesWithDescManyToMany, new Integer[] { 2, 4 } ); - assertEquals( 1, p.categoriesWithDescIdLt4ManyToMany.size() ); - checkIds( p.categoriesWithDescIdLt4ManyToMany, new Integer[] { 2 } ); - } - ); + factoryScope.inTransaction( (session) -> { + session.persist( flowers ); + session.persist( vegetables ); + session.persist( dogs ); + session.persist( building ); + session.persist( product ); + } ); + + factoryScope.inTransaction( (session) -> { + var p = session.find( Product.class, product.id ); + assertNotNull( p ); + assertEquals( 4, p.categoriesOneToMany.size() ); + checkIds( p.categoriesOneToMany, new Integer[] { 1, 2, 3, 4 } ); + assertEquals( 3, p.categoriesWithDescOneToMany.size() ); + checkIds( p.categoriesWithDescOneToMany, new Integer[] { 1, 2, 4 } ); + assertEquals( 4, p.categoriesManyToMany.size() ); + checkIds( p.categoriesManyToMany, new Integer[] { 1, 2, 3, 4 } ); + assertEquals( 3, p.categoriesWithDescManyToMany.size() ); + checkIds( p.categoriesWithDescManyToMany, new Integer[] { 1, 2, 4 } ); + assertEquals( 2, p.categoriesWithDescIdLt4ManyToMany.size() ); + checkIds( p.categoriesWithDescIdLt4ManyToMany, new Integer[] { 1, 2 } ); + } ); + + factoryScope.inTransaction( (session) -> { + var c = session.find( Category.class, flowers.id ); + assertNotNull( c ); + c.inactive = 1; + } ); + + factoryScope.inTransaction( (session) -> { + var c = session.find( Category.class, flowers.id ); + assertNull( c ); + } ); + + factoryScope.inTransaction( (session) -> { + var p = session.find( Product.class, product.id ); + assertNotNull( p ); + assertEquals( 3, p.categoriesOneToMany.size() ); + checkIds( p.categoriesOneToMany, new Integer[] { 2, 3, 4 } ); + assertEquals( 2, p.categoriesWithDescOneToMany.size() ); + checkIds( p.categoriesWithDescOneToMany, new Integer[] { 2, 4 } ); + assertEquals( 3, p.categoriesManyToMany.size() ); + checkIds( p.categoriesManyToMany, new Integer[] { 2, 3, 4 } ); + assertEquals( 2, p.categoriesWithDescManyToMany.size() ); + checkIds( p.categoriesWithDescManyToMany, new Integer[] { 2, 4 } ); + assertEquals( 1, p.categoriesWithDescIdLt4ManyToMany.size() ); + checkIds( p.categoriesWithDescIdLt4ManyToMany, new Integer[] { 2 } ); + } ); } private void checkIds(Set categories, Integer[] expectedIds) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/LazyElementCollectionBasicNonUniqueIdWhereTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/LazyElementCollectionBasicNonUniqueIdWhereTest.java index 307c153dc525..f3d012a36d85 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/LazyElementCollectionBasicNonUniqueIdWhereTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/LazyElementCollectionBasicNonUniqueIdWhereTest.java @@ -4,6 +4,7 @@ */ package org.hibernate.orm.test.where.annotations; +import java.sql.Statement; import java.util.ArrayList; import java.util.HashSet; import java.util.List; @@ -17,178 +18,162 @@ import jakarta.persistence.Table; import org.hibernate.Hibernate; -import org.hibernate.Session; import org.hibernate.annotations.Immutable; import org.hibernate.annotations.SQLRestriction; +import org.hibernate.dialect.Dialect; 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.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Gail Badner */ +@SuppressWarnings("JUnitMalformedDeclaration") @RequiresDialect(H2Dialect.class) -public class LazyElementCollectionBasicNonUniqueIdWhereTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Material.class, Building.class }; +@DomainModel(annotatedClasses = { + LazyElementCollectionBasicNonUniqueIdWhereTest.Material.class, + LazyElementCollectionBasicNonUniqueIdWhereTest.Building.class +}) +@SessionFactory(exportSchema = false) +public class LazyElementCollectionBasicNonUniqueIdWhereTest { + + @BeforeAll + public void createSchema(SessionFactoryScope factoryScope) { + applySchema( factoryScope ); } - @Before - public void setup() { - Session session = openSession(); - session.beginTransaction(); - { - session.createNativeQuery( getDialect().getDropTableString( "MAIN_TABLE" ) ).executeUpdate(); - session.createNativeQuery( getDialect().getDropTableString( "COLLECTION_TABLE" ) ).executeUpdate(); - session.createNativeQuery( getDialect().getDropTableString( "MATERIAL_RATINGS" ) ).executeUpdate(); - - session.createNativeQuery( - "create table MAIN_TABLE( " + - "ID integer not null, NAME varchar(255) not null, CODE varchar(10) not null, " + - "primary key (ID, CODE) )" - ).executeUpdate(); - - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'plastic', 'MATERIAL' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'house', 'BUILDING' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'high', 'RATING' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 2, 'medium', 'RATING' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 3, 'low', 'RATING' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'small', 'SIZE' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 2, 'medium', 'SIZE' )" ) - .executeUpdate(); - - session.createNativeQuery( - "create table COLLECTION_TABLE( " + - "MAIN_ID integer not null, MAIN_CODE varchar(10) not null, " + - "VAL varchar(10) not null, VALUE_CODE varchar(10) not null, " + - "primary key (MAIN_ID, MAIN_CODE, VAL, VALUE_CODE))" - ).executeUpdate(); - - session.createNativeQuery( - "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, VAL, VALUE_CODE) " + - "VALUES( 1, 'MATERIAL', 'high', 'RATING' )" - ).executeUpdate(); - session.createNativeQuery( - "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, VAL, VALUE_CODE) " + - "VALUES( 1, 'MATERIAL', 'medium', 'RATING' )" - ).executeUpdate(); - session.createNativeQuery( - "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, VAL, VALUE_CODE) " + - "VALUES( 1, 'MATERIAL', 'low', 'RATING' )" - ).executeUpdate(); - - session.createNativeQuery( - "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, VAL, VALUE_CODE) " + - "VALUES( 1, 'MATERIAL', 'medium', 'SIZE' )" - ).executeUpdate(); - - session.createNativeQuery( - "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, VAL, VALUE_CODE) " + - "VALUES( 1, 'BUILDING', 'high', 'RATING' )" - ).executeUpdate(); - - session.createNativeQuery( - "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, VAL, VALUE_CODE) " + - "VALUES( 1, 'BUILDING', 'small', 'SIZE' )" - ).executeUpdate(); - - - session.createNativeQuery( - "create table MATERIAL_RATINGS( " + - "MATERIAL_ID integer not null, RATING varchar(10) not null," + - " primary key (MATERIAL_ID, RATING))" - ).executeUpdate(); - - session.createNativeQuery( - "insert into MATERIAL_RATINGS(MATERIAL_ID, RATING) VALUES( 1, 'high' )" - ).executeUpdate(); - - } - session.getTransaction().commit(); - session.close(); + public static void applySchema(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( session -> session.doWork( connection -> { + final Dialect dialect = session.getDialect(); + try ( final Statement statement = connection.createStatement() ) { + statement.executeUpdate( dialect.getDropTableString( "MAIN_TABLE" ) ); + statement.executeUpdate( dialect.getDropTableString( "COLLECTION_TABLE" ) ); + statement.executeUpdate( dialect.getDropTableString( "MATERIAL_RATINGS" ) ); + + // MAIN_TABLE + statement.executeUpdate(""" + create table MAIN_TABLE( + ID integer not null, + NAME varchar(255) not null, + CODE varchar(10) not null, + primary key (ID, CODE) + ) + """ ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'plastic', 'MATERIAL' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'house', 'BUILDING' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'high', 'RATING' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 2, 'medium', 'RATING' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 3, 'low', 'RATING' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'small', 'SIZE' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 2, 'medium', 'SIZE' )" ); + + // COLLECTION_TABLE + statement.executeUpdate( """ + create table COLLECTION_TABLE( + MAIN_ID integer not null, + MAIN_CODE varchar(10) not null, + VAL varchar(10) not null, + VALUE_CODE varchar(10) not null, + primary key (MAIN_ID, MAIN_CODE, VAL, VALUE_CODE) + ) + """ ); + statement.executeUpdate( + "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, VAL, VALUE_CODE) " + + "VALUES( 1, 'MATERIAL', 'high', 'RATING' )" + ); + statement.executeUpdate( + "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, VAL, VALUE_CODE) " + + "VALUES( 1, 'MATERIAL', 'medium', 'RATING' )" + ); + statement.executeUpdate( + "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, VAL, VALUE_CODE) " + + "VALUES( 1, 'MATERIAL', 'low', 'RATING' )" + ); + statement.executeUpdate( + "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, VAL, VALUE_CODE) " + + "VALUES( 1, 'MATERIAL', 'medium', 'SIZE' )" + ); + statement.executeUpdate( + "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, VAL, VALUE_CODE) " + + "VALUES( 1, 'BUILDING', 'high', 'RATING' )" + ); + statement.executeUpdate( + "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, VAL, VALUE_CODE) " + + "VALUES( 1, 'BUILDING', 'small', 'SIZE' )" + ); + + // MATERIAL_RATINGS + statement.executeUpdate( """ + create table MATERIAL_RATINGS( + MATERIAL_ID integer not null, + RATING varchar(10) not null, + primary key (MATERIAL_ID, RATING) + ) + """ ); + statement.executeUpdate( "insert into MATERIAL_RATINGS(MATERIAL_ID, RATING) VALUES( 1, 'high' )" ); + } + } ) ); } - @After - public void cleanup() { - Session session = openSession(); - session.beginTransaction(); - { - session.createNativeQuery( "delete from MATERIAL_RATINGS" ).executeUpdate(); - session.createNativeQuery( "delete from COLLECTION_TABLE" ).executeUpdate(); - session.createNativeQuery( "delete from MAIN_TABLE" ).executeUpdate(); - } - session.getTransaction().commit(); - session.close(); + @AfterAll + public void dropSchema(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test @JiraKey( value = "HHH-12937") - public void testInitializeFromUniqueAssociationTable() { - Session session = openSession(); - session.beginTransaction(); - { - Material material = session.get( Material.class, 1 ); - assertEquals( "plastic", material.getName() ); - - // Material#ratings is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( material.getRatings() ) ); - assertEquals( 1, material.getRatings().size() ); - assertTrue( Hibernate.isInitialized( material.getRatings() ) ); - - assertEquals( "high", material.getRatings().iterator().next() ); - } - session.getTransaction().commit(); - session.close(); + public void testInitializeFromUniqueAssociationTable(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + var material = session.find( Material.class, 1 ); + assertEquals( "plastic", material.getName() ); + + // Material#ratings is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( material.getRatings() ) ); + assertEquals( 1, material.getRatings().size() ); + assertTrue( Hibernate.isInitialized( material.getRatings() ) ); + + assertEquals( "high", material.getRatings().iterator().next() ); + } ); } @Test @JiraKey( value = "HHH-12937") - public void testInitializeFromNonUniqueAssociationTable() { - Session session = openSession(); - session.beginTransaction(); - { - Material material = session.get( Material.class, 1 ); - assertEquals( "plastic", material.getName() ); - - // Material#sizesFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( material.getSizesFromCombined() ) ); - assertEquals( 1, material.getSizesFromCombined().size() ); - assertTrue( Hibernate.isInitialized( material.getSizesFromCombined() ) ); - - assertEquals( "medium", material.getSizesFromCombined().iterator().next() ); - - Building building = session.get( Building.class, 1 ); - - // building.ratingsFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( building.getRatingsFromCombined() ) ); - assertEquals( 1, building.getRatingsFromCombined().size() ); - assertTrue( Hibernate.isInitialized( building.getRatingsFromCombined() ) ); - assertEquals( "high", building.getRatingsFromCombined().iterator().next() ); - - // Building#sizesFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( building.getSizesFromCombined() ) ); - assertEquals( 1, building.getSizesFromCombined().size() ); - assertTrue( Hibernate.isInitialized( building.getSizesFromCombined() ) ); - assertEquals( "small", building.getSizesFromCombined().iterator().next() ); - } - session.getTransaction().commit(); - session.close(); + public void testInitializeFromNonUniqueAssociationTable(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + Material material = session.find( Material.class, 1 ); + assertEquals( "plastic", material.getName() ); + + // Material#sizesFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( material.getSizesFromCombined() ) ); + assertEquals( 1, material.getSizesFromCombined().size() ); + assertTrue( Hibernate.isInitialized( material.getSizesFromCombined() ) ); + + assertEquals( "medium", material.getSizesFromCombined().iterator().next() ); + + Building building = session.find( Building.class, 1 ); + + // building.ratingsFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( building.getRatingsFromCombined() ) ); + assertEquals( 1, building.getRatingsFromCombined().size() ); + assertTrue( Hibernate.isInitialized( building.getRatingsFromCombined() ) ); + assertEquals( "high", building.getRatingsFromCombined().iterator().next() ); + + // Building#sizesFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( building.getSizesFromCombined() ) ); + assertEquals( 1, building.getSizesFromCombined().size() ); + assertTrue( Hibernate.isInitialized( building.getSizesFromCombined() ) ); + assertEquals( "small", building.getSizesFromCombined().iterator().next() ); + } ); } @Entity( name = "Material" ) @@ -305,6 +290,5 @@ public Set getRatingsFromCombined() { public void setRatingsFromCombined(Set ratingsFromCombined) { this.ratingsFromCombined = ratingsFromCombined; } - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/LazyElementCollectionWithLazyManyToOneNonUniqueIdWhereTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/LazyElementCollectionWithLazyManyToOneNonUniqueIdWhereTest.java index b1e83d2fc4d9..60ff021d0bc1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/LazyElementCollectionWithLazyManyToOneNonUniqueIdWhereTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/LazyElementCollectionWithLazyManyToOneNonUniqueIdWhereTest.java @@ -4,10 +4,6 @@ */ package org.hibernate.orm.test.where.annotations; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; import jakarta.persistence.AssociationOverride; import jakarta.persistence.AssociationOverrides; import jakarta.persistence.CollectionTable; @@ -20,188 +16,178 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; - import org.hibernate.Hibernate; -import org.hibernate.Session; import org.hibernate.annotations.Immutable; import org.hibernate.annotations.SQLRestriction; +import org.hibernate.dialect.Dialect; 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.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.sql.Statement; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Gail Badner */ +@SuppressWarnings("JUnitMalformedDeclaration") @RequiresDialect(H2Dialect.class) -public class LazyElementCollectionWithLazyManyToOneNonUniqueIdWhereTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Material.class, Building.class, Rating.class, Size.class }; +@DomainModel(annotatedClasses = { + LazyElementCollectionWithLazyManyToOneNonUniqueIdWhereTest.Material.class, + LazyElementCollectionWithLazyManyToOneNonUniqueIdWhereTest.Building.class, + LazyElementCollectionWithLazyManyToOneNonUniqueIdWhereTest.Rating.class, + LazyElementCollectionWithLazyManyToOneNonUniqueIdWhereTest.Size.class +}) +@SessionFactory(exportSchema = false) +public class LazyElementCollectionWithLazyManyToOneNonUniqueIdWhereTest { + @BeforeAll + public void createSchema(SessionFactoryScope factoryScope) { + applySchema( factoryScope ); } - @Before - public void setup() { - Session session = openSession(); - session.beginTransaction(); - { - session.createNativeQuery( getDialect().getDropTableString( "MAIN_TABLE" ) ).executeUpdate(); - session.createNativeQuery( getDialect().getDropTableString( "COLLECTION_TABLE" ) ).executeUpdate(); - session.createNativeQuery( getDialect().getDropTableString( "MATERIAL_RATINGS" ) ).executeUpdate(); - - session.createNativeQuery( - "create table MAIN_TABLE( " + - "ID integer not null, NAME varchar(255) not null, CODE varchar(10) not null, " + - "primary key (ID, CODE) )" - ).executeUpdate(); - - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'plastic', 'MATERIAL' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'house', 'BUILDING' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'high', 'RATING' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 2, 'medium', 'RATING' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 3, 'low', 'RATING' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'small', 'SIZE' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 2, 'medium', 'SIZE' )" ) - .executeUpdate(); - - session.createNativeQuery( - "create table COLLECTION_TABLE( " + - "MAIN_ID integer not null, MAIN_CODE varchar(10) not null, " + - "ASSOCIATION_ID int not null, ASSOCIATION_CODE varchar(10) not null, " + - "primary key (MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE))" - ).executeUpdate(); - - session.createNativeQuery( - "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'MATERIAL', 1, 'RATING' )" - ).executeUpdate(); - session.createNativeQuery( - "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'MATERIAL', 2, 'RATING' )" - ).executeUpdate(); - session.createNativeQuery( - "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'MATERIAL', 3, 'RATING' )" - ).executeUpdate(); - - session.createNativeQuery( - "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'MATERIAL', 2, 'SIZE' )" - ).executeUpdate(); - - session.createNativeQuery( - "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'BUILDING', 1, 'RATING' )" - ).executeUpdate(); - - session.createNativeQuery( - "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'BUILDING', 1, 'SIZE' )" - ).executeUpdate(); - - - session.createNativeQuery( - "create table MATERIAL_RATINGS( " + - "MATERIAL_ID integer not null, RATING_ID integer not null," + - " primary key (MATERIAL_ID, RATING_ID))" - ).executeUpdate(); - - session.createNativeQuery( - "insert into MATERIAL_RATINGS(MATERIAL_ID, RATING_ID) VALUES( 1, 1 )" - ).executeUpdate(); - } - session.getTransaction().commit(); - session.close(); + public static void applySchema(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( session -> session.doWork( connection -> { + final Dialect dialect = session.getDialect(); + try ( final Statement statement = connection.createStatement() ) { + statement.executeUpdate( dialect.getDropTableString( "MAIN_TABLE" ) ); + statement.executeUpdate( dialect.getDropTableString( "COLLECTION_TABLE" ) ); + statement.executeUpdate( dialect.getDropTableString( "MATERIAL_RATINGS" ) ); + + // MAIN_TABLE + statement.executeUpdate(""" + create table MAIN_TABLE( + ID integer not null, + NAME varchar(255) not null, + CODE varchar(10) not null, + primary key (ID, CODE) + ) + """ ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'plastic', 'MATERIAL' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'house', 'BUILDING' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'high', 'RATING' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 2, 'medium', 'RATING' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 3, 'low', 'RATING' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'small', 'SIZE' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 2, 'medium', 'SIZE' )" ); + + // COLLECTION_TABLE + statement.executeUpdate( """ + create table COLLECTION_TABLE( + MAIN_ID integer not null, + MAIN_CODE varchar(10) not null, + ASSOCIATION_ID int not null, + ASSOCIATION_CODE varchar(10) not null, + primary key (MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) + )""" ); + statement.executeUpdate( + "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + + "VALUES( 1, 'MATERIAL', 1, 'RATING' )" + ); + statement.executeUpdate( + "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + + "VALUES( 1, 'MATERIAL', 2, 'RATING' )" + ); + statement.executeUpdate( + "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + + "VALUES( 1, 'MATERIAL', 3, 'RATING' )" + ); + statement.executeUpdate( + "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + + "VALUES( 1, 'MATERIAL', 2, 'SIZE' )" + ); + statement.executeUpdate( + "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + + "VALUES( 1, 'BUILDING', 1, 'RATING' )" + ); + statement.executeUpdate( + "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + + "VALUES( 1, 'BUILDING', 1, 'SIZE' )" + ); + + // MATERIAL_RATINGS + statement.executeUpdate( """ + create table MATERIAL_RATINGS( + MATERIAL_ID integer not null, + RATING_ID integer not null, + primary key (MATERIAL_ID, RATING_ID) + ) + """ ); + statement.executeUpdate( "insert into MATERIAL_RATINGS(MATERIAL_ID, RATING_ID) VALUES( 1, 1 )" ); + } + } ) ); } - @After - public void cleanup() { - Session session = openSession(); - session.beginTransaction(); - { - session.createNativeQuery( "delete from MATERIAL_RATINGS" ).executeUpdate(); - session.createNativeQuery( "delete from COLLECTION_TABLE" ).executeUpdate(); - session.createNativeQuery( "delete from MAIN_TABLE" ).executeUpdate(); - } - session.getTransaction().commit(); - session.close(); + @AfterAll + public void dropSchema(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test @JiraKey( value = "HHH-12937") - public void testInitializeFromUniqueAssociationTable() { - Session session = openSession(); - session.beginTransaction(); - { - Material material = session.get( Material.class, 1 ); - assertEquals( "plastic", material.getName() ); - - // Material#ratings is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( material.getContainedRatings() ) ); - assertEquals( 1, material.getContainedRatings().size() ); - assertTrue( Hibernate.isInitialized( material.getContainedRatings() ) ); - - final ContainedRating containedRating = material.getContainedRatings().iterator().next(); - assertTrue( Hibernate.isInitialized( containedRating ) ); - assertEquals( "high", containedRating.getRating().getName() ); - - } - session.getTransaction().commit(); - session.close(); + public void testInitializeFromUniqueAssociationTable(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + var material = session.find( Material.class, 1 ); + assertEquals( "plastic", material.getName() ); + + // Material#ratings is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( material.getContainedRatings() ) ); + assertEquals( 1, material.getContainedRatings().size() ); + assertTrue( Hibernate.isInitialized( material.getContainedRatings() ) ); + + var containedRating = material.getContainedRatings().iterator().next(); + assertTrue( Hibernate.isInitialized( containedRating ) ); + assertEquals( "high", containedRating.getRating().getName() ); + } ); } @Test @JiraKey( value = "HHH-12937") - public void testInitializeFromNonUniqueAssociationTable() { - Session session = openSession(); - session.beginTransaction(); - { - Material material = session.get( Material.class, 1 ); - assertEquals( "plastic", material.getName() ); - - // Material#containedSizesFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( material.getContainedSizesFromCombined() ) ); - assertEquals( 1, material.getContainedSizesFromCombined().size() ); - assertTrue( Hibernate.isInitialized( material.getContainedSizesFromCombined() ) ); - - ContainedSize containedSize = material.getContainedSizesFromCombined().iterator().next(); - assertFalse( Hibernate.isInitialized( containedSize.getSize() ) ); - assertEquals( "medium", containedSize.getSize().getName() ); - - Building building = session.get( Building.class, 1 ); - - // building.ratingsFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( building.getContainedRatingsFromCombined() ) ); - assertEquals( 1, building.getContainedRatingsFromCombined().size() ); - assertTrue( Hibernate.isInitialized( building.getContainedRatingsFromCombined() ) ); - ContainedRating containedRating = building.getContainedRatingsFromCombined().iterator().next(); - assertFalse( Hibernate.isInitialized( containedRating.getRating() ) ); - assertEquals( "high", containedRating.getRating().getName() ); - - // Building#containedSizesFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( building.getContainedSizesFromCombined() ) ); - assertEquals( 1, building.getContainedSizesFromCombined().size() ); - assertTrue( Hibernate.isInitialized( building.getContainedSizesFromCombined() ) ); - containedSize = building.getContainedSizesFromCombined().iterator().next(); - assertFalse( Hibernate.isInitialized( containedSize.getSize() ) ); - assertEquals( "small", containedSize.getSize().getName() ); - } - session.getTransaction().commit(); - session.close(); + public void testInitializeFromNonUniqueAssociationTable(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + var material = session.find( Material.class, 1 ); + assertEquals( "plastic", material.getName() ); + + // Material#containedSizesFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( material.getContainedSizesFromCombined() ) ); + assertEquals( 1, material.getContainedSizesFromCombined().size() ); + assertTrue( Hibernate.isInitialized( material.getContainedSizesFromCombined() ) ); + + var containedSize = material.getContainedSizesFromCombined().iterator().next(); + assertFalse( Hibernate.isInitialized( containedSize.getSize() ) ); + assertEquals( "medium", containedSize.getSize().getName() ); + + var building = session.find( Building.class, 1 ); + + // building.ratingsFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( building.getContainedRatingsFromCombined() ) ); + assertEquals( 1, building.getContainedRatingsFromCombined().size() ); + assertTrue( Hibernate.isInitialized( building.getContainedRatingsFromCombined() ) ); + + var containedRating = building.getContainedRatingsFromCombined().iterator().next(); + assertFalse( Hibernate.isInitialized( containedRating.getRating() ) ); + assertEquals( "high", containedRating.getRating().getName() ); + + // Building#containedSizesFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( building.getContainedSizesFromCombined() ) ); + assertEquals( 1, building.getContainedSizesFromCombined().size() ); + assertTrue( Hibernate.isInitialized( building.getContainedSizesFromCombined() ) ); + containedSize = building.getContainedSizesFromCombined().iterator().next(); + assertFalse( Hibernate.isInitialized( containedSize.getSize() ) ); + assertEquals( "small", containedSize.getSize().getName() ); + } ); } @Entity( name = "Material" ) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/LazyManyToManyNonUniqueIdWhereTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/LazyManyToManyNonUniqueIdWhereTest.java index 614b79059e54..62aff4537c54 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/LazyManyToManyNonUniqueIdWhereTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/LazyManyToManyNonUniqueIdWhereTest.java @@ -4,12 +4,6 @@ */ package org.hibernate.orm.test.where.annotations; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; @@ -17,231 +11,186 @@ import jakarta.persistence.JoinTable; import jakarta.persistence.ManyToMany; import jakarta.persistence.Table; - import org.hibernate.Hibernate; import org.hibernate.annotations.Immutable; import org.hibernate.annotations.SQLJoinTableRestriction; import org.hibernate.annotations.SQLRestriction; -import org.hibernate.cfg.Configuration; -import org.hibernate.metamodel.CollectionClassification; - +import org.hibernate.dialect.Dialect; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.hibernate.cfg.AvailableSettings.DEFAULT_LIST_SEMANTICS; -import static org.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.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.sql.Statement; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Gail Badner */ -public class LazyManyToManyNonUniqueIdWhereTest extends BaseCoreFunctionalTestCase { - - protected Class[] getAnnotatedClasses() { - return new Class[] { Material.class, Building.class, Rating.class, Size.class }; - } - - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - configuration.setProperty( DEFAULT_LIST_SEMANTICS, CollectionClassification.BAG ); +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(annotatedClasses = { + LazyManyToManyNonUniqueIdWhereTest.Material.class, + LazyManyToManyNonUniqueIdWhereTest.Building.class, + LazyManyToManyNonUniqueIdWhereTest.Rating.class, + LazyManyToManyNonUniqueIdWhereTest.Size.class +}) +@SessionFactory(exportSchema = false) +public class LazyManyToManyNonUniqueIdWhereTest { + @BeforeAll + public void createSchema(SessionFactoryScope factoryScope) { + applySchema( factoryScope ); } - @Before - public void setup() { - doInHibernate( - this::sessionFactory, session -> { - - session.createNativeQuery( getDialect().getDropTableString( "MATERIAL_RATINGS" )).executeUpdate(); - session.createNativeQuery( getDialect().getDropTableString( "BUILDING_RATINGS" )).executeUpdate(); - session.createNativeQuery( getDialect().getDropTableString( "ASSOCIATION_TABLE" )).executeUpdate(); - session.createNativeQuery( getDialect().getDropTableString( "MAIN_TABLE" )).executeUpdate(); - } - ); - - doInHibernate( - this::sessionFactory, session -> { - - session.createNativeQuery( - "create table MAIN_TABLE( " + - "ID integer not null, NAME varchar(255) not null, CODE varchar(10) not null, " + - "primary key (ID, CODE) )" - ).executeUpdate(); - - session.createNativeQuery( - "create table ASSOCIATION_TABLE( " + - "MAIN_ID integer not null, MAIN_CODE varchar(10) not null, " + - "ASSOCIATION_ID int not null, ASSOCIATION_CODE varchar(10) not null, " + - "primary key (MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE))" - ).executeUpdate(); - - session.createNativeQuery( - "create table MATERIAL_RATINGS( " + - "MATERIAL_ID integer not null, RATING_ID integer not null," + - " primary key (MATERIAL_ID, RATING_ID))" - ).executeUpdate(); - - session.createNativeQuery( - "create table BUILDING_RATINGS( " + - "BUILDING_ID integer not null, RATING_ID integer not null," + - " primary key (BUILDING_ID, RATING_ID))" - ).executeUpdate(); - } - ); - - doInHibernate( - this::sessionFactory, session -> { - - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'plastic', 'MATERIAL' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'house', 'BUILDING' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'high', 'RATING' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 2, 'medium', 'RATING' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 3, 'low', 'RATING' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'small', 'SIZE' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 2, 'medium', 'SIZE' )" ) - .executeUpdate(); - - session.createNativeQuery( - "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'MATERIAL', 1, 'RATING' )" - ).executeUpdate(); - session.createNativeQuery( - "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'MATERIAL', 2, 'RATING' )" - ).executeUpdate(); - session.createNativeQuery( - "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'MATERIAL', 3, 'RATING' )" - ).executeUpdate(); - - session.createNativeQuery( - "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'MATERIAL', 2, 'SIZE' )" - ).executeUpdate(); - - session.createNativeQuery( - "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'BUILDING', 1, 'RATING' )" - ).executeUpdate(); - - session.createNativeQuery( - "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'BUILDING', 1, 'SIZE' )" - ).executeUpdate(); - - session.createNativeQuery( - "insert into MATERIAL_RATINGS(MATERIAL_ID, RATING_ID) VALUES( 1, 1 )" - ).executeUpdate(); - - session.createNativeQuery( - "insert into BUILDING_RATINGS(BUILDING_ID, RATING_ID) VALUES( 1, 1 )" - ).executeUpdate(); - session.createNativeQuery( - "insert into BUILDING_RATINGS(BUILDING_ID, RATING_ID) VALUES( 1, 2 )" - ).executeUpdate(); - session.createNativeQuery( - "insert into BUILDING_RATINGS(BUILDING_ID, RATING_ID) VALUES( 1, 3 )" - ).executeUpdate(); - } - ); + public static void applySchema(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( session -> session.doWork( connection -> { + final Dialect dialect = session.getDialect(); + try ( final Statement statement = connection.createStatement() ) { + statement.executeUpdate( dialect.getDropTableString( "MAIN_TABLE" ) ); + statement.executeUpdate( dialect.getDropTableString( "BUILDING_RATINGS" ) ); + statement.executeUpdate( dialect.getDropTableString( "ASSOCIATION_TABLE" ) ); + statement.executeUpdate( dialect.getDropTableString( "MATERIAL_RATINGS" ) ); + + statement.executeUpdate( """ + create table MAIN_TABLE( + ID integer not null, + NAME varchar(255) not null, + CODE varchar(10) not null, + primary key (ID, CODE) + )""" ); + statement.executeUpdate( """ + create table ASSOCIATION_TABLE( + MAIN_ID integer not null, + MAIN_CODE varchar(10) not null, + ASSOCIATION_ID int not null, + ASSOCIATION_CODE varchar(10) not null, + primary key (MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) + )""" ); + statement.executeUpdate(""" + create table MATERIAL_RATINGS( + MATERIAL_ID integer not null, + RATING_ID integer not null, + primary key (MATERIAL_ID, RATING_ID) + )""" ); + statement.executeUpdate( """ + create table BUILDING_RATINGS( + BUILDING_ID integer not null, + RATING_ID integer not null, + primary key (BUILDING_ID, RATING_ID) + )""" ); + + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'plastic', 'MATERIAL' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'house', 'BUILDING' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'high', 'RATING' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 2, 'medium', 'RATING' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 3, 'low', 'RATING' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'small', 'SIZE' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 2, 'medium', 'SIZE' )" ); + + statement.executeUpdate( "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + + "VALUES( 1, 'MATERIAL', 1, 'RATING' )" ); + statement.executeUpdate( "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + + "VALUES( 1, 'MATERIAL', 2, 'RATING' )" ); + statement.executeUpdate( "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + + "VALUES( 1, 'MATERIAL', 3, 'RATING' )" ); + statement.executeUpdate( "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + + "VALUES( 1, 'MATERIAL', 2, 'SIZE' )" ); + statement.executeUpdate( "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + + "VALUES( 1, 'BUILDING', 1, 'RATING' )" ); + statement.executeUpdate( "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + + "VALUES( 1, 'BUILDING', 1, 'SIZE' )" ); + + statement.executeUpdate( "insert into MATERIAL_RATINGS(MATERIAL_ID, RATING_ID) VALUES( 1, 1 )" ); + + statement.executeUpdate( "insert into BUILDING_RATINGS(BUILDING_ID, RATING_ID) VALUES( 1, 1 )" ); + statement.executeUpdate( "insert into BUILDING_RATINGS(BUILDING_ID, RATING_ID) VALUES( 1, 2 )" ); + statement.executeUpdate( "insert into BUILDING_RATINGS(BUILDING_ID, RATING_ID) VALUES( 1, 3 )" ); + } + } ) ); } - @After - public void cleanup() { - doInHibernate( - this::sessionFactory, session -> { - session.createNativeQuery( "delete from MATERIAL_RATINGS" ).executeUpdate(); - session.createNativeQuery( "delete from BUILDING_RATINGS" ).executeUpdate(); - session.createNativeQuery( "delete from ASSOCIATION_TABLE" ).executeUpdate(); - session.createNativeQuery( "delete from MAIN_TABLE" ).executeUpdate(); - } - ); + @AfterAll + public void dropSchema(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test @JiraKey( value = "HHH-12875") - public void testInitializeFromUniqueAssociationTable() { - doInHibernate( - this::sessionFactory, session -> { - - Material material = session.get( Material.class, 1 ); - assertEquals( "plastic", material.getName() ); - - // Material#ratings is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( material.getRatings() ) ); - assertEquals( 1, material.getRatings().size() ); - assertTrue( Hibernate.isInitialized( material.getRatings() ) ); - - final Rating rating = material.getRatings().iterator().next(); - assertEquals( "high", rating.getName() ); - - Building building = session.get( Building.class, 1 ); - assertEquals( "house", building.getName() ); - - // Building#ratings is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( building.getMediumOrHighRatings() ) ); - checkMediumOrHighRatings( building.getMediumOrHighRatings() ); - } - ); + public void testInitializeFromUniqueAssociationTable(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + var material = session.find( Material.class, 1 ); + assertEquals( "plastic", material.getName() ); + + // Material#ratings is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( material.getRatings() ) ); + assertEquals( 1, material.getRatings().size() ); + assertTrue( Hibernate.isInitialized( material.getRatings() ) ); + + final Rating rating = material.getRatings().iterator().next(); + assertEquals( "high", rating.getName() ); + + var building = session.find( Building.class, 1 ); + assertEquals( "house", building.getName() ); + + // Building#ratings is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( building.getMediumOrHighRatings() ) ); + checkMediumOrHighRatings( building.getMediumOrHighRatings() ); + } ); } @Test @JiraKey( value = "HHH-12875") - public void testInitializeFromNonUniqueAssociationTable() { - doInHibernate( - this::sessionFactory, session -> { - - Material material = session.get( Material.class, 1 ); - assertEquals( "plastic", material.getName() ); - - // Material#mediumOrHighRatingsFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( material.getMediumOrHighRatingsFromCombined() ) ); - checkMediumOrHighRatings( material.getMediumOrHighRatingsFromCombined() ); - Rating highRating = null; - for ( Rating rating : material.getMediumOrHighRatingsFromCombined() ) { - if ( "high".equals( rating.getName() ) ) { - highRating = rating; - } - } - assertNotNull( highRating ); - - // Material#sizesFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( material.getSizesFromCombined() ) ); - assertEquals( 1, material.getSizesFromCombined().size() ); - assertTrue( Hibernate.isInitialized( material.getSizesFromCombined() ) ); - - final Size size = material.getSizesFromCombined().iterator().next(); - assertEquals( "medium", size.getName() ); - - Building building = session.get( Building.class, 1 ); - - // building.ratingsFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( building.getRatingsFromCombined() ) ); - assertEquals( 1, building.getRatingsFromCombined().size() ); - assertTrue( Hibernate.isInitialized( building.getRatingsFromCombined() ) ); - assertSame( highRating, building.getRatingsFromCombined().iterator().next() ); - - // Building#sizesFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( building.getSizesFromCombined() ) ); - assertEquals( 1, building.getSizesFromCombined().size() ); - assertTrue( Hibernate.isInitialized( building.getSizesFromCombined() ) ); - assertEquals( "small", building.getSizesFromCombined().iterator().next().getName() ); + public void testInitializeFromNonUniqueAssociationTable(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + var material = session.find( Material.class, 1 ); + assertEquals( "plastic", material.getName() ); + + // Material#mediumOrHighRatingsFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( material.getMediumOrHighRatingsFromCombined() ) ); + checkMediumOrHighRatings( material.getMediumOrHighRatingsFromCombined() ); + Rating highRating = null; + for ( Rating rating : material.getMediumOrHighRatingsFromCombined() ) { + if ( "high".equals( rating.getName() ) ) { + highRating = rating; } - ); + } + assertNotNull( highRating ); + + // Material#sizesFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( material.getSizesFromCombined() ) ); + assertEquals( 1, material.getSizesFromCombined().size() ); + assertTrue( Hibernate.isInitialized( material.getSizesFromCombined() ) ); + + final Size size = material.getSizesFromCombined().iterator().next(); + assertEquals( "medium", size.getName() ); + + var building = session.find( Building.class, 1 ); + + // building.ratingsFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( building.getRatingsFromCombined() ) ); + assertEquals( 1, building.getRatingsFromCombined().size() ); + assertTrue( Hibernate.isInitialized( building.getRatingsFromCombined() ) ); + assertSame( highRating, building.getRatingsFromCombined().iterator().next() ); + + // Building#sizesFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( building.getSizesFromCombined() ) ); + assertEquals( 1, building.getSizesFromCombined().size() ); + assertTrue( Hibernate.isInitialized( building.getSizesFromCombined() ) ); + assertEquals( "small", building.getSizesFromCombined().iterator().next().getName() ); + } ); } private void checkMediumOrHighRatings(List mediumOrHighRatings) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/LazyOneToManyNonUniqueIdWhereTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/LazyOneToManyNonUniqueIdWhereTest.java index 2cfcb7b5e426..82924e0f525a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/LazyOneToManyNonUniqueIdWhereTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/LazyOneToManyNonUniqueIdWhereTest.java @@ -4,153 +4,125 @@ */ package org.hibernate.orm.test.where.annotations; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; - import org.hibernate.Hibernate; import org.hibernate.annotations.Immutable; import org.hibernate.annotations.SQLRestriction; -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.After; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.hibernate.cfg.AvailableSettings.DEFAULT_LIST_SEMANTICS; -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.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Gail Badner */ -public class LazyOneToManyNonUniqueIdWhereTest extends BaseCoreFunctionalTestCase { - - protected Class[] getAnnotatedClasses() { - return new Class[] { Material.class, Building.class, Rating.class, Size.class }; - } - - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - configuration.setProperty( DEFAULT_LIST_SEMANTICS, CollectionClassification.BAG ); - } - - @Before - public void setup() { - doInHibernate( - this::sessionFactory, session -> { - - session.createNativeQuery( getDialect().getDropTableString( "MAIN_TABLE" )).executeUpdate(); - } - ); - - doInHibernate( - this::sessionFactory, session -> { - - session.createNativeQuery( - "create table MAIN_TABLE( " + - "ID integer not null, NAME varchar(255) not null, CODE varchar(10) not null, " + - "MATERIAL_OWNER_ID integer, BUILDING_OWNER_ID integer, " + - "primary key (ID, CODE) )" - ).executeUpdate(); - } - ); - - doInHibernate( - this::sessionFactory, session -> { - - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'plastic', 'MATERIAL' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'house', 'BUILDING' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE, MATERIAL_OWNER_ID, BUILDING_OWNER_ID) " + - "VALUES( 1, 'high', 'RATING', 1, 1 )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE, MATERIAL_OWNER_ID, BUILDING_OWNER_ID) " + - "VALUES( 2, 'medium', 'RATING', 1, null )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE, MATERIAL_OWNER_ID, BUILDING_OWNER_ID) " + - "VALUES( 3, 'low', 'RATING', 1, null )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE, MATERIAL_OWNER_ID, BUILDING_OWNER_ID) " + - "VALUES( 1, 'small', 'SIZE', null, 1 )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE, MATERIAL_OWNER_ID, BUILDING_OWNER_ID) " + - "VALUES( 2, 'medium', 'SIZE', 1, null )" ) - .executeUpdate(); - } - ); +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(annotatedClasses = { + LazyOneToManyNonUniqueIdWhereTest.Material.class, + LazyOneToManyNonUniqueIdWhereTest.Building.class, + LazyOneToManyNonUniqueIdWhereTest.Rating.class, + LazyOneToManyNonUniqueIdWhereTest.Size.class +}) +@SessionFactory(exportSchema = false) +public class LazyOneToManyNonUniqueIdWhereTest { + @BeforeEach + void createSchema(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( session -> session.doWork( connection -> { + var dialect = session.getDialect(); + try ( Statement statement = connection.createStatement() ) { + statement.executeUpdate( dialect.getDropTableString( "MAIN_TABLE" ) ); + statement.executeUpdate( """ + create table MAIN_TABLE( + ID integer not null, + NAME varchar(255) not null, + CODE varchar(10) not null, + MATERIAL_OWNER_ID integer, + BUILDING_OWNER_ID integer, + primary key (ID, CODE) + )""" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'plastic', 'MATERIAL' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'house', 'BUILDING' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE, MATERIAL_OWNER_ID, BUILDING_OWNER_ID) " + + "VALUES( 1, 'high', 'RATING', 1, 1 )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE, MATERIAL_OWNER_ID, BUILDING_OWNER_ID) " + + "VALUES( 2, 'medium', 'RATING', 1, null )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE, MATERIAL_OWNER_ID, BUILDING_OWNER_ID) " + + "VALUES( 3, 'low', 'RATING', 1, null )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE, MATERIAL_OWNER_ID, BUILDING_OWNER_ID) " + + "VALUES( 1, 'small', 'SIZE', null, 1 )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE, MATERIAL_OWNER_ID, BUILDING_OWNER_ID) " + + "VALUES( 2, 'medium', 'SIZE', 1, null )" ); + } + } ) ); } - @After - public void cleanup() { - doInHibernate( - this::sessionFactory, session -> { - session.createNativeQuery( "delete from MAIN_TABLE" ).executeUpdate(); - } - ); + @AfterAll + public void dropSchema(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test @JiraKey( value = "HHH-12875") - public void testInitializeFromNonUniqueAssociationTable() { - doInHibernate( - this::sessionFactory, session -> { - - Material material = session.get( Material.class, 1 ); - assertEquals( "plastic", material.getName() ); - - // Material#mediumOrHighRatingsFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( material.getMediumOrHighRatingsFromCombined() ) ); - checkMediumOrHighRatings( material.getMediumOrHighRatingsFromCombined() ); - Rating highRating = null; - for ( Rating rating : material.getMediumOrHighRatingsFromCombined() ) { - if ( "high".equals( rating.getName() ) ) { - highRating = rating; - } - } - assertNotNull( highRating ); - - // Material#sizesFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( material.getSizesFromCombined() ) ); - assertEquals( 1, material.getSizesFromCombined().size() ); - assertTrue( Hibernate.isInitialized( material.getSizesFromCombined() ) ); - - final Size size = material.getSizesFromCombined().iterator().next(); - assertEquals( "medium", size.getName() ); - - Building building = session.get( Building.class, 1 ); - - // building.ratingsFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( building.getRatingsFromCombined() ) ); - assertEquals( 1, building.getRatingsFromCombined().size() ); - assertTrue( Hibernate.isInitialized( building.getRatingsFromCombined() ) ); - assertSame( highRating, building.getRatingsFromCombined().iterator().next() ); - - // Building#sizesFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( building.getSizesFromCombined() ) ); - assertEquals( 1, building.getSizesFromCombined().size() ); - assertTrue( Hibernate.isInitialized( building.getSizesFromCombined() ) ); - assertEquals( "small", building.getSizesFromCombined().iterator().next().getName() ); + public void testInitializeFromNonUniqueAssociationTable(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + Material material = session.find( Material.class, 1 ); + assertEquals( "plastic", material.getName() ); + + // Material#mediumOrHighRatingsFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( material.getMediumOrHighRatingsFromCombined() ) ); + checkMediumOrHighRatings( material.getMediumOrHighRatingsFromCombined() ); + Rating highRating = null; + for ( Rating rating : material.getMediumOrHighRatingsFromCombined() ) { + if ( "high".equals( rating.getName() ) ) { + highRating = rating; } - ); + } + assertNotNull( highRating ); + + // Material#sizesFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( material.getSizesFromCombined() ) ); + assertEquals( 1, material.getSizesFromCombined().size() ); + assertTrue( Hibernate.isInitialized( material.getSizesFromCombined() ) ); + + final Size size = material.getSizesFromCombined().iterator().next(); + assertEquals( "medium", size.getName() ); + + Building building = session.get( Building.class, 1 ); + + // building.ratingsFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( building.getRatingsFromCombined() ) ); + assertEquals( 1, building.getRatingsFromCombined().size() ); + assertTrue( Hibernate.isInitialized( building.getRatingsFromCombined() ) ); + assertSame( highRating, building.getRatingsFromCombined().iterator().next() ); + + // Building#sizesFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( building.getSizesFromCombined() ) ); + assertEquals( 1, building.getSizesFromCombined().size() ); + assertTrue( Hibernate.isInitialized( building.getSizesFromCombined() ) ); + assertEquals( "small", building.getSizesFromCombined().iterator().next().getName() ); + } ); } private void checkMediumOrHighRatings(List mediumOrHighRatings) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/LazyToManyWhereTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/LazyToManyWhereTest.java index 90f186335168..eea91bf0dae8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/LazyToManyWhereTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/LazyToManyWhereTest.java @@ -4,9 +4,6 @@ */ package org.hibernate.orm.test.where.annotations; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; @@ -16,19 +13,24 @@ import jakarta.persistence.ManyToMany; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; - import org.hibernate.annotations.SQLJoinTableRestriction; import org.hibernate.annotations.SQLRestriction; - +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; /** * Tests association collections with default AvailableSettings.USE_ENTITY_WHERE_CLAUSE_FOR_COLLECTIONS, @@ -36,19 +38,20 @@ * * @author Gail Badner */ -public class LazyToManyWhereTest extends BaseNonConfigCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Product.class, Category.class }; +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(annotatedClasses = { LazyToManyWhereTest.Product.class, LazyToManyWhereTest.Category.class }) +@SessionFactory +public class LazyToManyWhereTest { + @AfterEach + public void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test @JiraKey( value = "HHH-13011" ) - public void testAssociatedWhereClause() { - - Product product = new Product(); - Category flowers = new Category(); + public void testAssociatedWhereClause(SessionFactoryScope factoryScope) { + var product = new Product(); + var flowers = new Category(); flowers.id = 1; flowers.name = "flowers"; flowers.description = "FLOWERS"; @@ -57,7 +60,7 @@ public void testAssociatedWhereClause() { product.categoriesManyToMany.add( flowers ); product.categoriesWithDescManyToMany.add( flowers ); product.categoriesWithDescIdLt4ManyToMany.add( flowers ); - Category vegetables = new Category(); + var vegetables = new Category(); vegetables.id = 2; vegetables.name = "vegetables"; vegetables.description = "VEGETABLES"; @@ -66,7 +69,7 @@ public void testAssociatedWhereClause() { product.categoriesManyToMany.add( vegetables ); product.categoriesWithDescManyToMany.add( vegetables ); product.categoriesWithDescIdLt4ManyToMany.add( vegetables ); - Category dogs = new Category(); + var dogs = new Category(); dogs.id = 3; dogs.name = "dogs"; dogs.description = null; @@ -75,7 +78,7 @@ public void testAssociatedWhereClause() { product.categoriesManyToMany.add( dogs ); product.categoriesWithDescManyToMany.add( dogs ); product.categoriesWithDescIdLt4ManyToMany.add( dogs ); - Category building = new Category(); + var building = new Category(); building.id = 4; building.name = "building"; building.description = "BUILDING"; @@ -85,69 +88,54 @@ public void testAssociatedWhereClause() { product.categoriesWithDescManyToMany.add( building ); product.categoriesWithDescIdLt4ManyToMany.add( building ); - doInHibernate( - this::sessionFactory, - session -> { - session.persist( flowers ); - session.persist( vegetables ); - session.persist( dogs ); - session.persist( building ); - session.persist( product ); - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Product p = session.get( Product.class, product.id ); - assertNotNull( p ); - assertEquals( 4, p.categoriesOneToMany.size() ); - checkIds( p.categoriesOneToMany, new Integer[] { 1, 2, 3, 4 } ); - assertEquals( 3, p.categoriesWithDescOneToMany.size() ); - checkIds( p.categoriesWithDescOneToMany, new Integer[] { 1, 2, 4 } ); - assertEquals( 4, p.categoriesManyToMany.size() ); - checkIds( p.categoriesManyToMany, new Integer[] { 1, 2, 3, 4 } ); - assertEquals( 3, p.categoriesWithDescManyToMany.size() ); - checkIds( p.categoriesWithDescManyToMany, new Integer[] { 1, 2, 4 } ); - assertEquals( 2, p.categoriesWithDescIdLt4ManyToMany.size() ); - checkIds( p.categoriesWithDescIdLt4ManyToMany, new Integer[] { 1, 2 } ); - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Category c = session.get( Category.class, flowers.id ); - assertNotNull( c ); - c.inactive = 1; - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Category c = session.get( Category.class, flowers.id ); - assertNull( c ); - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Product p = session.get( Product.class, product.id ); - assertNotNull( p ); - assertEquals( 3, p.categoriesOneToMany.size() ); - checkIds( p.categoriesOneToMany, new Integer[] { 2, 3, 4 } ); - assertEquals( 2, p.categoriesWithDescOneToMany.size() ); - checkIds( p.categoriesWithDescOneToMany, new Integer[] { 2, 4 } ); - assertEquals( 3, p.categoriesManyToMany.size() ); - checkIds( p.categoriesManyToMany, new Integer[] { 2, 3, 4 } ); - assertEquals( 2, p.categoriesWithDescManyToMany.size() ); - checkIds( p.categoriesWithDescManyToMany, new Integer[] { 2, 4 } ); - assertEquals( 1, p.categoriesWithDescIdLt4ManyToMany.size() ); - checkIds( p.categoriesWithDescIdLt4ManyToMany, new Integer[] { 2 } ); - } - ); + factoryScope.inTransaction( (session) -> { + session.persist( flowers ); + session.persist( vegetables ); + session.persist( dogs ); + session.persist( building ); + session.persist( product ); + } ); + + factoryScope.inTransaction( (session) -> { + var p = session.find( Product.class, product.id ); + assertNotNull( p ); + assertEquals( 4, p.categoriesOneToMany.size() ); + checkIds( p.categoriesOneToMany, new Integer[] { 1, 2, 3, 4 } ); + assertEquals( 3, p.categoriesWithDescOneToMany.size() ); + checkIds( p.categoriesWithDescOneToMany, new Integer[] { 1, 2, 4 } ); + assertEquals( 4, p.categoriesManyToMany.size() ); + checkIds( p.categoriesManyToMany, new Integer[] { 1, 2, 3, 4 } ); + assertEquals( 3, p.categoriesWithDescManyToMany.size() ); + checkIds( p.categoriesWithDescManyToMany, new Integer[] { 1, 2, 4 } ); + assertEquals( 2, p.categoriesWithDescIdLt4ManyToMany.size() ); + checkIds( p.categoriesWithDescIdLt4ManyToMany, new Integer[] { 1, 2 } ); + } ); + + factoryScope.inTransaction( (session) -> { + var c = session.find( Category.class, flowers.id ); + assertNotNull( c ); + c.inactive = 1; + } ); + + factoryScope.inTransaction( (session) -> { + var c = session.find( Category.class, flowers.id ); + assertNull( c ); + } ); + + factoryScope.inTransaction( (session) -> { + Product p = session.find( Product.class, product.id ); + assertNotNull( p ); + assertEquals( 3, p.categoriesOneToMany.size() ); + checkIds( p.categoriesOneToMany, new Integer[] { 2, 3, 4 } ); + assertEquals( 2, p.categoriesWithDescOneToMany.size() ); + checkIds( p.categoriesWithDescOneToMany, new Integer[] { 2, 4 } ); + assertEquals( 3, p.categoriesManyToMany.size() ); + checkIds( p.categoriesManyToMany, new Integer[] { 2, 3, 4 } ); + assertEquals( 2, p.categoriesWithDescManyToMany.size() ); + checkIds( p.categoriesWithDescManyToMany, new Integer[] { 2, 4 } ); + assertEquals( 1, p.categoriesWithDescIdLt4ManyToMany.size() ); + checkIds( p.categoriesWithDescIdLt4ManyToMany, new Integer[] { 2 } ); + } ); } private void checkIds(Set categories, Integer[] expectedIds) { @@ -201,5 +189,9 @@ public static class Category { private String description; private int inactive; + + public int getId() { + return id; + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/LazyToManyWhereUseClassWhereTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/LazyToManyWhereUseClassWhereTest.java index e1811b6913ac..7bb4779a3f5c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/LazyToManyWhereUseClassWhereTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/LazyToManyWhereUseClassWhereTest.java @@ -11,9 +11,9 @@ import org.hibernate.annotations.SQLJoinTableRestriction; import org.hibernate.annotations.SQLRestriction; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; @@ -24,29 +24,32 @@ import jakarta.persistence.ManyToMany; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Gail Badner */ -public class LazyToManyWhereUseClassWhereTest extends BaseNonConfigCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Product.class, Category.class }; +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(annotatedClasses = { LazyToManyWhereUseClassWhereTest.Product.class, LazyToManyWhereUseClassWhereTest.Category.class }) +@SessionFactory +public class LazyToManyWhereUseClassWhereTest { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test @JiraKey( "HHH-13011" ) - public void testAssociatedWhereClause() { - - Product product = new Product(); - Category flowers = new Category(); + public void testAssociatedWhereClause(SessionFactoryScope factoryScope) { + var product = new Product(); + var flowers = new Category(); flowers.id = 1; flowers.name = "flowers"; flowers.description = "FLOWERS"; @@ -55,7 +58,7 @@ public void testAssociatedWhereClause() { product.categoriesManyToMany.add( flowers ); product.categoriesWithDescManyToMany.add( flowers ); product.categoriesWithDescIdLt4ManyToMany.add( flowers ); - Category vegetables = new Category(); + var vegetables = new Category(); vegetables.id = 2; vegetables.name = "vegetables"; vegetables.description = "VEGETABLES"; @@ -64,7 +67,7 @@ public void testAssociatedWhereClause() { product.categoriesManyToMany.add( vegetables ); product.categoriesWithDescManyToMany.add( vegetables ); product.categoriesWithDescIdLt4ManyToMany.add( vegetables ); - Category dogs = new Category(); + var dogs = new Category(); dogs.id = 3; dogs.name = "dogs"; dogs.description = null; @@ -73,7 +76,7 @@ public void testAssociatedWhereClause() { product.categoriesManyToMany.add( dogs ); product.categoriesWithDescManyToMany.add( dogs ); product.categoriesWithDescIdLt4ManyToMany.add( dogs ); - Category building = new Category(); + var building = new Category(); building.id = 4; building.name = "building"; building.description = "BUILDING"; @@ -83,69 +86,54 @@ public void testAssociatedWhereClause() { product.categoriesWithDescManyToMany.add( building ); product.categoriesWithDescIdLt4ManyToMany.add( building ); - doInHibernate( - this::sessionFactory, - session -> { - session.persist( flowers ); - session.persist( vegetables ); - session.persist( dogs ); - session.persist( building ); - session.persist( product ); - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Product p = session.get( Product.class, product.id ); - assertNotNull( p ); - assertEquals( 4, p.categoriesOneToMany.size() ); - checkIds( p.categoriesOneToMany, new Integer[] { 1, 2, 3, 4 } ); - assertEquals( 3, p.categoriesWithDescOneToMany.size() ); - checkIds( p.categoriesWithDescOneToMany, new Integer[] { 1, 2, 4 } ); - assertEquals( 4, p.categoriesManyToMany.size() ); - checkIds( p.categoriesManyToMany, new Integer[] { 1, 2, 3, 4 } ); - assertEquals( 3, p.categoriesWithDescManyToMany.size() ); - checkIds( p.categoriesWithDescManyToMany, new Integer[] { 1, 2, 4 } ); - assertEquals( 2, p.categoriesWithDescIdLt4ManyToMany.size() ); - checkIds( p.categoriesWithDescIdLt4ManyToMany, new Integer[] { 1, 2 } ); - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Category c = session.get( Category.class, flowers.id ); - assertNotNull( c ); - c.inactive = 1; - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Category c = session.get( Category.class, flowers.id ); - assertNull( c ); - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Product p = session.get( Product.class, product.id ); - assertNotNull( p ); - assertEquals( 3, p.categoriesOneToMany.size() ); - checkIds( p.categoriesOneToMany, new Integer[] { 2, 3, 4 } ); - assertEquals( 2, p.categoriesWithDescOneToMany.size() ); - checkIds( p.categoriesWithDescOneToMany, new Integer[] { 2, 4 } ); - assertEquals( 3, p.categoriesManyToMany.size() ); - checkIds( p.categoriesManyToMany, new Integer[] { 2, 3, 4 } ); - assertEquals( 2, p.categoriesWithDescManyToMany.size() ); - checkIds( p.categoriesWithDescManyToMany, new Integer[] { 2, 4 } ); - assertEquals( 1, p.categoriesWithDescIdLt4ManyToMany.size() ); - checkIds( p.categoriesWithDescIdLt4ManyToMany, new Integer[] { 2 } ); - } - ); + factoryScope.inTransaction( (session) -> { + session.persist( flowers ); + session.persist( vegetables ); + session.persist( dogs ); + session.persist( building ); + session.persist( product ); + } ); + + factoryScope.inTransaction( (session) -> { + var p = session.find( Product.class, product.id ); + assertNotNull( p ); + assertEquals( 4, p.categoriesOneToMany.size() ); + checkIds( p.categoriesOneToMany, new Integer[] { 1, 2, 3, 4 } ); + assertEquals( 3, p.categoriesWithDescOneToMany.size() ); + checkIds( p.categoriesWithDescOneToMany, new Integer[] { 1, 2, 4 } ); + assertEquals( 4, p.categoriesManyToMany.size() ); + checkIds( p.categoriesManyToMany, new Integer[] { 1, 2, 3, 4 } ); + assertEquals( 3, p.categoriesWithDescManyToMany.size() ); + checkIds( p.categoriesWithDescManyToMany, new Integer[] { 1, 2, 4 } ); + assertEquals( 2, p.categoriesWithDescIdLt4ManyToMany.size() ); + checkIds( p.categoriesWithDescIdLt4ManyToMany, new Integer[] { 1, 2 } ); + } ); + + factoryScope.inTransaction( (session) -> { + var c = session.find( Category.class, flowers.id ); + assertNotNull( c ); + c.inactive = 1; + } ); + + factoryScope.inTransaction( (session) -> { + var c = session.find( Category.class, flowers.id ); + assertNull( c ); + } ); + + factoryScope.inTransaction( (session) -> { + var p = session.find( Product.class, product.id ); + assertNotNull( p ); + assertEquals( 3, p.categoriesOneToMany.size() ); + checkIds( p.categoriesOneToMany, new Integer[] { 2, 3, 4 } ); + assertEquals( 2, p.categoriesWithDescOneToMany.size() ); + checkIds( p.categoriesWithDescOneToMany, new Integer[] { 2, 4 } ); + assertEquals( 3, p.categoriesManyToMany.size() ); + checkIds( p.categoriesManyToMany, new Integer[] { 2, 3, 4 } ); + assertEquals( 2, p.categoriesWithDescManyToMany.size() ); + checkIds( p.categoriesWithDescManyToMany, new Integer[] { 2, 4 } ); + assertEquals( 1, p.categoriesWithDescIdLt4ManyToMany.size() ); + checkIds( p.categoriesWithDescIdLt4ManyToMany, new Integer[] { 2 } ); + } ); } private void checkIds(Set categories, Integer[] expectedIds) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/EagerManyToOneFetchModeJoinWhereTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/EagerManyToOneFetchModeJoinWhereTest.java index c6108fe80fe1..76d5405422cd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/EagerManyToOneFetchModeJoinWhereTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/EagerManyToOneFetchModeJoinWhereTest.java @@ -7,95 +7,79 @@ import java.util.HashSet; import java.util.Set; -import org.hibernate.testing.FailureExpected; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.FailureExpected; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; /** * @author Gail Badner */ -public class EagerManyToOneFetchModeJoinWhereTest extends BaseNonConfigCoreFunctionalTestCase { - - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } - - @Override - protected String[] getMappings() { - return new String[] { "where/hbm/EagerManyToOneFetchModeJoinWhereTest.hbm.xml" }; +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(xmlMappings = "hbm/where/EagerManyToOneFetchModeJoinWhereTest.hbm.xml") +@SessionFactory(exportSchema = false) +public class EagerManyToOneFetchModeJoinWhereTest { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test @JiraKey( value = "HHH-12104" ) @FailureExpected( jiraKey = "HHH-12104") - public void testAssociatedWhereClause() { - Product product = new Product(); - Category category = new Category(); + public void testAssociatedWhereClause(SessionFactoryScope factoryScope) { + var product = new Product(); + var category = new Category(); category.name = "flowers"; product.category = category; product.containedCategory = new ContainedCategory(); product.containedCategory.category = category; product.containedCategories.add( new ContainedCategory( category ) ); - doInHibernate( - this::sessionFactory, - session -> { - session.persist( product ); - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Product p = session.get( Product.class, product.id ); - assertNotNull( p ); - assertNotNull( p.category ); - assertNotNull( p.containedCategory.category ); - assertEquals( 1, p.containedCategories.size() ); - assertSame( p.category, p.containedCategory.category ); - assertSame( p.category, p.containedCategories.iterator().next().category ); - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Category c = session.get( Category.class, category.id ); - assertNotNull( c ); - c.inactive = 1; - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Category c = session.get( Category.class, category.id ); - assertNull( c ); - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - // Entity's where clause is ignored when to-one associations to that - // association is loaded eagerly using FetchMode.JOIN, so the result - // should be the same as before the Category was made inactive. - Product p = session.get( Product.class, product.id ); - assertNotNull( p ); - assertNull( p.category ); - assertNull( p.containedCategory.category ); - assertEquals( 1, p.containedCategories.size() ); - assertNull( p.containedCategories.iterator().next().category ); - } - ); + factoryScope.inTransaction( (session) -> { + session.persist( product ); + } ); + + factoryScope.inTransaction( (session) -> { + var p = session.find( Product.class, product.id ); + assertNotNull( p ); + assertNotNull( p.category ); + assertNotNull( p.containedCategory.category ); + assertEquals( 1, p.containedCategories.size() ); + assertSame( p.category, p.containedCategory.category ); + assertSame( p.category, p.containedCategories.iterator().next().category ); + } ); + + factoryScope.inTransaction( (session) -> { + var c = session.find( Category.class, category.id ); + assertNotNull( c ); + c.inactive = 1; + } ); + + factoryScope.inTransaction( (session) -> { + var c = session.find( Category.class, category.id ); + assertNull( c ); + } ); + + factoryScope.inTransaction( (session) -> { + // Entity-level where clause is ignored when to-one associations to that + // association is loaded eagerly using FetchMode.JOIN, so the result + // should be the same as before the Category was made inactive. + var p = session.find( Product.class, product.id ); + assertNotNull( p ); + assertNull( p.category ); + assertNull( p.containedCategory.category ); + assertEquals( 1, p.containedCategories.size() ); + assertNull( p.containedCategories.iterator().next().category ); + } ); } public static class Product { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/EagerManyToOneFetchModeSelectWhereTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/EagerManyToOneFetchModeSelectWhereTest.java index c7b98f8444c4..06470699124d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/EagerManyToOneFetchModeSelectWhereTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/EagerManyToOneFetchModeSelectWhereTest.java @@ -8,92 +8,76 @@ import java.util.Set; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; /** * @author Gail Badner */ -public class EagerManyToOneFetchModeSelectWhereTest extends BaseNonConfigCoreFunctionalTestCase { - - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } - - @Override - protected String[] getMappings() { - return new String[] { "where/hbm/EagerManyToOneFetchModeSelectWhereTest.hbm.xml" }; +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(xmlMappings = "hbm/where/EagerManyToOneFetchModeSelectWhereTest.hbm.xml") +@SessionFactory +public class EagerManyToOneFetchModeSelectWhereTest { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test @JiraKey( value = "HHH-12104" ) - public void testAssociatedWhereClause() { - Product product = new Product(); - Category category = new Category(); + public void testAssociatedWhereClause(SessionFactoryScope factoryScope) { + var product = new Product(); + var category = new Category(); category.name = "flowers"; product.category = category; product.containedCategory = new ContainedCategory(); product.containedCategory.category = category; product.containedCategories.add( new ContainedCategory( category ) ); - doInHibernate( - this::sessionFactory, - session -> { - session.persist( product ); - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Product p = session.get( Product.class, product.id ); - assertNotNull( p ); - assertNotNull( p.category ); - assertNotNull( p.containedCategory.category ); - assertEquals( 1, p.containedCategories.size() ); - assertSame( p.category, p.containedCategory.category ); - assertSame( p.category, p.containedCategories.iterator().next().category ); - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Category c = session.get( Category.class, category.id ); - assertNotNull( c ); - c.inactive = 1; - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - Category c = session.get( Category.class, category.id ); - assertNull( c ); - } - ); - - doInHibernate( - this::sessionFactory, - session -> { - // Entity's where clause is taken into account when to-one associations - // to that entity is loaded eagerly using FetchMode.SELECT, so Category - // associations will be null. - Product p = session.get( Product.class, product.id ); - assertNotNull( p ); - assertNull( p.category ); - assertNull( p.containedCategory ); - assertEquals( 0, p.containedCategories.size() ); - } - ); + factoryScope.inTransaction( (session) -> { + session.persist( product ); + } ); + + factoryScope.inTransaction( (session) -> { + var p = session.find( Product.class, product.id ); + assertNotNull( p ); + assertNotNull( p.category ); + assertNotNull( p.containedCategory.category ); + assertEquals( 1, p.containedCategories.size() ); + assertSame( p.category, p.containedCategory.category ); + assertSame( p.category, p.containedCategories.iterator().next().category ); + } ); + + factoryScope.inTransaction( (session) -> { + var c = session.find( Category.class, category.id ); + assertNotNull( c ); + c.inactive = 1; + } ); + + factoryScope.inTransaction( (session) -> { + var c = session.find( Category.class, category.id ); + assertNull( c ); + } ); + + factoryScope.inTransaction( (session) -> { + // Entity-level where clause is taken into account when to-one associations + // to that entity is loaded eagerly using FetchMode.SELECT, so Category + // associations will be null. + var p = session.find( Product.class, product.id ); + assertNotNull( p ); + assertNull( p.category ); + assertNull( p.containedCategory ); + assertEquals( 0, p.containedCategories.size() ); + } ); } public static class Product { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/EagerToManyWhereTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/EagerToManyWhereTest.java index 8ec1a18f6f0d..954302c49e49 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/EagerToManyWhereTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/EagerToManyWhereTest.java @@ -4,19 +4,21 @@ */ package org.hibernate.orm.test.where.hbm; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + import java.util.Arrays; import java.util.HashSet; import java.util.Set; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests association collections with default AvailableSettings.USE_ENTITY_WHERE_CLAUSE_FOR_COLLECTIONS, @@ -24,24 +26,20 @@ * * @author Gail Badner */ -public class EagerToManyWhereTest extends BaseNonConfigCoreFunctionalTestCase { - - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } - - @Override - protected String[] getMappings() { - return new String[] { "where/hbm/EagerToManyWhere.hbm.xml" }; +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(xmlMappings = "hbm/where/EagerToManyWhere.hbm.xml") +@SessionFactory +public class EagerToManyWhereTest { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test @JiraKey( value = "HHH-13011" ) - public void testAssociatedWhereClause() { - - Product product = new Product(); - Category flowers = new Category(); + public void testAssociatedWhereClause(SessionFactoryScope factoryScope) { + var product = new Product(); + var flowers = new Category(); flowers.setId( 1 ); flowers.setName( "flowers" ); flowers.setDescription( "FLOWERS" ); @@ -50,7 +48,7 @@ public void testAssociatedWhereClause() { product.getCategoriesManyToMany().add( flowers ); product.getCategoriesWithDescManyToMany().add( flowers ); product.getCategoriesWithDescIdLt4ManyToMany().add( flowers ); - Category vegetables = new Category(); + var vegetables = new Category(); vegetables.setId( 2 ); vegetables.setName( "vegetables" ); vegetables.setDescription( "VEGETABLES" ); @@ -59,7 +57,7 @@ public void testAssociatedWhereClause() { product.getCategoriesManyToMany().add( vegetables ); product.getCategoriesWithDescManyToMany().add( vegetables ); product.getCategoriesWithDescIdLt4ManyToMany().add( vegetables ); - Category dogs = new Category(); + var dogs = new Category(); dogs.setId( 3 ); dogs.setName( "dogs" ); dogs.setDescription( null ); @@ -68,7 +66,7 @@ public void testAssociatedWhereClause() { product.getCategoriesManyToMany().add( dogs ); product.getCategoriesWithDescManyToMany().add( dogs ); product.getCategoriesWithDescIdLt4ManyToMany().add( dogs ); - Category building = new Category(); + var building = new Category(); building.setId( 4 ); building.setName( "building" ); building.setDescription( "BUILDING" ); @@ -78,69 +76,54 @@ public void testAssociatedWhereClause() { product.getCategoriesWithDescManyToMany().add( building ); product.getCategoriesWithDescIdLt4ManyToMany().add( building ); - doInHibernate( - this::sessionFactory, - session -> { - session.persist( flowers ); - session.persist( vegetables ); - session.persist( dogs ); - session.persist( building ); - session.persist( product ); - } - ); + factoryScope.inTransaction( (session) -> { + session.persist( flowers ); + session.persist( vegetables ); + session.persist( dogs ); + session.persist( building ); + session.persist( product ); + } ); - doInHibernate( - this::sessionFactory, - session -> { - Product p = session.get( Product.class, product.getId() ); - assertNotNull( p ); - assertEquals( 4, p.getCategoriesOneToMany().size() ); - checkIds( p.getCategoriesOneToMany(), new Integer[] { 1, 2, 3, 4 } ); - assertEquals( 3, p.getCategoriesWithDescOneToMany().size() ); - checkIds( p.getCategoriesWithDescOneToMany(), new Integer[] { 1, 2, 4 } ); - assertEquals( 4, p.getCategoriesManyToMany().size() ); - checkIds( p.getCategoriesManyToMany(), new Integer[] { 1, 2, 3, 4 } ); - assertEquals( 3, p.getCategoriesWithDescManyToMany().size() ); - checkIds( p.getCategoriesWithDescManyToMany(), new Integer[] { 1, 2, 4 } ); - assertEquals( 2, p.getCategoriesWithDescIdLt4ManyToMany().size() ); - checkIds( p.getCategoriesWithDescIdLt4ManyToMany(), new Integer[] { 1, 2 } ); - } - ); + factoryScope.inTransaction( (session) -> { + var p = session.find( Product.class, product.getId() ); + assertNotNull( p ); + assertEquals( 4, p.getCategoriesOneToMany().size() ); + checkIds( p.getCategoriesOneToMany(), new Integer[] { 1, 2, 3, 4 } ); + assertEquals( 3, p.getCategoriesWithDescOneToMany().size() ); + checkIds( p.getCategoriesWithDescOneToMany(), new Integer[] { 1, 2, 4 } ); + assertEquals( 4, p.getCategoriesManyToMany().size() ); + checkIds( p.getCategoriesManyToMany(), new Integer[] { 1, 2, 3, 4 } ); + assertEquals( 3, p.getCategoriesWithDescManyToMany().size() ); + checkIds( p.getCategoriesWithDescManyToMany(), new Integer[] { 1, 2, 4 } ); + assertEquals( 2, p.getCategoriesWithDescIdLt4ManyToMany().size() ); + checkIds( p.getCategoriesWithDescIdLt4ManyToMany(), new Integer[] { 1, 2 } ); + } ); - doInHibernate( - this::sessionFactory, - session -> { - Category c = session.get( Category.class, flowers.getId() ); - assertNotNull( c ); - c.setInactive( 1 ); - } - ); + factoryScope.inTransaction( (session) -> { + var c = session.find( Category.class, flowers.getId() ); + assertNotNull( c ); + c.setInactive( 1 ); + } ); - doInHibernate( - this::sessionFactory, - session -> { - Category c = session.get( Category.class, flowers.getId() ); - assertNull( c ); - } - ); + factoryScope.inTransaction( (session) -> { + var c = session.find( Category.class, flowers.getId() ); + assertNull( c ); + } ); - doInHibernate( - this::sessionFactory, - session -> { - Product p = session.get( Product.class, product.getId() ); - assertNotNull( p ); - assertEquals( 3, p.getCategoriesOneToMany().size() ); - checkIds( p.getCategoriesOneToMany(), new Integer[] { 2, 3, 4 } ); - assertEquals( 2, p.getCategoriesWithDescOneToMany().size() ); - checkIds( p.getCategoriesWithDescOneToMany(), new Integer[] { 2, 4 } ); - assertEquals( 3, p.getCategoriesManyToMany().size() ); - checkIds( p.getCategoriesManyToMany(), new Integer[] { 2, 3, 4 } ); - assertEquals( 2, p.getCategoriesWithDescManyToMany().size() ); - checkIds( p.getCategoriesWithDescManyToMany(), new Integer[] { 2, 4 } ); - assertEquals( 1, p.getCategoriesWithDescIdLt4ManyToMany().size() ); - checkIds( p.getCategoriesWithDescIdLt4ManyToMany(), new Integer[] { 2 } ); - } - ); + factoryScope.inTransaction( (session) -> { + var p = session.find( Product.class, product.getId() ); + assertNotNull( p ); + assertEquals( 3, p.getCategoriesOneToMany().size() ); + checkIds( p.getCategoriesOneToMany(), new Integer[] { 2, 3, 4 } ); + assertEquals( 2, p.getCategoriesWithDescOneToMany().size() ); + checkIds( p.getCategoriesWithDescOneToMany(), new Integer[] { 2, 4 } ); + assertEquals( 3, p.getCategoriesManyToMany().size() ); + checkIds( p.getCategoriesManyToMany(), new Integer[] { 2, 3, 4 } ); + assertEquals( 2, p.getCategoriesWithDescManyToMany().size() ); + checkIds( p.getCategoriesWithDescManyToMany(), new Integer[] { 2, 4 } ); + assertEquals( 1, p.getCategoriesWithDescIdLt4ManyToMany().size() ); + checkIds( p.getCategoriesWithDescIdLt4ManyToMany(), new Integer[] { 2 } ); + } ); } private void checkIds(Set categories, Integer[] expectedIds) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/EagerToManyWhereUseClassWhereTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/EagerToManyWhereUseClassWhereTest.java index c31049345c57..6e2a67220253 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/EagerToManyWhereUseClassWhereTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/EagerToManyWhereUseClassWhereTest.java @@ -4,41 +4,39 @@ */ package org.hibernate.orm.test.where.hbm; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + import java.util.Arrays; import java.util.HashSet; import java.util.Set; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Gail Badner */ -public class EagerToManyWhereUseClassWhereTest extends BaseNonConfigCoreFunctionalTestCase { - - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } - - @Override - protected String[] getMappings() { - return new String[] { "where/hbm/EagerToManyWhere.hbm.xml" }; +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(xmlMappings = "hbm/where/EagerToManyWhere.hbm.xml") +@SessionFactory +public class EagerToManyWhereUseClassWhereTest { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test @JiraKey( "HHH-13011" ) - public void testAssociatedWhereClause() { - - Product product = new Product(); - Category flowers = new Category(); + public void testAssociatedWhereClause(SessionFactoryScope factoryScope) { + var product = new Product(); + var flowers = new Category(); flowers.setId( 1 ); flowers.setName( "flowers" ); flowers.setDescription( "FLOWERS" ); @@ -47,7 +45,7 @@ public void testAssociatedWhereClause() { product.getCategoriesManyToMany().add( flowers ); product.getCategoriesWithDescManyToMany().add( flowers ); product.getCategoriesWithDescIdLt4ManyToMany().add( flowers ); - Category vegetables = new Category(); + var vegetables = new Category(); vegetables.setId( 2 ); vegetables.setName( "vegetables" ); vegetables.setDescription( "VEGETABLES" ); @@ -56,7 +54,7 @@ public void testAssociatedWhereClause() { product.getCategoriesManyToMany().add( vegetables ); product.getCategoriesWithDescManyToMany().add( vegetables ); product.getCategoriesWithDescIdLt4ManyToMany().add( vegetables ); - Category dogs = new Category(); + var dogs = new Category(); dogs.setId( 3 ); dogs.setName( "dogs" ); dogs.setDescription( null ); @@ -65,7 +63,7 @@ public void testAssociatedWhereClause() { product.getCategoriesManyToMany().add( dogs ); product.getCategoriesWithDescManyToMany().add( dogs ); product.getCategoriesWithDescIdLt4ManyToMany().add( dogs ); - Category building = new Category(); + var building = new Category(); building.setId( 4 ); building.setName( "building" ); building.setDescription( "BUILDING" ); @@ -75,69 +73,54 @@ public void testAssociatedWhereClause() { product.getCategoriesWithDescManyToMany().add( building ); product.getCategoriesWithDescIdLt4ManyToMany().add( building ); - doInHibernate( - this::sessionFactory, - session -> { - session.persist( flowers ); - session.persist( vegetables ); - session.persist( dogs ); - session.persist( building ); - session.persist( product ); - } - ); + factoryScope.inTransaction( (session) -> { + session.persist( flowers ); + session.persist( vegetables ); + session.persist( dogs ); + session.persist( building ); + session.persist( product ); + } ); - doInHibernate( - this::sessionFactory, - session -> { - Product p = session.get( Product.class, product.getId() ); - assertNotNull( p ); - assertEquals( 4, p.getCategoriesOneToMany().size() ); - checkIds( p.getCategoriesOneToMany(), new Integer[] { 1, 2, 3, 4 } ); - assertEquals( 3, p.getCategoriesWithDescOneToMany().size() ); - checkIds( p.getCategoriesWithDescOneToMany(), new Integer[] { 1, 2, 4 } ); - assertEquals( 4, p.getCategoriesManyToMany().size() ); - checkIds( p.getCategoriesManyToMany(), new Integer[] { 1, 2, 3, 4 } ); - assertEquals( 3, p.getCategoriesWithDescManyToMany().size() ); - checkIds( p.getCategoriesWithDescManyToMany(), new Integer[] { 1, 2, 4 } ); - assertEquals( 2, p.getCategoriesWithDescIdLt4ManyToMany().size() ); - checkIds( p.getCategoriesWithDescIdLt4ManyToMany(), new Integer[] { 1, 2 } ); - } - ); + factoryScope.inTransaction( (session) -> { + var p = session.find( Product.class, product.getId() ); + assertNotNull( p ); + assertEquals( 4, p.getCategoriesOneToMany().size() ); + checkIds( p.getCategoriesOneToMany(), new Integer[] { 1, 2, 3, 4 } ); + assertEquals( 3, p.getCategoriesWithDescOneToMany().size() ); + checkIds( p.getCategoriesWithDescOneToMany(), new Integer[] { 1, 2, 4 } ); + assertEquals( 4, p.getCategoriesManyToMany().size() ); + checkIds( p.getCategoriesManyToMany(), new Integer[] { 1, 2, 3, 4 } ); + assertEquals( 3, p.getCategoriesWithDescManyToMany().size() ); + checkIds( p.getCategoriesWithDescManyToMany(), new Integer[] { 1, 2, 4 } ); + assertEquals( 2, p.getCategoriesWithDescIdLt4ManyToMany().size() ); + checkIds( p.getCategoriesWithDescIdLt4ManyToMany(), new Integer[] { 1, 2 } ); + } ); - doInHibernate( - this::sessionFactory, - session -> { - Category c = session.get( Category.class, flowers.getId() ); - assertNotNull( c ); - c.setInactive( 1 ); - } - ); + factoryScope.inTransaction( (session) -> { + var c = session.find( Category.class, flowers.getId() ); + assertNotNull( c ); + c.setInactive( 1 ); + } ); - doInHibernate( - this::sessionFactory, - session -> { - Category c = session.get( Category.class, flowers.getId() ); - assertNull( c ); - } - ); + factoryScope.inTransaction( (session) -> { + var c = session.find( Category.class, flowers.getId() ); + assertNull( c ); + } ); - doInHibernate( - this::sessionFactory, - session -> { - Product p = session.get( Product.class, product.getId() ); - assertNotNull( p ); - assertEquals( 3, p.getCategoriesOneToMany().size() ); - checkIds( p.getCategoriesOneToMany(), new Integer[] { 2, 3, 4 } ); - assertEquals( 2, p.getCategoriesWithDescOneToMany().size() ); - checkIds( p.getCategoriesWithDescOneToMany(), new Integer[] { 2, 4 } ); - assertEquals( 3, p.getCategoriesManyToMany().size() ); - checkIds( p.getCategoriesManyToMany(), new Integer[] { 2, 3, 4 } ); - assertEquals( 2, p.getCategoriesWithDescManyToMany().size() ); - checkIds( p.getCategoriesWithDescManyToMany(), new Integer[] { 2, 4 } ); - assertEquals( 1, p.getCategoriesWithDescIdLt4ManyToMany().size() ); - checkIds( p.getCategoriesWithDescIdLt4ManyToMany(), new Integer[] { 2 } ); - } - ); + factoryScope.inTransaction( (session) -> { + var p = session.find( Product.class, product.getId() ); + assertNotNull( p ); + assertEquals( 3, p.getCategoriesOneToMany().size() ); + checkIds( p.getCategoriesOneToMany(), new Integer[] { 2, 3, 4 } ); + assertEquals( 2, p.getCategoriesWithDescOneToMany().size() ); + checkIds( p.getCategoriesWithDescOneToMany(), new Integer[] { 2, 4 } ); + assertEquals( 3, p.getCategoriesManyToMany().size() ); + checkIds( p.getCategoriesManyToMany(), new Integer[] { 2, 3, 4 } ); + assertEquals( 2, p.getCategoriesWithDescManyToMany().size() ); + checkIds( p.getCategoriesWithDescManyToMany(), new Integer[] { 2, 4 } ); + assertEquals( 1, p.getCategoriesWithDescIdLt4ManyToMany().size() ); + checkIds( p.getCategoriesWithDescIdLt4ManyToMany(), new Integer[] { 2 } ); + } ); } private void checkIds(Set categories, Integer[] expectedIds) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyElementCollectionBasicNonUniqueIdWhereTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyElementCollectionBasicNonUniqueIdWhereTest.java index 1fb62d095b3d..0ccfca436ae8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyElementCollectionBasicNonUniqueIdWhereTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyElementCollectionBasicNonUniqueIdWhereTest.java @@ -10,182 +10,82 @@ import java.util.Set; import org.hibernate.Hibernate; -import org.hibernate.Session; 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.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Gail Badner */ +@SuppressWarnings("JUnitMalformedDeclaration") @RequiresDialect(H2Dialect.class) -public class LazyElementCollectionBasicNonUniqueIdWhereTest extends BaseCoreFunctionalTestCase { - - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; +@DomainModel(xmlMappings = "hbm/where/LazyElementCollectionBasicNonUniqueIdWhereTest.hbm.xml") +@SessionFactory(exportSchema = false) +public class LazyElementCollectionBasicNonUniqueIdWhereTest { + @BeforeAll + static void createSchema(SessionFactoryScope factoryScope) { + org.hibernate.orm.test.where.annotations.LazyElementCollectionBasicNonUniqueIdWhereTest.applySchema( factoryScope ); } - @Override - protected String[] getMappings() { - return new String[] { "where/hbm/LazyElementCollectionBasicNonUniqueIdWhereTest.hbm.xml" }; - } - - @Before - public void setup() { - Session session = openSession(); - session.beginTransaction(); - { - session.createNativeQuery( getDialect().getDropTableString( "MAIN_TABLE" ) ).executeUpdate(); - session.createNativeQuery( getDialect().getDropTableString( "COLLECTION_TABLE" ) ).executeUpdate(); - session.createNativeQuery( getDialect().getDropTableString( "MATERIAL_RATINGS" ) ).executeUpdate(); - - session.createNativeQuery( - "create table MAIN_TABLE( " + - "ID integer not null, NAME varchar(255) not null, CODE varchar(10) not null, " + - "primary key (ID, CODE) )" - ).executeUpdate(); - - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'plastic', 'MATERIAL' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'house', 'BUILDING' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'high', 'RATING' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 2, 'medium', 'RATING' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 3, 'low', 'RATING' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'small', 'SIZE' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 2, 'medium', 'SIZE' )" ) - .executeUpdate(); - - session.createNativeQuery( - "create table COLLECTION_TABLE( " + - "MAIN_ID integer not null, MAIN_CODE varchar(10) not null, " + - "VAL varchar(10) not null, VALUE_CODE varchar(10) not null, " + - "primary key (MAIN_ID, MAIN_CODE, VAL, VALUE_CODE))" - ).executeUpdate(); - - session.createNativeQuery( - "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, VAL, VALUE_CODE) " + - "VALUES( 1, 'MATERIAL', 'high', 'RATING' )" - ).executeUpdate(); - session.createNativeQuery( - "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, VAL, VALUE_CODE) " + - "VALUES( 1, 'MATERIAL', 'medium', 'RATING' )" - ).executeUpdate(); - session.createNativeQuery( - "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, VAL, VALUE_CODE) " + - "VALUES( 1, 'MATERIAL', 'low', 'RATING' )" - ).executeUpdate(); - - session.createNativeQuery( - "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, VAL, VALUE_CODE) " + - "VALUES( 1, 'MATERIAL', 'medium', 'SIZE' )" - ).executeUpdate(); - - session.createNativeQuery( - "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, VAL, VALUE_CODE) " + - "VALUES( 1, 'BUILDING', 'high', 'RATING' )" - ).executeUpdate(); - - session.createNativeQuery( - "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, VAL, VALUE_CODE) " + - "VALUES( 1, 'BUILDING', 'small', 'SIZE' )" - ).executeUpdate(); - - - session.createNativeQuery( - "create table MATERIAL_RATINGS( " + - "MATERIAL_ID integer not null, RATING varchar(10) not null," + - " primary key (MATERIAL_ID, RATING))" - ).executeUpdate(); - - session.createNativeQuery( - "insert into MATERIAL_RATINGS(MATERIAL_ID, RATING) VALUES( 1, 'high' )" - ).executeUpdate(); - - } - session.getTransaction().commit(); - session.close(); - } - - @After - public void cleanup() { - Session session = openSession(); - session.beginTransaction(); - { - session.createNativeQuery( "delete from MATERIAL_RATINGS" ).executeUpdate(); -// session.createSQLQuery( "delete from BUILDING_RATINGS" ).executeUpdate(); - session.createNativeQuery( "delete from COLLECTION_TABLE" ).executeUpdate(); - session.createNativeQuery( "delete from MAIN_TABLE" ).executeUpdate(); - } - session.getTransaction().commit(); - session.close(); + @AfterAll + static void dropSchema(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test @JiraKey( value = "HHH-12937") - public void testInitializeFromUniqueAssociationTable() { - Session session = openSession(); - session.beginTransaction(); - { - Material material = session.get( Material.class, 1 ); - assertEquals( "plastic", material.getName() ); - - // Material#ratings is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( material.getRatings() ) ); - assertEquals( 1, material.getRatings().size() ); - assertTrue( Hibernate.isInitialized( material.getRatings() ) ); - - assertEquals( "high", material.getRatings().iterator().next() ); - } - session.getTransaction().commit(); - session.close(); + public void testInitializeFromUniqueAssociationTable(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + var material = session.find( Material.class, 1 ); + assertEquals( "plastic", material.getName() ); + + // Material#ratings is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( material.getRatings() ) ); + assertEquals( 1, material.getRatings().size() ); + assertTrue( Hibernate.isInitialized( material.getRatings() ) ); + + assertEquals( "high", material.getRatings().iterator().next() ); + } ); } @Test @JiraKey( value = "HHH-12937") - public void testInitializeFromNonUniqueAssociationTable() { - Session session = openSession(); - session.beginTransaction(); - { - Material material = session.get( Material.class, 1 ); - assertEquals( "plastic", material.getName() ); - - // Material#sizesFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( material.getSizesFromCombined() ) ); - assertEquals( 1, material.getSizesFromCombined().size() ); - assertTrue( Hibernate.isInitialized( material.getSizesFromCombined() ) ); - - assertEquals( "medium", material.getSizesFromCombined().iterator().next() ); - - Building building = session.get( Building.class, 1 ); - - // building.ratingsFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( building.getRatingsFromCombined() ) ); - assertEquals( 1, building.getRatingsFromCombined().size() ); - assertTrue( Hibernate.isInitialized( building.getRatingsFromCombined() ) ); - assertEquals( "high", building.getRatingsFromCombined().iterator().next() ); - - // Building#sizesFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( building.getSizesFromCombined() ) ); - assertEquals( 1, building.getSizesFromCombined().size() ); - assertTrue( Hibernate.isInitialized( building.getSizesFromCombined() ) ); - assertEquals( "small", building.getSizesFromCombined().iterator().next() ); - } - session.getTransaction().commit(); - session.close(); + public void testInitializeFromNonUniqueAssociationTable(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + Material material = session.find( Material.class, 1 ); + assertEquals( "plastic", material.getName() ); + + // Material#sizesFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( material.getSizesFromCombined() ) ); + assertEquals( 1, material.getSizesFromCombined().size() ); + assertTrue( Hibernate.isInitialized( material.getSizesFromCombined() ) ); + + assertEquals( "medium", material.getSizesFromCombined().iterator().next() ); + + Building building = session.find( Building.class, 1 ); + + // building.ratingsFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( building.getRatingsFromCombined() ) ); + assertEquals( 1, building.getRatingsFromCombined().size() ); + assertTrue( Hibernate.isInitialized( building.getRatingsFromCombined() ) ); + assertEquals( "high", building.getRatingsFromCombined().iterator().next() ); + + // Building#sizesFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( building.getSizesFromCombined() ) ); + assertEquals( 1, building.getSizesFromCombined().size() ); + assertTrue( Hibernate.isInitialized( building.getSizesFromCombined() ) ); + assertEquals( "small", building.getSizesFromCombined().iterator().next() ); + } ); } public static class Material { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyElementCollectionWithLazyManyToOneNonUniqueIdWhereTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyElementCollectionWithLazyManyToOneNonUniqueIdWhereTest.java index 740b880a6a90..9578aeb35560 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyElementCollectionWithLazyManyToOneNonUniqueIdWhereTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyElementCollectionWithLazyManyToOneNonUniqueIdWhereTest.java @@ -4,195 +4,96 @@ */ package org.hibernate.orm.test.where.hbm; +import org.hibernate.Hibernate; +import org.hibernate.dialect.H2Dialect; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; -import org.hibernate.Hibernate; -import org.hibernate.Session; -import org.hibernate.dialect.H2Dialect; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Gail Badner */ +@SuppressWarnings("JUnitMalformedDeclaration") @RequiresDialect(H2Dialect.class) -public class LazyElementCollectionWithLazyManyToOneNonUniqueIdWhereTest extends BaseCoreFunctionalTestCase { - - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; +@DomainModel(xmlMappings = "hbm/where/LazyElementCollectionWithLazyManyToOneNonUniqueIdWhereTest.hbm.xml") +@SessionFactory(exportSchema = false) +public class LazyElementCollectionWithLazyManyToOneNonUniqueIdWhereTest { + @BeforeAll + public void createSchema(SessionFactoryScope factoryScope) { + org.hibernate.orm.test.where.annotations.LazyElementCollectionWithLazyManyToOneNonUniqueIdWhereTest.applySchema( factoryScope ); } - @Override - protected String[] getMappings() { - return new String[] { "where/hbm/LazyElementCollectionWithLazyManyToOneNonUniqueIdWhereTest.hbm.xml" }; - } - - @Before - public void setup() { - Session session = openSession(); - session.beginTransaction(); - { - session.createNativeQuery( getDialect().getDropTableString( "MAIN_TABLE" ) ).executeUpdate(); - session.createNativeQuery( getDialect().getDropTableString( "COLLECTION_TABLE" ) ).executeUpdate(); - session.createNativeQuery( getDialect().getDropTableString( "MATERIAL_RATINGS" ) ).executeUpdate(); - - session.createNativeQuery( - "create table MAIN_TABLE( " + - "ID integer not null, NAME varchar(255) not null, CODE varchar(10) not null, " + - "primary key (ID, CODE) )" - ).executeUpdate(); - - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'plastic', 'MATERIAL' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'house', 'BUILDING' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'high', 'RATING' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 2, 'medium', 'RATING' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 3, 'low', 'RATING' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'small', 'SIZE' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 2, 'medium', 'SIZE' )" ) - .executeUpdate(); - - session.createNativeQuery( - "create table COLLECTION_TABLE( " + - "MAIN_ID integer not null, MAIN_CODE varchar(10) not null, " + - "ASSOCIATION_ID int not null, ASSOCIATION_CODE varchar(10) not null, " + - "primary key (MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE))" - ).executeUpdate(); - - session.createNativeQuery( - "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'MATERIAL', 1, 'RATING' )" - ).executeUpdate(); - session.createNativeQuery( - "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'MATERIAL', 2, 'RATING' )" - ).executeUpdate(); - session.createNativeQuery( - "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'MATERIAL', 3, 'RATING' )" - ).executeUpdate(); - - session.createNativeQuery( - "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'MATERIAL', 2, 'SIZE' )" - ).executeUpdate(); - - session.createNativeQuery( - "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'BUILDING', 1, 'RATING' )" - ).executeUpdate(); - - session.createNativeQuery( - "insert into COLLECTION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'BUILDING', 1, 'SIZE' )" - ).executeUpdate(); - - - session.createNativeQuery( - "create table MATERIAL_RATINGS( " + - "MATERIAL_ID integer not null, RATING_ID integer not null," + - " primary key (MATERIAL_ID, RATING_ID))" - ).executeUpdate(); - - session.createNativeQuery( - "insert into MATERIAL_RATINGS(MATERIAL_ID, RATING_ID) VALUES( 1, 1 )" - ).executeUpdate(); - - } - session.getTransaction().commit(); - session.close(); - } - - @After - public void cleanup() { - Session session = openSession(); - session.beginTransaction(); - { - session.createNativeQuery( "delete from MATERIAL_RATINGS" ).executeUpdate(); - session.createNativeQuery( "delete from COLLECTION_TABLE" ).executeUpdate(); - session.createNativeQuery( "delete from MAIN_TABLE" ).executeUpdate(); - } - session.getTransaction().commit(); - session.close(); + @AfterAll + public void dropSchema(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test @JiraKey( value = "HHH-12937") - public void testInitializeFromUniqueAssociationTable() { - Session session = openSession(); - session.beginTransaction(); - { - Material material = session.get( Material.class, 1 ); - assertEquals( "plastic", material.getName() ); - - // Material#ratings is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( material.getContainedRatings() ) ); - assertEquals( 1, material.getContainedRatings().size() ); - assertTrue( Hibernate.isInitialized( material.getContainedRatings() ) ); - - final ContainedRating containedRating = material.getContainedRatings().iterator().next(); - assertTrue( Hibernate.isInitialized( containedRating ) ); - assertEquals( "high", containedRating.getRating().getName() ); - } - session.getTransaction().commit(); - session.close(); + public void testInitializeFromUniqueAssociationTable(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + Material material = session.find( Material.class, 1 ); + assertEquals( "plastic", material.getName() ); + + // Material#ratings is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( material.getContainedRatings() ) ); + assertEquals( 1, material.getContainedRatings().size() ); + assertTrue( Hibernate.isInitialized( material.getContainedRatings() ) ); + + final ContainedRating containedRating = material.getContainedRatings().iterator().next(); + assertTrue( Hibernate.isInitialized( containedRating ) ); + assertEquals( "high", containedRating.getRating().getName() ); + } ); } @Test @JiraKey( value = "HHH-12937") - public void testInitializeFromNonUniqueAssociationTable() { - Session session = openSession(); - session.beginTransaction(); - { - Material material = session.get( Material.class, 1 ); - assertEquals( "plastic", material.getName() ); - - // Material#containedSizesFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( material.getContainedSizesFromCombined() ) ); - assertEquals( 1, material.getContainedSizesFromCombined().size() ); - assertTrue( Hibernate.isInitialized( material.getContainedSizesFromCombined() ) ); - - ContainedSize containedSize = material.getContainedSizesFromCombined().iterator().next(); - assertFalse( Hibernate.isInitialized( containedSize.getSize() ) ); - assertEquals( "medium", containedSize.getSize().getName() ); - - Building building = session.get( Building.class, 1 ); - - // building.ratingsFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( building.getContainedRatingsFromCombined() ) ); - assertEquals( 1, building.getContainedRatingsFromCombined().size() ); - assertTrue( Hibernate.isInitialized( building.getContainedRatingsFromCombined() ) ); - ContainedRating containedRating = building.getContainedRatingsFromCombined().iterator().next(); - assertFalse( Hibernate.isInitialized( containedRating.getRating() ) ); - assertEquals( "high", containedRating.getRating().getName() ); - - // Building#containedSizesFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( building.getContainedSizesFromCombined() ) ); - assertEquals( 1, building.getContainedSizesFromCombined().size() ); - assertTrue( Hibernate.isInitialized( building.getContainedSizesFromCombined() ) ); - containedSize = building.getContainedSizesFromCombined().iterator().next(); - assertFalse( Hibernate.isInitialized( containedSize.getSize() ) ); - assertEquals( "small", containedSize.getSize().getName() ); - } - session.getTransaction().commit(); - session.close(); + public void testInitializeFromNonUniqueAssociationTable(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + Material material = session.find( Material.class, 1 ); + assertEquals( "plastic", material.getName() ); + + // Material#containedSizesFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( material.getContainedSizesFromCombined() ) ); + assertEquals( 1, material.getContainedSizesFromCombined().size() ); + assertTrue( Hibernate.isInitialized( material.getContainedSizesFromCombined() ) ); + + ContainedSize containedSize = material.getContainedSizesFromCombined().iterator().next(); + assertFalse( Hibernate.isInitialized( containedSize.getSize() ) ); + assertEquals( "medium", containedSize.getSize().getName() ); + + Building building = session.find( Building.class, 1 ); + + // building.ratingsFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( building.getContainedRatingsFromCombined() ) ); + assertEquals( 1, building.getContainedRatingsFromCombined().size() ); + assertTrue( Hibernate.isInitialized( building.getContainedRatingsFromCombined() ) ); + ContainedRating containedRating = building.getContainedRatingsFromCombined().iterator().next(); + assertFalse( Hibernate.isInitialized( containedRating.getRating() ) ); + assertEquals( "high", containedRating.getRating().getName() ); + + // Building#containedSizesFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( building.getContainedSizesFromCombined() ) ); + assertEquals( 1, building.getContainedSizesFromCombined().size() ); + assertTrue( Hibernate.isInitialized( building.getContainedSizesFromCombined() ) ); + containedSize = building.getContainedSizesFromCombined().iterator().next(); + assertFalse( Hibernate.isInitialized( containedSize.getSize() ) ); + assertEquals( "small", containedSize.getSize().getName() ); + } ); } public static class Material { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyManyToManyNonUniqueIdNotFoundWhereTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyManyToManyNonUniqueIdNotFoundWhereTest.java index 7b1b2630be7a..afbbbc74f9bb 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyManyToManyNonUniqueIdNotFoundWhereTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyManyToManyNonUniqueIdNotFoundWhereTest.java @@ -4,236 +4,184 @@ */ package org.hibernate.orm.test.where.hbm; -import java.util.HashSet; -import java.util.Set; import org.hibernate.Hibernate; +import org.hibernate.dialect.Dialect; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.sql.Statement; +import java.util.HashSet; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; -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.assertSame; -import static org.junit.Assert.assertTrue; /** * @author Gail Badner */ -public class LazyManyToManyNonUniqueIdNotFoundWhereTest extends BaseCoreFunctionalTestCase { - - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } - - @Override - protected String[] getMappings() { - return new String[] { "where/hbm/LazyManyToManyNonUniqueIdNotFoundWhereTest.hbm.xml" }; - } - - @Before - public void setup() { - doInHibernate( - this::sessionFactory, session -> { - - session.createNativeQuery( getDialect().getDropTableString( "MATERIAL_RATINGS" )).executeUpdate(); - session.createNativeQuery( getDialect().getDropTableString( "BUILDING_RATINGS" )).executeUpdate(); - session.createNativeQuery( getDialect().getDropTableString( "ASSOCIATION_TABLE" )).executeUpdate(); - session.createNativeQuery( getDialect().getDropTableString( "MAIN_TABLE" )).executeUpdate(); - } - ); - - doInHibernate( - this::sessionFactory, session -> { - - session.createNativeQuery( - "create table MAIN_TABLE( " + - "ID integer not null, NAME varchar(255) not null, CODE varchar(10) not null, " + - "primary key (ID, CODE) )" - ).executeUpdate(); - - session.createNativeQuery( - "create table ASSOCIATION_TABLE( " + - "MAIN_ID integer not null, MAIN_CODE varchar(10) not null, " + - "ASSOCIATION_ID int not null, ASSOCIATION_CODE varchar(10) not null, " + - "primary key (MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE))" - ).executeUpdate(); - - session.createNativeQuery( - "create table BUILDING_RATINGS( " + - "BUILDING_ID integer not null, RATING_ID integer not null," + - " primary key (BUILDING_ID, RATING_ID))" - ).executeUpdate(); - - session.createNativeQuery( - "create table MATERIAL_RATINGS( " + - "MATERIAL_ID integer not null, RATING_ID integer not null," + - " primary key (MATERIAL_ID, RATING_ID))" - ).executeUpdate(); - } - ); - - doInHibernate( - this::sessionFactory, session -> { - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'plastic', 'MATERIAL' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'house', 'BUILDING' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'high', 'RATING' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'small', 'SIZE' )" ) - .executeUpdate(); - - session.createNativeQuery( - "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'MATERIAL', 1, 'RATING' )" - ).executeUpdate(); - - // add a collection element that won't be found - session.createNativeQuery( - "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'MATERIAL', 2, 'RATING' )" - ).executeUpdate(); - - session.createNativeQuery( - "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'MATERIAL', 1, 'SIZE' )" - ).executeUpdate(); - - // add a collection element that won't be found - session.createNativeQuery( - "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'MATERIAL', 2, 'SIZE' )" - ).executeUpdate(); - - session.createNativeQuery( - "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'BUILDING', 1, 'RATING' )" - ).executeUpdate(); - - // add a collection element that won't be found - session.createNativeQuery( - "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'BUILDING', 2, 'RATING' )" - ).executeUpdate(); - - - session.createNativeQuery( - "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'BUILDING', 1, 'SIZE' )" - ).executeUpdate(); - - // add a collection element that won't be found - session.createNativeQuery( - "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'BUILDING', 2, 'SIZE' )" - ).executeUpdate(); - - session.createNativeQuery( - "insert into MATERIAL_RATINGS(MATERIAL_ID, RATING_ID) VALUES( 1, 1 )" - ).executeUpdate(); - - // add a collection element that won't be found - session.createNativeQuery( - "insert into MATERIAL_RATINGS(MATERIAL_ID, RATING_ID) VALUES( 1, 2 )" - ).executeUpdate(); - - session.createNativeQuery( - "insert into BUILDING_RATINGS(BUILDING_ID, RATING_ID) VALUES( 1, 1 )" - ).executeUpdate(); - - // add a collection element that won't be found - session.createNativeQuery( - "insert into BUILDING_RATINGS(BUILDING_ID, RATING_ID) VALUES( 1, 2 )" - ).executeUpdate(); - } - ); +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(xmlMappings = "hbm/where/LazyManyToManyNonUniqueIdNotFoundWhereTest.hbm.xml") +@SessionFactory(exportSchema = false) +public class LazyManyToManyNonUniqueIdNotFoundWhereTest { + @AfterAll + static void dropSchema(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } - @After - public void cleanup() { - doInHibernate( - this::sessionFactory, session -> { - session.createNativeQuery( "delete from MATERIAL_RATINGS" ).executeUpdate(); - session.createNativeQuery( "delete from BUILDING_RATINGS" ).executeUpdate(); - session.createNativeQuery( "delete from ASSOCIATION_TABLE" ).executeUpdate(); - session.createNativeQuery( "delete from MAIN_TABLE" ).executeUpdate(); - } - ); + @BeforeAll + public void createSchema(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( session -> session.doWork( connection -> { + final Dialect dialect = session.getDialect(); + try (final Statement statement = connection.createStatement()) { + statement.executeUpdate( dialect.getDropTableString( "MAIN_TABLE" ) ); + statement.executeUpdate( dialect.getDropTableString( "BUILDING_RATINGS" ) ); + statement.executeUpdate( dialect.getDropTableString( "ASSOCIATION_TABLE" ) ); + statement.executeUpdate( dialect.getDropTableString( "MATERIAL_RATINGS" ) ); + + statement.executeUpdate( """ + create table MAIN_TABLE( + ID integer not null, + NAME varchar(255) not null, + CODE varchar(10) not null, + primary key (ID, CODE) + )""" ); + statement.executeUpdate( """ + create table ASSOCIATION_TABLE( + MAIN_ID integer not null, + MAIN_CODE varchar(10) not null, + ASSOCIATION_ID int not null, + ASSOCIATION_CODE varchar(10) not null, + primary key (MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) + )""" ); + statement.executeUpdate( """ + create table BUILDING_RATINGS( + BUILDING_ID integer not null, + RATING_ID integer not null, + primary key (BUILDING_ID, RATING_ID) + )""" ); + statement.executeUpdate(""" + create table MATERIAL_RATINGS( + MATERIAL_ID integer not null, + RATING_ID integer not null, + primary key (MATERIAL_ID, RATING_ID) + )""" ); + + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'plastic', 'MATERIAL' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'house', 'BUILDING' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'high', 'RATING' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'small', 'SIZE' )" ); + + statement.executeUpdate( "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + + "VALUES( 1, 'MATERIAL', 1, 'RATING' )" ); + // add a collection element that won't be found + statement.executeUpdate( "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + + "VALUES( 1, 'MATERIAL', 2, 'RATING' )" ); + + statement.executeUpdate( "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + + "VALUES( 1, 'MATERIAL', 1, 'SIZE' )" ); + + // add a collection element that won't be found + statement.executeUpdate( "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + + "VALUES( 1, 'MATERIAL', 2, 'SIZE' )" ); + + statement.executeUpdate( "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + + "VALUES( 1, 'BUILDING', 1, 'RATING' )" ); + + // add a collection element that won't be found + statement.executeUpdate( "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + + "VALUES( 1, 'BUILDING', 2, 'RATING' )" ); + + statement.executeUpdate( "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + + "VALUES( 1, 'BUILDING', 1, 'SIZE' )" ); + + // add a collection element that won't be found + statement.executeUpdate( "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + + "VALUES( 1, 'BUILDING', 2, 'SIZE' )" ); + + statement.executeUpdate( "insert into MATERIAL_RATINGS(MATERIAL_ID, RATING_ID) VALUES( 1, 1 )" ); + + // add a collection element that won't be found + statement.executeUpdate( "insert into MATERIAL_RATINGS(MATERIAL_ID, RATING_ID) VALUES( 1, 2 )" ); + + statement.executeUpdate( "insert into BUILDING_RATINGS(BUILDING_ID, RATING_ID) VALUES( 1, 1 )" ); + + // add a collection element that won't be found + statement.executeUpdate( "insert into BUILDING_RATINGS(BUILDING_ID, RATING_ID) VALUES( 1, 2 )" ); + } + } ) ); } @Test @JiraKey( value = "HHH-12875" ) - public void testInitializeFromUniqueAssociationTable() { - doInHibernate( - this::sessionFactory, session -> { - - Material material = session.get( Material.class, 1 ); - assertEquals( "plastic", material.getName() ); - - // Material#ratings is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( material.getRatings() ) ); - assertEquals( 1, material.getRatings().size() ); - assertTrue( Hibernate.isInitialized( material.getRatings() ) ); - - final Rating rating = material.getRatings().iterator().next(); - assertEquals( "high", rating.getName() ); - - Building building = session.get( Building.class, 1 ); - assertEquals( "house", building.getName() ); - - // Building#ratings is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( building.getRatings() ) ); - assertEquals( 1, building.getRatings().size() ); - assertTrue( Hibernate.isInitialized( building.getRatings() ) ); - assertSame( rating, building.getRatings().iterator().next() ); - } - ); + public void testInitializeFromUniqueAssociationTable(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + Material material = session.find( Material.class, 1 ); + assertEquals( "plastic", material.getName() ); + + // Material#ratings is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( material.getRatings() ) ); + assertEquals( 1, material.getRatings().size() ); + assertTrue( Hibernate.isInitialized( material.getRatings() ) ); + + final Rating rating = material.getRatings().iterator().next(); + assertEquals( "high", rating.getName() ); + + Building building = session.find( Building.class, 1 ); + assertEquals( "house", building.getName() ); + + // Building#ratings is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( building.getRatings() ) ); + assertEquals( 1, building.getRatings().size() ); + assertTrue( Hibernate.isInitialized( building.getRatings() ) ); + assertSame( rating, building.getRatings().iterator().next() ); + } ); } @Test @JiraKey( value = "HHH-12875" ) - public void testInitializeFromNonUniqueAssociationTable() { - doInHibernate( - this::sessionFactory, session -> { - - Material material = session.get( Material.class, 1 ); - assertEquals( "plastic", material.getName() ); - - // Material#ratingsFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( material.getRatingsFromCombined() ) ); - assertEquals( 1, material.getRatingsFromCombined().size() ); - assertTrue( Hibernate.isInitialized( material.getRatingsFromCombined() ) ); - - final Rating rating = material.getRatingsFromCombined().iterator().next(); - assertEquals( "high", rating.getName() ); - - // Material#sizesFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( material.getSizesFromCombined() ) ); - assertEquals( 1, material.getSizesFromCombined().size() ); - assertTrue( Hibernate.isInitialized( material.getSizesFromCombined() ) ); - - final Size size = material.getSizesFromCombined().iterator().next(); - assertEquals( "small", size.getName() ); - - Building building = session.get( Building.class, 1 ); - - // building.ratingsFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( building.getRatingsFromCombined() ) ); - assertEquals( 1, building.getRatingsFromCombined().size() ); - assertTrue( Hibernate.isInitialized( building.getRatingsFromCombined() ) ); - assertSame( rating, building.getRatingsFromCombined().iterator().next() ); - - // Building#sizesFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( building.getSizesFromCombined() ) ); - assertEquals( 1, building.getSizesFromCombined().size() ); - assertTrue( Hibernate.isInitialized( building.getSizesFromCombined() ) ); - assertSame( size, building.getSizesFromCombined().iterator().next() ); - } - ); + public void testInitializeFromNonUniqueAssociationTable(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + Material material = session.find( Material.class, 1 ); + assertEquals( "plastic", material.getName() ); + + // Material#ratingsFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( material.getRatingsFromCombined() ) ); + assertEquals( 1, material.getRatingsFromCombined().size() ); + assertTrue( Hibernate.isInitialized( material.getRatingsFromCombined() ) ); + + final Rating rating = material.getRatingsFromCombined().iterator().next(); + assertEquals( "high", rating.getName() ); + + // Material#sizesFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( material.getSizesFromCombined() ) ); + assertEquals( 1, material.getSizesFromCombined().size() ); + assertTrue( Hibernate.isInitialized( material.getSizesFromCombined() ) ); + + final Size size = material.getSizesFromCombined().iterator().next(); + assertEquals( "small", size.getName() ); + + Building building = session.find( Building.class, 1 ); + + // building.ratingsFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( building.getRatingsFromCombined() ) ); + assertEquals( 1, building.getRatingsFromCombined().size() ); + assertTrue( Hibernate.isInitialized( building.getRatingsFromCombined() ) ); + assertSame( rating, building.getRatingsFromCombined().iterator().next() ); + + // Building#sizesFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( building.getSizesFromCombined() ) ); + assertEquals( 1, building.getSizesFromCombined().size() ); + assertTrue( Hibernate.isInitialized( building.getSizesFromCombined() ) ); + assertSame( size, building.getSizesFromCombined().iterator().next() ); + } ); } public static class Material { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyManyToManyNonUniqueIdWhereTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyManyToManyNonUniqueIdWhereTest.java index b3f8d20d6568..98bbdbb5b956 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyManyToManyNonUniqueIdWhereTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyManyToManyNonUniqueIdWhereTest.java @@ -4,229 +4,174 @@ */ package org.hibernate.orm.test.where.hbm; +import org.hibernate.Hibernate; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.sql.Statement; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; -import org.hibernate.Hibernate; - -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.hibernate.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.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Gail Badner */ -public class LazyManyToManyNonUniqueIdWhereTest extends BaseCoreFunctionalTestCase { - - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(xmlMappings = "hbm/where/LazyManyToManyNonUniqueIdWhereTest.hbm.xml") +@SessionFactory(exportSchema = false) +public class LazyManyToManyNonUniqueIdWhereTest { + + @BeforeAll + public void createSchema(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> session.doWork( (connections) -> { + var dialect = session.getDialect(); + try (Statement statement = connections.createStatement()) { + statement.executeUpdate( dialect.getDropTableString( "MATERIAL_RATINGS" ) ); + statement.executeUpdate( dialect.getDropTableString( "BUILDING_RATINGS" ) ); + statement.executeUpdate( dialect.getDropTableString( "ASSOCIATION_TABLE" ) ); + statement.executeUpdate( dialect.getDropTableString( "MAIN_TABLE" ) ); + + statement.executeUpdate( """ + create table MAIN_TABLE( + ID integer not null, + NAME varchar(255) not null, + CODE varchar(10) not null, + primary key (ID, CODE) + )""" ); + statement.executeUpdate( """ + create table ASSOCIATION_TABLE( + MAIN_ID integer not null, + MAIN_CODE varchar(10) not null, + ASSOCIATION_ID int not null, + ASSOCIATION_CODE varchar(10) not null, + primary key (MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) + )""" ); + statement.executeUpdate(""" + create table MATERIAL_RATINGS( + MATERIAL_ID integer not null, + RATING_ID integer not null, + primary key (MATERIAL_ID, RATING_ID) + )""" ); + statement.executeUpdate( """ + create table BUILDING_RATINGS( + BUILDING_ID integer not null, + RATING_ID integer not null, + primary key (BUILDING_ID, RATING_ID) + )""" ); + + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'plastic', 'MATERIAL' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'house', 'BUILDING' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'high', 'RATING' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 2, 'medium', 'RATING' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 3, 'low', 'RATING' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'small', 'SIZE' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 2, 'medium', 'SIZE' )" ); + + statement.executeUpdate( "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + + "VALUES( 1, 'MATERIAL', 1, 'RATING' )" ); + statement.executeUpdate( "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + + "VALUES( 1, 'MATERIAL', 2, 'RATING' )" ); + statement.executeUpdate( "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + + "VALUES( 1, 'MATERIAL', 3, 'RATING' )" ); + statement.executeUpdate( "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + + "VALUES( 1, 'MATERIAL', 2, 'SIZE' )" ); + statement.executeUpdate( "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + + "VALUES( 1, 'BUILDING', 1, 'RATING' )" ); + statement.executeUpdate( "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + + "VALUES( 1, 'BUILDING', 1, 'SIZE' )" ); + + statement.executeUpdate( "insert into MATERIAL_RATINGS(MATERIAL_ID, RATING_ID) VALUES( 1, 1 )" ); + + statement.executeUpdate( "insert into BUILDING_RATINGS(BUILDING_ID, RATING_ID) VALUES( 1, 1 )" ); + statement.executeUpdate( "insert into BUILDING_RATINGS(BUILDING_ID, RATING_ID) VALUES( 1, 2 )" ); + statement.executeUpdate( "insert into BUILDING_RATINGS(BUILDING_ID, RATING_ID) VALUES( 1, 3 )" ); + } + } ) ); } - @Override - protected String[] getMappings() { - return new String[] { "where/hbm/LazyManyToManyNonUniqueIdWhereTest.hbm.xml" }; - } - - @Before - public void setup() { - doInHibernate( - this::sessionFactory, session -> { - session.createNativeQuery( getDialect().getDropTableString( "MATERIAL_RATINGS" ) ).executeUpdate(); - session.createNativeQuery( getDialect().getDropTableString( "BUILDING_RATINGS" ) ).executeUpdate(); - session.createNativeQuery( getDialect().getDropTableString( "ASSOCIATION_TABLE" ) ).executeUpdate(); - session.createNativeQuery( getDialect().getDropTableString( "MAIN_TABLE" ) ).executeUpdate(); - } - ); - - doInHibernate( - this::sessionFactory, session -> { - - session.createNativeQuery( - "create table MAIN_TABLE( " + - "ID integer not null, NAME varchar(255) not null, CODE varchar(10) not null, " + - "primary key (ID, CODE) )" - ).executeUpdate(); - - session.createNativeQuery( - "create table ASSOCIATION_TABLE( " + - "MAIN_ID integer not null, MAIN_CODE varchar(10) not null, " + - "ASSOCIATION_ID int not null, ASSOCIATION_CODE varchar(10) not null, " + - "primary key (MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE))" - ).executeUpdate(); - - session.createNativeQuery( - "create table MATERIAL_RATINGS( " + - "MATERIAL_ID integer not null, RATING_ID integer not null," + - " primary key (MATERIAL_ID, RATING_ID))" - ).executeUpdate(); - - session.createNativeQuery( - "create table BUILDING_RATINGS( " + - "BUILDING_ID integer not null, RATING_ID integer not null," + - " primary key (BUILDING_ID, RATING_ID))" - ).executeUpdate(); - } - ); - - doInHibernate( - this::sessionFactory, session -> { - - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'plastic', 'MATERIAL' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'house', 'BUILDING' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'high', 'RATING' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 2, 'medium', 'RATING' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 3, 'low', 'RATING' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'small', 'SIZE' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 2, 'medium', 'SIZE' )" ) - .executeUpdate(); - - session.createNativeQuery( - "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'MATERIAL', 1, 'RATING' )" - ).executeUpdate(); - session.createNativeQuery( - "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'MATERIAL', 2, 'RATING' )" - ).executeUpdate(); - session.createNativeQuery( - "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'MATERIAL', 3, 'RATING' )" - ).executeUpdate(); - - session.createNativeQuery( - "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'MATERIAL', 2, 'SIZE' )" - ).executeUpdate(); - - session.createNativeQuery( - "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'BUILDING', 1, 'RATING' )" - ).executeUpdate(); - - session.createNativeQuery( - "insert into ASSOCIATION_TABLE(MAIN_ID, MAIN_CODE, ASSOCIATION_ID, ASSOCIATION_CODE) " + - "VALUES( 1, 'BUILDING', 1, 'SIZE' )" - ).executeUpdate(); - - session.createNativeQuery( - "insert into MATERIAL_RATINGS(MATERIAL_ID, RATING_ID) VALUES( 1, 1 )" - ).executeUpdate(); - - session.createNativeQuery( - "insert into BUILDING_RATINGS(BUILDING_ID, RATING_ID) VALUES( 1, 1 )" - ).executeUpdate(); - session.createNativeQuery( - "insert into BUILDING_RATINGS(BUILDING_ID, RATING_ID) VALUES( 1, 2 )" - ).executeUpdate(); - session.createNativeQuery( - "insert into BUILDING_RATINGS(BUILDING_ID, RATING_ID) VALUES( 1, 3 )" - ).executeUpdate(); - } - ); - } - - @After - public void cleanup() { - doInHibernate( - this::sessionFactory, session -> { - session.createNativeQuery( "delete from MATERIAL_RATINGS" ).executeUpdate(); - session.createNativeQuery( "delete from BUILDING_RATINGS" ).executeUpdate(); - session.createNativeQuery( "delete from ASSOCIATION_TABLE" ).executeUpdate(); - session.createNativeQuery( "delete from MAIN_TABLE" ).executeUpdate(); - } - ); + @AfterAll + public void dropSchema(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test @JiraKey( value = "HHH-12875") - public void testInitializeFromUniqueAssociationTable() { - doInHibernate( - this::sessionFactory, session -> { - - Material material = session.get( Material.class, 1 ); - assertEquals( "plastic", material.getName() ); - - // Material#ratings is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( material.getRatings() ) ); - assertEquals( 1, material.getRatings().size() ); - assertTrue( Hibernate.isInitialized( material.getRatings() ) ); - - final Rating rating = material.getRatings().iterator().next(); - assertEquals( "high", rating.getName() ); - - Building building = session.get( Building.class, 1 ); - assertEquals( "house", building.getName() ); - - // Building#ratings is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( building.getMediumOrHighRatings() ) ); - checkMediumOrHighRatings( building.getMediumOrHighRatings() ); - } - ); + public void testInitializeFromUniqueAssociationTable(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + Material material = session.find( Material.class, 1 ); + assertEquals( "plastic", material.getName() ); + + // Material#ratings is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( material.getRatings() ) ); + assertEquals( 1, material.getRatings().size() ); + assertTrue( Hibernate.isInitialized( material.getRatings() ) ); + + final Rating rating = material.getRatings().iterator().next(); + assertEquals( "high", rating.getName() ); + + Building building = session.find( Building.class, 1 ); + assertEquals( "house", building.getName() ); + + // Building#ratings is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( building.getMediumOrHighRatings() ) ); + checkMediumOrHighRatings( building.getMediumOrHighRatings() ); + } ); } @Test @JiraKey( value = "HHH-12875") - public void testInitializeFromNonUniqueAssociationTable() { - doInHibernate( - this::sessionFactory, session -> { - - Material material = session.get( Material.class, 1 ); - assertEquals( "plastic", material.getName() ); - - // Material#mediumOrHighRatingsFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( material.getMediumOrHighRatingsFromCombined() ) ); - checkMediumOrHighRatings( material.getMediumOrHighRatingsFromCombined() ); - Rating highRating = null; - for ( Rating rating : material.getMediumOrHighRatingsFromCombined() ) { - if ( "high".equals( rating.getName() ) ) { - highRating = rating; - } - } - assertNotNull( highRating ); - - // Material#sizesFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( material.getSizesFromCombined() ) ); - assertEquals( 1, material.getSizesFromCombined().size() ); - assertTrue( Hibernate.isInitialized( material.getSizesFromCombined() ) ); - - final Size size = material.getSizesFromCombined().iterator().next(); - assertEquals( "medium", size.getName() ); - - Building building = session.get( Building.class, 1 ); - - // building.ratingsFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( building.getRatingsFromCombined() ) ); - assertEquals( 1, building.getRatingsFromCombined().size() ); - assertTrue( Hibernate.isInitialized( building.getRatingsFromCombined() ) ); - assertSame( highRating, building.getRatingsFromCombined().iterator().next() ); - - // Building#sizesFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( building.getSizesFromCombined() ) ); - assertEquals( 1, building.getSizesFromCombined().size() ); - assertTrue( Hibernate.isInitialized( building.getSizesFromCombined() ) ); - assertEquals( "small", building.getSizesFromCombined().iterator().next().getName() ); + public void testInitializeFromNonUniqueAssociationTable(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + Material material = session.find( Material.class, 1 ); + assertEquals( "plastic", material.getName() ); + + // Material#mediumOrHighRatingsFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( material.getMediumOrHighRatingsFromCombined() ) ); + checkMediumOrHighRatings( material.getMediumOrHighRatingsFromCombined() ); + Rating highRating = null; + for ( Rating rating : material.getMediumOrHighRatingsFromCombined() ) { + if ( "high".equals( rating.getName() ) ) { + highRating = rating; } - ); + } + assertNotNull( highRating ); + + // Material#sizesFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( material.getSizesFromCombined() ) ); + assertEquals( 1, material.getSizesFromCombined().size() ); + assertTrue( Hibernate.isInitialized( material.getSizesFromCombined() ) ); + + final Size size = material.getSizesFromCombined().iterator().next(); + assertEquals( "medium", size.getName() ); + + Building building = session.find( Building.class, 1 ); + + // building.ratingsFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( building.getRatingsFromCombined() ) ); + assertEquals( 1, building.getRatingsFromCombined().size() ); + assertTrue( Hibernate.isInitialized( building.getRatingsFromCombined() ) ); + assertSame( highRating, building.getRatingsFromCombined().iterator().next() ); + + // Building#sizesFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( building.getSizesFromCombined() ) ); + assertEquals( 1, building.getSizesFromCombined().size() ); + assertTrue( Hibernate.isInitialized( building.getSizesFromCombined() ) ); + assertEquals( "small", building.getSizesFromCombined().iterator().next().getName() ); + } ); } private void checkMediumOrHighRatings(List mediumOrHighRatings) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyOneToManyNonUniqueIdWhereTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyOneToManyNonUniqueIdWhereTest.java index 5cdb25239d9a..9e490795e686 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyOneToManyNonUniqueIdWhereTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyOneToManyNonUniqueIdWhereTest.java @@ -4,139 +4,114 @@ */ package org.hibernate.orm.test.where.hbm; +import org.hibernate.Hibernate; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.sql.Statement; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; -import org.hibernate.Hibernate; - -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.hibernate.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.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Gail Badner */ -public class LazyOneToManyNonUniqueIdWhereTest extends BaseCoreFunctionalTestCase { - - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(xmlMappings = "hbm/where/LazyOneToManyNonUniqueIdWhereTest.hbm.xml") +@SessionFactory(exportSchema = false) +public class LazyOneToManyNonUniqueIdWhereTest { + @BeforeAll + public void createSchema(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> session.doWork( (connection) -> { + var dialect = session.getDialect(); + try (Statement statement = connection.createStatement()) { + statement.executeUpdate( dialect.getDropTableString( "MAIN_TABLE" ) ); + + statement.executeUpdate( """ + create table MAIN_TABLE( + ID integer not null, + NAME varchar(255) not null, + CODE varchar(10) not null, + MATERIAL_OWNER_ID integer, + BUILDING_OWNER_ID integer, + primary key (ID, CODE) + )""" ); + + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'plastic', 'MATERIAL' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'house', 'BUILDING' )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE, MATERIAL_OWNER_ID, BUILDING_OWNER_ID) " + + "VALUES( 1, 'high', 'RATING', 1, 1 )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE, MATERIAL_OWNER_ID, BUILDING_OWNER_ID) " + + "VALUES( 2, 'medium', 'RATING', 1, null )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE, MATERIAL_OWNER_ID, BUILDING_OWNER_ID) " + + "VALUES( 3, 'low', 'RATING', 1, null )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE, MATERIAL_OWNER_ID, BUILDING_OWNER_ID) " + + "VALUES( 1, 'small', 'SIZE', null, 1 )" ); + statement.executeUpdate( "insert into MAIN_TABLE(ID, NAME, CODE, MATERIAL_OWNER_ID, BUILDING_OWNER_ID) " + + "VALUES( 2, 'medium', 'SIZE', 1, null )" ); + } + } ) ); } - @Override - protected String[] getMappings() { - return new String[] { "where/hbm/LazyOneToManyNonUniqueIdWhereTest.hbm.xml" }; - } - - @Before - public void setup() { - doInHibernate( - this::sessionFactory, session -> { - session.createNativeQuery( getDialect().getDropTableString( "MAIN_TABLE" ) ).executeUpdate(); - } - ); - - doInHibernate( - this::sessionFactory, session -> { - session.createNativeQuery( - "create table MAIN_TABLE( " + - "ID integer not null, NAME varchar(255) not null, CODE varchar(10) not null, " + - "MATERIAL_OWNER_ID integer, BUILDING_OWNER_ID integer, " + - "primary key (ID, CODE) )" - ).executeUpdate(); - } - ); - - doInHibernate( - this::sessionFactory, session -> { - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'plastic', 'MATERIAL' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE) VALUES( 1, 'house', 'BUILDING' )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE, MATERIAL_OWNER_ID, BUILDING_OWNER_ID) " + - "VALUES( 1, 'high', 'RATING', 1, 1 )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE, MATERIAL_OWNER_ID, BUILDING_OWNER_ID) " + - "VALUES( 2, 'medium', 'RATING', 1, null )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE, MATERIAL_OWNER_ID, BUILDING_OWNER_ID) " + - "VALUES( 3, 'low', 'RATING', 1, null )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE, MATERIAL_OWNER_ID, BUILDING_OWNER_ID) " + - "VALUES( 1, 'small', 'SIZE', null, 1 )" ) - .executeUpdate(); - session.createNativeQuery( "insert into MAIN_TABLE(ID, NAME, CODE, MATERIAL_OWNER_ID, BUILDING_OWNER_ID) " + - "VALUES( 2, 'medium', 'SIZE', 1, null )" ) - .executeUpdate(); - } - ); - } - - @After - public void cleanup() { - doInHibernate( - this::sessionFactory, session -> { - session.createNativeQuery( "delete from MAIN_TABLE" ).executeUpdate(); - } - ); + @AfterAll + public void dropSchema(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test @JiraKey( value = "HHH-12875") - public void testInitializeFromNonUniqueAssociationTable() { - doInHibernate( - this::sessionFactory, session -> { - - Material material = session.get( Material.class, 1 ); - assertEquals( "plastic", material.getName() ); - - // Material#mediumOrHighRatingsFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( material.getMediumOrHighRatingsFromCombined() ) ); - checkMediumOrHighRatings( material.getMediumOrHighRatingsFromCombined() ); - Rating highRating = null; - for ( Rating rating : material.getMediumOrHighRatingsFromCombined() ) { - if ( "high".equals( rating.getName() ) ) { - highRating = rating; - } - } - assertNotNull( highRating ); - - // Material#sizesFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( material.getSizesFromCombined() ) ); - assertEquals( 1, material.getSizesFromCombined().size() ); - assertTrue( Hibernate.isInitialized( material.getSizesFromCombined() ) ); - - final Size size = material.getSizesFromCombined().iterator().next(); - assertEquals( "medium", size.getName() ); - - Building building = session.get( Building.class, 1 ); - - // building.ratingsFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( building.getRatingsFromCombined() ) ); - assertEquals( 1, building.getRatingsFromCombined().size() ); - assertTrue( Hibernate.isInitialized( building.getRatingsFromCombined() ) ); - assertSame( highRating, building.getRatingsFromCombined().iterator().next() ); - - // Building#sizesFromCombined is mapped with lazy="true" - assertFalse( Hibernate.isInitialized( building.getSizesFromCombined() ) ); - assertEquals( 1, building.getSizesFromCombined().size() ); - assertTrue( Hibernate.isInitialized( building.getSizesFromCombined() ) ); - assertEquals( "small", building.getSizesFromCombined().iterator().next().getName() ); + public void testInitializeFromNonUniqueAssociationTable(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> { + Material material = session.find( Material.class, 1 ); + assertEquals( "plastic", material.getName() ); + + // Material#mediumOrHighRatingsFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( material.getMediumOrHighRatingsFromCombined() ) ); + checkMediumOrHighRatings( material.getMediumOrHighRatingsFromCombined() ); + Rating highRating = null; + for ( Rating rating : material.getMediumOrHighRatingsFromCombined() ) { + if ( "high".equals( rating.getName() ) ) { + highRating = rating; } - ); + } + assertNotNull( highRating ); + + // Material#sizesFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( material.getSizesFromCombined() ) ); + assertEquals( 1, material.getSizesFromCombined().size() ); + assertTrue( Hibernate.isInitialized( material.getSizesFromCombined() ) ); + + final Size size = material.getSizesFromCombined().iterator().next(); + assertEquals( "medium", size.getName() ); + + Building building = session.find( Building.class, 1 ); + + // building.ratingsFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( building.getRatingsFromCombined() ) ); + assertEquals( 1, building.getRatingsFromCombined().size() ); + assertTrue( Hibernate.isInitialized( building.getRatingsFromCombined() ) ); + assertSame( highRating, building.getRatingsFromCombined().iterator().next() ); + + // Building#sizesFromCombined is mapped with lazy="true" + assertFalse( Hibernate.isInitialized( building.getSizesFromCombined() ) ); + assertEquals( 1, building.getSizesFromCombined().size() ); + assertTrue( Hibernate.isInitialized( building.getSizesFromCombined() ) ); + assertEquals( "small", building.getSizesFromCombined().iterator().next().getName() ); + } ); } private void checkMediumOrHighRatings(List mediumOrHighRatings) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyToManyWhereTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyToManyWhereTest.java index 9e82c67203e0..591c59f204c2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyToManyWhereTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyToManyWhereTest.java @@ -8,15 +8,17 @@ import java.util.HashSet; import java.util.Set; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests association collections with default AvailableSettings.USE_ENTITY_WHERE_CLAUSE_FOR_COLLECTIONS, @@ -24,22 +26,18 @@ * * @author Gail Badner */ -public class LazyToManyWhereTest extends BaseNonConfigCoreFunctionalTestCase { - - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } - - @Override - protected String[] getMappings() { - return new String[] { "where/hbm/LazyToManyWhere.hbm.xml" }; +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(xmlMappings = "hbm/where/LazyToManyWhere.hbm.xml") +@SessionFactory +public class LazyToManyWhereTest { + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test @JiraKey( value = "HHH-13011" ) - public void testAssociatedWhereClause() { - + public void testAssociatedWhereClause(SessionFactoryScope factoryScope) { Product product = new Product(); Category flowers = new Category(); flowers.setId( 1 ); @@ -78,69 +76,54 @@ public void testAssociatedWhereClause() { product.getCategoriesWithDescManyToMany().add( building ); product.getCategoriesWithDescIdLt4ManyToMany().add( building ); - doInHibernate( - this::sessionFactory, - session -> { - session.persist( flowers ); - session.persist( vegetables ); - session.persist( dogs ); - session.persist( building ); - session.persist( product ); - } - ); + factoryScope.inTransaction( (session) -> { + session.persist( flowers ); + session.persist( vegetables ); + session.persist( dogs ); + session.persist( building ); + session.persist( product ); + } ); - doInHibernate( - this::sessionFactory, - session -> { - Product p = session.get( Product.class, product.getId() ); - assertNotNull( p ); - assertEquals( 4, p.getCategoriesOneToMany().size() ); - checkIds( p.getCategoriesOneToMany(), new Integer[] { 1, 2, 3, 4 } ); - assertEquals( 3, p.getCategoriesWithDescOneToMany().size() ); - checkIds( p.getCategoriesWithDescOneToMany(), new Integer[] { 1, 2, 4 } ); - assertEquals( 4, p.getCategoriesManyToMany().size() ); - checkIds( p.getCategoriesManyToMany(), new Integer[] { 1, 2, 3, 4 } ); - assertEquals( 3, p.getCategoriesWithDescManyToMany().size() ); - checkIds( p.getCategoriesWithDescManyToMany(), new Integer[] { 1, 2, 4 } ); - assertEquals( 2, p.getCategoriesWithDescIdLt4ManyToMany().size() ); - checkIds( p.getCategoriesWithDescIdLt4ManyToMany(), new Integer[] { 1, 2 } ); - } - ); + factoryScope.inTransaction( (session) -> { + Product p = session.find( Product.class, product.getId() ); + assertNotNull( p ); + assertEquals( 4, p.getCategoriesOneToMany().size() ); + checkIds( p.getCategoriesOneToMany(), new Integer[] { 1, 2, 3, 4 } ); + assertEquals( 3, p.getCategoriesWithDescOneToMany().size() ); + checkIds( p.getCategoriesWithDescOneToMany(), new Integer[] { 1, 2, 4 } ); + assertEquals( 4, p.getCategoriesManyToMany().size() ); + checkIds( p.getCategoriesManyToMany(), new Integer[] { 1, 2, 3, 4 } ); + assertEquals( 3, p.getCategoriesWithDescManyToMany().size() ); + checkIds( p.getCategoriesWithDescManyToMany(), new Integer[] { 1, 2, 4 } ); + assertEquals( 2, p.getCategoriesWithDescIdLt4ManyToMany().size() ); + checkIds( p.getCategoriesWithDescIdLt4ManyToMany(), new Integer[] { 1, 2 } ); + } ); - doInHibernate( - this::sessionFactory, - session -> { - Category c = session.get( Category.class, flowers.getId() ); - assertNotNull( c ); - c.setInactive( 1 ); - } - ); + factoryScope.inTransaction( (session) -> { + Category c = session.find( Category.class, flowers.getId() ); + assertNotNull( c ); + c.setInactive( 1 ); + } ); - doInHibernate( - this::sessionFactory, - session -> { - Category c = session.get( Category.class, flowers.getId() ); - assertNull( c ); - } - ); + factoryScope.inTransaction( (session) -> { + Category c = session.find( Category.class, flowers.getId() ); + assertNull( c ); + } ); - doInHibernate( - this::sessionFactory, - session -> { - Product p = session.get( Product.class, product.getId() ); - assertNotNull( p ); - assertEquals( 3, p.getCategoriesOneToMany().size() ); - checkIds( p.getCategoriesOneToMany(), new Integer[] { 2, 3, 4 } ); - assertEquals( 2, p.getCategoriesWithDescOneToMany().size() ); - checkIds( p.getCategoriesWithDescOneToMany(), new Integer[] { 2, 4 } ); - assertEquals( 3, p.getCategoriesManyToMany().size() ); - checkIds( p.getCategoriesManyToMany(), new Integer[] { 2, 3, 4 } ); - assertEquals( 2, p.getCategoriesWithDescManyToMany().size() ); - checkIds( p.getCategoriesWithDescManyToMany(), new Integer[] { 2, 4 } ); - assertEquals( 1, p.getCategoriesWithDescIdLt4ManyToMany().size() ); - checkIds( p.getCategoriesWithDescIdLt4ManyToMany(), new Integer[] { 2 } ); - } - ); + factoryScope.inTransaction( (session) -> { + Product p = session.find( Product.class, product.getId() ); + assertNotNull( p ); + assertEquals( 3, p.getCategoriesOneToMany().size() ); + checkIds( p.getCategoriesOneToMany(), new Integer[] { 2, 3, 4 } ); + assertEquals( 2, p.getCategoriesWithDescOneToMany().size() ); + checkIds( p.getCategoriesWithDescOneToMany(), new Integer[] { 2, 4 } ); + assertEquals( 3, p.getCategoriesManyToMany().size() ); + checkIds( p.getCategoriesManyToMany(), new Integer[] { 2, 3, 4 } ); + assertEquals( 2, p.getCategoriesWithDescManyToMany().size() ); + checkIds( p.getCategoriesWithDescManyToMany(), new Integer[] { 2, 4 } ); + assertEquals( 1, p.getCategoriesWithDescIdLt4ManyToMany().size() ); + checkIds( p.getCategoriesWithDescIdLt4ManyToMany(), new Integer[] { 2 } ); + } ); } private void checkIds(Set categories, Integer[] expectedIds) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyToManyWhereUseClassWhereTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyToManyWhereUseClassWhereTest.java index 3d19a3a610e5..b45c7b1c9317 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyToManyWhereUseClassWhereTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyToManyWhereUseClassWhereTest.java @@ -4,39 +4,38 @@ */ package org.hibernate.orm.test.where.hbm; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + import java.util.Arrays; import java.util.HashSet; import java.util.Set; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Gail Badner */ -public class LazyToManyWhereUseClassWhereTest extends BaseNonConfigCoreFunctionalTestCase { +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(xmlMappings = "hbm/where/LazyToManyWhere.hbm.xml") +@SessionFactory +public class LazyToManyWhereUseClassWhereTest { - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } - - @Override - protected String[] getMappings() { - return new String[] { "where/hbm/LazyToManyWhere.hbm.xml" }; + @AfterEach + void dropTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test @JiraKey( "HHH-13011" ) - public void testAssociatedWhereClause() { - + public void testAssociatedWhereClause(SessionFactoryScope factoryScope) { Product product = new Product(); Category flowers = new Category(); flowers.setId( 1 ); @@ -75,69 +74,54 @@ public void testAssociatedWhereClause() { product.getCategoriesWithDescManyToMany().add( building ); product.getCategoriesWithDescIdLt4ManyToMany().add( building ); - doInHibernate( - this::sessionFactory, - session -> { - session.persist( flowers ); - session.persist( vegetables ); - session.persist( dogs ); - session.persist( building ); - session.persist( product ); - } - ); + factoryScope.inTransaction( (session) -> { + session.persist( flowers ); + session.persist( vegetables ); + session.persist( dogs ); + session.persist( building ); + session.persist( product ); + } ); - doInHibernate( - this::sessionFactory, - session -> { - Product p = session.get( Product.class, product.getId() ); - assertNotNull( p ); - assertEquals( 4, p.getCategoriesOneToMany().size() ); - checkIds( p.getCategoriesOneToMany(), new Integer[] { 1, 2, 3, 4 } ); - assertEquals( 3, p.getCategoriesWithDescOneToMany().size() ); - checkIds( p.getCategoriesWithDescOneToMany(), new Integer[] { 1, 2, 4 } ); - assertEquals( 4, p.getCategoriesManyToMany().size() ); - checkIds( p.getCategoriesManyToMany(), new Integer[] { 1, 2, 3, 4 } ); - assertEquals( 3, p.getCategoriesWithDescManyToMany().size() ); - checkIds( p.getCategoriesWithDescManyToMany(), new Integer[] { 1, 2, 4 } ); - assertEquals( 2, p.getCategoriesWithDescIdLt4ManyToMany().size() ); - checkIds( p.getCategoriesWithDescIdLt4ManyToMany(), new Integer[] { 1, 2 } ); - } - ); + factoryScope.inTransaction( (session) -> { + Product p = session.find( Product.class, product.getId() ); + assertNotNull( p ); + assertEquals( 4, p.getCategoriesOneToMany().size() ); + checkIds( p.getCategoriesOneToMany(), new Integer[] { 1, 2, 3, 4 } ); + assertEquals( 3, p.getCategoriesWithDescOneToMany().size() ); + checkIds( p.getCategoriesWithDescOneToMany(), new Integer[] { 1, 2, 4 } ); + assertEquals( 4, p.getCategoriesManyToMany().size() ); + checkIds( p.getCategoriesManyToMany(), new Integer[] { 1, 2, 3, 4 } ); + assertEquals( 3, p.getCategoriesWithDescManyToMany().size() ); + checkIds( p.getCategoriesWithDescManyToMany(), new Integer[] { 1, 2, 4 } ); + assertEquals( 2, p.getCategoriesWithDescIdLt4ManyToMany().size() ); + checkIds( p.getCategoriesWithDescIdLt4ManyToMany(), new Integer[] { 1, 2 } ); + } ); - doInHibernate( - this::sessionFactory, - session -> { - Category c = session.get( Category.class, flowers.getId() ); - assertNotNull( c ); - c.setInactive( 1 ); - } - ); + factoryScope.inTransaction( (session) -> { + Category c = session.find( Category.class, flowers.getId() ); + assertNotNull( c ); + c.setInactive( 1 ); + } ); - doInHibernate( - this::sessionFactory, - session -> { - Category c = session.get( Category.class, flowers.getId() ); - assertNull( c ); - } - ); + factoryScope.inTransaction( (session) -> { + Category c = session.find( Category.class, flowers.getId() ); + assertNull( c ); + } ); - doInHibernate( - this::sessionFactory, - session -> { - Product p = session.get( Product.class, product.getId() ); - assertNotNull( p ); - assertEquals( 3, p.getCategoriesOneToMany().size() ); - checkIds( p.getCategoriesOneToMany(), new Integer[] { 2, 3, 4 } ); - assertEquals( 2, p.getCategoriesWithDescOneToMany().size() ); - checkIds( p.getCategoriesWithDescOneToMany(), new Integer[] { 2, 4 } ); - assertEquals( 3, p.getCategoriesManyToMany().size() ); - checkIds( p.getCategoriesManyToMany(), new Integer[] { 2, 3, 4 } ); - assertEquals( 2, p.getCategoriesWithDescManyToMany().size() ); - checkIds( p.getCategoriesWithDescManyToMany(), new Integer[] { 2, 4 } ); - assertEquals( 1, p.getCategoriesWithDescIdLt4ManyToMany().size() ); - checkIds( p.getCategoriesWithDescIdLt4ManyToMany(), new Integer[] { 2 } ); - } - ); + factoryScope.inTransaction( (session) -> { + Product p = session.find( Product.class, product.getId() ); + assertNotNull( p ); + assertEquals( 3, p.getCategoriesOneToMany().size() ); + checkIds( p.getCategoriesOneToMany(), new Integer[] { 2, 3, 4 } ); + assertEquals( 2, p.getCategoriesWithDescOneToMany().size() ); + checkIds( p.getCategoriesWithDescOneToMany(), new Integer[] { 2, 4 } ); + assertEquals( 3, p.getCategoriesManyToMany().size() ); + checkIds( p.getCategoriesManyToMany(), new Integer[] { 2, 3, 4 } ); + assertEquals( 2, p.getCategoriesWithDescManyToMany().size() ); + checkIds( p.getCategoriesWithDescManyToMany(), new Integer[] { 2, 4 } ); + assertEquals( 1, p.getCategoriesWithDescIdLt4ManyToMany().size() ); + checkIds( p.getCategoriesWithDescIdLt4ManyToMany(), new Integer[] { 2 } ); + } ); } private void checkIds(Set categories, Integer[] expectedIds) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/WhereTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/WhereTest.java index be15391a23ac..0d31695b5ac5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/WhereTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/WhereTest.java @@ -4,131 +4,104 @@ */ package org.hibernate.orm.test.where.hbm; -import java.util.HashSet; -import java.util.List; - import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.JoinType; import jakarta.persistence.criteria.Root; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - import org.hibernate.Hibernate; import org.hibernate.query.NativeQuery; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; /** * @author Max Rydahl Andersen */ -public class WhereTest extends BaseCoreFunctionalTestCase { - - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(xmlMappings = "hbm/where/File.hbm.xml") +@SessionFactory +public class WhereTest { + @BeforeEach + public void createTestData(SessionFactoryScope factoryScope) { + // `parent` has no parent + // `deleted parent` has no parent + // `child` has `parent` for parent + // `deleted child` has `parent` for parent + factoryScope.inTransaction(s -> { + File parent = new File("parent", null); + s.persist( parent ); + s.persist( new File("child", parent) ); + File deletedChild = new File("deleted child", parent); + deletedChild.setDeleted(true); + s.persist( deletedChild ); + File deletedParent = new File("deleted parent", null); + deletedParent.setDeleted(true); + s.persist( deletedParent ); + } ); } - @Override - public String[] getMappings() { - return new String[] { "where/hbm/File.hbm.xml" }; - } - - @Before - public void createTestData() { - inTransaction( - s -> { - // `parent` has no parent - // `deleted parent` has no parent - // `child` has `parent` for parent - // `deleted child` has `parent` for parent - File parent = new File("parent", null); - s.persist( parent ); - s.persist( new File("child", parent) ); - File deletedChild = new File("deleted child", parent); - deletedChild.setDeleted(true); - s.persist( deletedChild ); - File deletedParent = new File("deleted parent", null); - deletedParent.setDeleted(true); - s.persist( deletedParent ); - } - ); - } - - @After - public void removeTestData() { - inTransaction( - s -> { - s.createNativeQuery( "update T_FILE set parent = null" ).executeUpdate(); - s.createNativeQuery( "delete from T_FILE" ).executeUpdate(); - } - ); + @AfterEach + public void removeTestData(SessionFactoryScope factoryScope) { + factoryScope.dropData(); } @Test - public void testHql() { - inTransaction( - s -> { - File parent = s.createQuery("from File f where f.id = 4", File.class ) - .uniqueResult(); - - assertNull( parent ); - } - ); + public void testHql(SessionFactoryScope factoryScope) { + factoryScope.inTransaction(s -> { + var parent = s.createQuery("from File f where f.id = 4", File.class ).uniqueResult(); + assertNull( parent ); + } ); } @Test - public void testHqlWithFetch() { - inTransaction( - s -> { - final List files = s.createQuery( - "from File f left join fetch f.children where f.parent is null", - File.class - ).list(); - final HashSet filesSet = new HashSet<>( files ); - assertEquals( 1, filesSet.size() ); - File parent = files.get( 0 ); - assertEquals( 1, parent.getChildren().size() ); - } - ); + public void testHqlWithFetch(SessionFactoryScope factoryScope) { + factoryScope.inTransaction(s -> { + final List files = s.createQuery( + "from File f left join fetch f.children where f.parent is null", + File.class + ).list(); + assertEquals( 1, files.size() ); + File parent = files.get( 0 ); + assertEquals( 1, parent.getChildren().size() ); + } ); } @Test - public void testCriteria() { - inTransaction( - s -> { - CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); - CriteriaQuery criteria = criteriaBuilder.createQuery( File.class ); - Root root = criteria.from( File.class ); - root.fetch( "children", JoinType.LEFT ); - criteria.where( criteriaBuilder.isNull( root.get("parent") )); - File parent = s.createQuery( criteria ).uniqueResult(); - assertEquals( parent.getChildren().size(), 1 ); - assertEquals( 1, parent.getChildren().size() ); - } - ); + public void testCriteria(SessionFactoryScope factoryScope) { + factoryScope.inTransaction(s -> { + CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); + CriteriaQuery criteria = criteriaBuilder.createQuery( File.class ); + Root root = criteria.from( File.class ); + root.fetch( "children", JoinType.LEFT ); + criteria.where( criteriaBuilder.isNull( root.get("parent") )); + File parent = s.createQuery( criteria ).uniqueResult(); + assertEquals( parent.getChildren().size(), 1 ); + assertEquals( 1, parent.getChildren().size() ); + } ); } @Test - public void testNativeQuery() { - inTransaction( - s -> { - final NativeQuery query = s.createNativeQuery( - "select {f.*}, {c.*} from T_FILE f left join T_FILE c on f.id = c.parent where f.parent is null" ) - .addEntity( "f", File.class ); - query.addFetch( "c", "f", "children" ); - - File parent = (File) query.list().get( 0 ); - // @Where should not be applied - assertTrue( Hibernate.isInitialized( parent.getChildren() ) ); - assertEquals( 2, parent.getChildren().size() ); - } - ); + public void testNativeQuery(SessionFactoryScope factoryScope) { + factoryScope.inTransaction(s -> { + final NativeQuery query = s.createNativeQuery( + "select {f.*}, {c.*} from T_FILE f left join T_FILE c on f.id = c.parent where f.parent is null" ) + .addEntity( "f", File.class ); + query.addFetch( "c", "f", "children" ); + + File parent = (File) query.list().get( 0 ); + // @Where should not be applied + assertTrue( Hibernate.isInitialized( parent.getChildren() ) ); + assertEquals( 2, parent.getChildren().size() ); + } ); } } diff --git a/hibernate-core/src/test/resources/org/hibernate/orm/test/where/hbm/EagerManyToOneFetchModeJoinWhereTest.hbm.xml b/hibernate-core/src/test/resources/hbm/where/EagerManyToOneFetchModeJoinWhereTest.hbm.xml similarity index 100% rename from hibernate-core/src/test/resources/org/hibernate/orm/test/where/hbm/EagerManyToOneFetchModeJoinWhereTest.hbm.xml rename to hibernate-core/src/test/resources/hbm/where/EagerManyToOneFetchModeJoinWhereTest.hbm.xml diff --git a/hibernate-core/src/test/resources/org/hibernate/orm/test/where/hbm/EagerManyToOneFetchModeSelectWhereTest.hbm.xml b/hibernate-core/src/test/resources/hbm/where/EagerManyToOneFetchModeSelectWhereTest.hbm.xml similarity index 100% rename from hibernate-core/src/test/resources/org/hibernate/orm/test/where/hbm/EagerManyToOneFetchModeSelectWhereTest.hbm.xml rename to hibernate-core/src/test/resources/hbm/where/EagerManyToOneFetchModeSelectWhereTest.hbm.xml diff --git a/hibernate-core/src/test/resources/org/hibernate/orm/test/where/hbm/EagerToManyWhere.hbm.xml b/hibernate-core/src/test/resources/hbm/where/EagerToManyWhere.hbm.xml similarity index 100% rename from hibernate-core/src/test/resources/org/hibernate/orm/test/where/hbm/EagerToManyWhere.hbm.xml rename to hibernate-core/src/test/resources/hbm/where/EagerToManyWhere.hbm.xml diff --git a/hibernate-core/src/test/resources/org/hibernate/orm/test/where/hbm/File.hbm.xml b/hibernate-core/src/test/resources/hbm/where/File.hbm.xml similarity index 100% rename from hibernate-core/src/test/resources/org/hibernate/orm/test/where/hbm/File.hbm.xml rename to hibernate-core/src/test/resources/hbm/where/File.hbm.xml diff --git a/hibernate-core/src/test/resources/org/hibernate/orm/test/where/hbm/LazyElementCollectionBasicNonUniqueIdWhereTest.hbm.xml b/hibernate-core/src/test/resources/hbm/where/LazyElementCollectionBasicNonUniqueIdWhereTest.hbm.xml similarity index 100% rename from hibernate-core/src/test/resources/org/hibernate/orm/test/where/hbm/LazyElementCollectionBasicNonUniqueIdWhereTest.hbm.xml rename to hibernate-core/src/test/resources/hbm/where/LazyElementCollectionBasicNonUniqueIdWhereTest.hbm.xml diff --git a/hibernate-core/src/test/resources/org/hibernate/orm/test/where/hbm/LazyElementCollectionWithLazyManyToOneNonUniqueIdWhereTest.hbm.xml b/hibernate-core/src/test/resources/hbm/where/LazyElementCollectionWithLazyManyToOneNonUniqueIdWhereTest.hbm.xml similarity index 100% rename from hibernate-core/src/test/resources/org/hibernate/orm/test/where/hbm/LazyElementCollectionWithLazyManyToOneNonUniqueIdWhereTest.hbm.xml rename to hibernate-core/src/test/resources/hbm/where/LazyElementCollectionWithLazyManyToOneNonUniqueIdWhereTest.hbm.xml diff --git a/hibernate-core/src/test/resources/org/hibernate/orm/test/where/hbm/LazyManyToManyNonUniqueIdNotFoundWhereTest.hbm.xml b/hibernate-core/src/test/resources/hbm/where/LazyManyToManyNonUniqueIdNotFoundWhereTest.hbm.xml similarity index 100% rename from hibernate-core/src/test/resources/org/hibernate/orm/test/where/hbm/LazyManyToManyNonUniqueIdNotFoundWhereTest.hbm.xml rename to hibernate-core/src/test/resources/hbm/where/LazyManyToManyNonUniqueIdNotFoundWhereTest.hbm.xml diff --git a/hibernate-core/src/test/resources/org/hibernate/orm/test/where/hbm/LazyManyToManyNonUniqueIdWhereTest.hbm.xml b/hibernate-core/src/test/resources/hbm/where/LazyManyToManyNonUniqueIdWhereTest.hbm.xml similarity index 100% rename from hibernate-core/src/test/resources/org/hibernate/orm/test/where/hbm/LazyManyToManyNonUniqueIdWhereTest.hbm.xml rename to hibernate-core/src/test/resources/hbm/where/LazyManyToManyNonUniqueIdWhereTest.hbm.xml diff --git a/hibernate-core/src/test/resources/org/hibernate/orm/test/where/hbm/LazyOneToManyNonUniqueIdWhereTest.hbm.xml b/hibernate-core/src/test/resources/hbm/where/LazyOneToManyNonUniqueIdWhereTest.hbm.xml similarity index 100% rename from hibernate-core/src/test/resources/org/hibernate/orm/test/where/hbm/LazyOneToManyNonUniqueIdWhereTest.hbm.xml rename to hibernate-core/src/test/resources/hbm/where/LazyOneToManyNonUniqueIdWhereTest.hbm.xml diff --git a/hibernate-core/src/test/resources/org/hibernate/orm/test/where/hbm/LazyToManyWhere.hbm.xml b/hibernate-core/src/test/resources/hbm/where/LazyToManyWhere.hbm.xml similarity index 100% rename from hibernate-core/src/test/resources/org/hibernate/orm/test/where/hbm/LazyToManyWhere.hbm.xml rename to hibernate-core/src/test/resources/hbm/where/LazyToManyWhere.hbm.xml diff --git a/hibernate-core/src/test/resources/org/hibernate/orm/test/fetchprofiles/join/Mappings.hbm.xml b/hibernate-core/src/test/resources/mappings/fetchprofile/Mappings.hbm.xml similarity index 83% rename from hibernate-core/src/test/resources/org/hibernate/orm/test/fetchprofiles/join/Mappings.hbm.xml rename to hibernate-core/src/test/resources/mappings/fetchprofile/Mappings.hbm.xml index d45e1310615f..601c8dc750f9 100644 --- a/hibernate-core/src/test/resources/org/hibernate/orm/test/fetchprofiles/join/Mappings.hbm.xml +++ b/hibernate-core/src/test/resources/mappings/fetchprofile/Mappings.hbm.xml @@ -10,24 +10,18 @@ - - - + - - - + - - - + @@ -39,9 +33,7 @@ - - - + @@ -59,9 +51,7 @@ - - - + diff --git a/hibernate-core/src/test/resources/org/hibernate/orm/test/ternary/Ternary.hbm.xml b/hibernate-core/src/test/resources/mappings/map/Ternary.hbm.xml similarity index 93% rename from hibernate-core/src/test/resources/org/hibernate/orm/test/ternary/Ternary.hbm.xml rename to hibernate-core/src/test/resources/mappings/map/Ternary.hbm.xml index 7a7ecece0117..3b0b308544df 100644 --- a/hibernate-core/src/test/resources/org/hibernate/orm/test/ternary/Ternary.hbm.xml +++ b/hibernate-core/src/test/resources/mappings/map/Ternary.hbm.xml @@ -7,6 +7,10 @@ "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> + + diff --git a/hibernate-core/src/test/resources/org/hibernate/orm/test/deletetransient/Person.hbm.xml b/hibernate-core/src/test/resources/org/hibernate/orm/test/deletetransient/Person.hbm.xml deleted file mode 100644 index c2ea11567824..000000000000 --- a/hibernate-core/src/test/resources/org/hibernate/orm/test/deletetransient/Person.hbm.xml +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/hibernate-core/src/test/resources/org/hibernate/orm/test/version/db/User.hbm.xml b/hibernate-core/src/test/resources/org/hibernate/orm/test/version/db/User.hbm.xml index 80fb281790e1..279d5294dff4 100644 --- a/hibernate-core/src/test/resources/org/hibernate/orm/test/version/db/User.hbm.xml +++ b/hibernate-core/src/test/resources/org/hibernate/orm/test/version/db/User.hbm.xml @@ -16,9 +16,7 @@ package="org.hibernate.orm.test.version.db"> - - - + @@ -32,9 +30,7 @@ - - - + @@ -44,9 +40,7 @@ - - - + diff --git a/hibernate-testing/src/main/java/org/hibernate/testing/junit4/BaseCoreFunctionalTestCase.java b/hibernate-testing/src/main/java/org/hibernate/testing/junit4/BaseCoreFunctionalTestCase.java index 40f494475a50..03fa6ffecfd4 100644 --- a/hibernate-testing/src/main/java/org/hibernate/testing/junit4/BaseCoreFunctionalTestCase.java +++ b/hibernate-testing/src/main/java/org/hibernate/testing/junit4/BaseCoreFunctionalTestCase.java @@ -63,7 +63,10 @@ * Applies functional testing logic for core Hibernate testing on top of {@link BaseUnitTestCase} * * @author Steve Ebersole + * + * @deprecated Use JUnit 5/6 */ +@Deprecated public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase { public static final String VALIDATE_DATA_CLEANUP = "hibernate.test.validateDataCleanup"; diff --git a/hibernate-testing/src/main/java/org/hibernate/testing/junit4/BaseNonConfigCoreFunctionalTestCase.java b/hibernate-testing/src/main/java/org/hibernate/testing/junit4/BaseNonConfigCoreFunctionalTestCase.java index e740c8e5613e..0b8d50e8ded5 100644 --- a/hibernate-testing/src/main/java/org/hibernate/testing/junit4/BaseNonConfigCoreFunctionalTestCase.java +++ b/hibernate-testing/src/main/java/org/hibernate/testing/junit4/BaseNonConfigCoreFunctionalTestCase.java @@ -67,7 +67,10 @@ * use (the neutered form of) Configuration. * * @author Steve Ebersole + * + * @deprecated Use JUnit 5/6 */ +@Deprecated public class BaseNonConfigCoreFunctionalTestCase extends BaseUnitTestCase { public static final String VALIDATE_DATA_CLEANUP = "hibernate.test.validateDataCleanup"; diff --git a/hibernate-testing/src/main/java/org/hibernate/testing/junit4/BaseUnitTestCase.java b/hibernate-testing/src/main/java/org/hibernate/testing/junit4/BaseUnitTestCase.java index 4d95f7e85790..14499705e2b6 100644 --- a/hibernate-testing/src/main/java/org/hibernate/testing/junit4/BaseUnitTestCase.java +++ b/hibernate-testing/src/main/java/org/hibernate/testing/junit4/BaseUnitTestCase.java @@ -28,7 +28,10 @@ * The base unit test adapter. * * @author Steve Ebersole + * + * @deprecated Use JUnit 5/6 */ +@Deprecated @RunWith( CustomRunner.class ) public abstract class BaseUnitTestCase { diff --git a/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/DialectFeatureChecks.java b/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/DialectFeatureChecks.java index b5c42c6c78cf..b3a3509ddb77 100644 --- a/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/DialectFeatureChecks.java +++ b/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/DialectFeatureChecks.java @@ -165,6 +165,18 @@ public boolean apply(Dialect dialect) { } } + public static class SupportsTemporaryTableIdentity implements DialectFeatureCheck { + public boolean apply(Dialect dialect) { + return dialect.getLocalTemporaryTableStrategy() != null + && dialect.getLocalTemporaryTableStrategy().supportsTemporaryTablePrimaryKey() + || dialect.getGlobalTemporaryTableStrategy() != null + && dialect.getGlobalTemporaryTableStrategy().supportsTemporaryTablePrimaryKey() + // Persistent tables definitely support identity + || dialect.getLocalTemporaryTableStrategy() == null + && dialect.getGlobalTemporaryTableStrategy() == null; + } + } + public static class SupportsColumnCheck implements DialectFeatureCheck { public boolean apply(Dialect dialect) { return dialect.supportsColumnCheck(); diff --git a/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/EntityManagerFactoryScope.java b/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/EntityManagerFactoryScope.java index 6c8c140307af..759d8496a426 100644 --- a/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/EntityManagerFactoryScope.java +++ b/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/EntityManagerFactoryScope.java @@ -38,4 +38,7 @@ default Dialect getDialect() { return ((SessionFactoryImplementor) getEntityManagerFactory()).getJdbcServices().getDialect(); } + default void dropData() { + ((SessionFactoryImplementor) getEntityManagerFactory()).getSchemaManager().truncateMappedObjects(); + } }