From 723735ca765ab84e2a1c18af6826290b16bd0394 Mon Sep 17 00:00:00 2001 From: Jan Schatteman Date: Thu, 14 Oct 2021 23:08:29 +0200 Subject: [PATCH] Use org.hibernate.testing.orm.junit.RequiresDialect instead of org.hibernate.testing.RequiresDialect and indicate Dialect version where needed. Signed-off-by: Jan Schatteman --- .../AbstractMetamodelSpecificTest.java | 25 +- .../orm/test/annotations/EntityTest.java | 640 ++++--- .../indexcoll/IndexedCollectionTest.java | 1502 +++++++++-------- .../test/component/basic/ComponentTest.java | 553 +++--- .../function/SybaseASE15FunctionTest.java | 137 -- .../function/SybaseASEFunctionTest.java | 131 ++ .../dialect/functional/HANASearchTest.java | 426 ++--- ...> MariaDBExtractSequenceMetadataTest.java} | 26 +- .../functional/OracleFollowOnLockingTest.java | 3 - .../functional/OracleSequenceInfoTest.java | 12 +- .../SequenceInformationMariaDBTest.java | 75 +- .../functional/SequenceInformationTest.java | 39 +- .../generatedkeys/select/MyEntity.hbm.xml | 2 +- .../select/SelectGeneratorTest.java | 47 +- .../JoinedSequenceIdentityBatchTest.java | 62 +- .../seqidentity/MyEntity.hbm.xml | 2 +- .../seqidentity/SequenceIdentityTest.java | 69 +- .../criteria/ManipulationCriteriaTest.java | 13 +- .../criteria/basic/AggregationResultTest.java | 17 +- .../jpa/criteria/basic/ExpressionsTest.java | 19 +- .../jpa/criteria/basic/ListIndexTest.java | 22 +- .../jpa/criteria/basic/PredicateTest.java | 39 +- .../idclass/IdClassPredicateTest.java | 16 +- .../jpa/criteria/mapjoin/MapJoinTest.java | 4 +- ...CriteriaLiteralInSelectExpressionTest.java | 252 ++- .../criteria/paths/AbstractPathImplTest.java | 21 +- .../jpa/criteria/paths/FetchAndJoinTest.java | 4 +- .../paths/PluralAttributeExpressionsTest.java | 7 +- .../subquery/CorrelatedSubqueryTest.java | 18 +- .../subquery/UncorrelatedSubqueryTest.java | 6 +- .../jpa/criteria/tuple/TupleCriteriaTest.java | 14 +- .../orm/test/jpa/lock/LockExceptionTests.java | 11 +- .../test/jpa/query/NamedQueryCommentTest.java | 297 ++-- .../NativeQueryOrdinalParametersTest.java | 200 +-- ...racleConstructorResultNativeQueryTest.java | 203 ++- ...bSelectCollectionDialectWithLimitTest.java | 2 +- .../locking/HANAOptimisticLockingTest.java | 106 +- .../orm/test/locking/LockModeTest.java | 55 +- .../mapping/generated/ComponentOwner.hbm.xml | 2 +- .../PartiallyGeneratedComponentTest.java | 76 +- .../procedure/OracleStoredProcedureTest.java | 2 +- .../MaxInExpressionParameterPaddingTest.java | 24 +- .../test/query/hql/CountExpressionTest.java | 5 - .../AbstractSkipAutoCommitTest.java | 70 +- .../jdbc/autocommit/H2SkipAutoCommitTest.java | 2 +- .../autocommit/MySQLSkipAutoCommitTest.java | 2 +- .../autocommit/OracleSkipAutoCommitTest.java | 6 +- .../PostgreSQLSkipAutoCommitTest.java | 2 +- .../SQLServerSkipAutoCommitTest.java | 2 +- .../AbstractAlterTableQuoteSchemaTest.java | 9 +- .../AlterTableQuoteDefaultSchemaTest.java | 80 +- .../AlterTableQuoteSpecifiedSchemaTest.java | 82 +- .../SchemaUpdateSchemaNameTest.java | 31 +- .../SynonymValidationTest.java | 35 +- .../BaseSessionFactoryFunctionalTest.java | 24 + ...tityManagerFactoryBasedFunctionalTest.java | 3 + .../testing/orm/junit/SettingProvider.java | 2 +- 57 files changed, 2855 insertions(+), 2681 deletions(-) delete mode 100644 hibernate-core/src/test/java/org/hibernate/orm/test/dialect/function/SybaseASE15FunctionTest.java create mode 100644 hibernate-core/src/test/java/org/hibernate/orm/test/dialect/function/SybaseASEFunctionTest.java rename hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/{MariaDBExtractSequenceMatadataTest.java => MariaDBExtractSequenceMetadataTest.java} (75%) diff --git a/hibernate-core/src/test/java/org/hibernate/jpa/test/metamodel/AbstractMetamodelSpecificTest.java b/hibernate-core/src/test/java/org/hibernate/jpa/test/metamodel/AbstractMetamodelSpecificTest.java index 9a79658665..4fb39e65cc 100644 --- a/hibernate-core/src/test/java/org/hibernate/jpa/test/metamodel/AbstractMetamodelSpecificTest.java +++ b/hibernate-core/src/test/java/org/hibernate/jpa/test/metamodel/AbstractMetamodelSpecificTest.java @@ -5,12 +5,26 @@ * See the lgpl.txt file in the root directory or . */ package org.hibernate.jpa.test.metamodel; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; + +import jakarta.persistence.EntityManager; + +import org.hibernate.testing.orm.junit.EntityManagerFactoryBasedFunctionalTest; +import org.junit.jupiter.api.AfterAll; /** * @author Steve Ebersole */ -public abstract class AbstractMetamodelSpecificTest extends BaseEntityManagerFunctionalTestCase { +public abstract class AbstractMetamodelSpecificTest extends EntityManagerFactoryBasedFunctionalTest { + + private EntityManager em; + + @AfterAll + public final void closeEntityManager() { + if ( em != null ) { + em.close(); + } + } + @Override public Class[] getAnnotatedClasses() { return new Class[] { @@ -21,4 +35,11 @@ public abstract class AbstractMetamodelSpecificTest extends BaseEntityManagerFun VersionedEntity.class }; } + + protected EntityManager getOrCreateEntityManager() { + if ( em == null || !em.isOpen() ) { + em = entityManagerFactory().createEntityManager(); + } + return em; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/EntityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/EntityTest.java index 56046bea8f..9185e9c580 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/EntityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/EntityTest.java @@ -18,182 +18,188 @@ import java.util.TimeZone; import jakarta.persistence.PersistenceException; import org.hibernate.HibernateException; -import org.hibernate.Session; import org.hibernate.StaleStateException; import org.hibernate.Transaction; -import org.hibernate.boot.MetadataBuilder; -import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.dialect.MySQLDialect; -import org.hibernate.dialect.Oracle10gDialect; +import org.hibernate.dialect.OracleDialect; import org.hibernate.query.Query; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.schema.TargetType; import org.hibernate.type.StandardBasicTypes; -import org.hibernate.testing.SkipForDialect; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.DomainModelScope; +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 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.fail; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Emmanuel Bernard */ -public class EntityTest extends BaseNonConfigCoreFunctionalTestCase { +@ServiceRegistry( + settings = { + @Setting(name = AvailableSettings.IMPLICIT_NAMING_STRATEGY, value = "org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl"), + @Setting(name = AvailableSettings.HBM2DDL_AUTO, value = "none") + } +) +@DomainModel( + annotatedClasses = { + Flight.class, + Company.class, + Sky.class + } +) +@SessionFactory +public class EntityTest { private DateFormat df = SimpleDateFormat.getDateTimeInstance( DateFormat.LONG, DateFormat.LONG ); - @Override - protected void configureMetadataBuilder(MetadataBuilder metadataBuilder) { - super.configureMetadataBuilder( metadataBuilder ); - metadataBuilder.applyImplicitNamingStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE ); - } - @Test - public void testLoad() throws Exception { + public void testLoad(DomainModelScope domainModelScope, SessionFactoryScope sessionFactoryScope) throws Exception { //put an object in DB - assertEquals( "Flight", metadata().getEntityBinding( Flight.class.getName() ).getTable().getName() ); + assertEquals( "Flight", domainModelScope.getDomainModel().getEntityBinding( Flight.class.getName() ).getTable().getName() ); - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Flight firstOne = new Flight(); - firstOne.setId( Long.valueOf( 1 ) ); - firstOne.setName( "AF3202" ); - firstOne.setDuration( new Long( 1000000 ) ); - firstOne.setDurationInSec( 2000 ); - s.save( firstOne ); - s.flush(); - tx.commit(); - s.close(); + sessionFactoryScope.inTransaction( + session -> { + Flight firstOne = new Flight(); + firstOne.setId( Long.valueOf( 1 ) ); + firstOne.setName( "AF3202" ); + firstOne.setDuration( new Long( 1000000 ) ); + firstOne.setDurationInSec( 2000 ); + session.save( firstOne ); + session.flush(); + } + ); //read it - s = openSession(); - tx = s.beginTransaction(); - firstOne = (Flight) s.get( Flight.class, Long.valueOf( 1 ) ); - assertNotNull( firstOne ); - assertEquals( Long.valueOf( 1 ), firstOne.getId() ); - assertEquals( "AF3202", firstOne.getName() ); - assertEquals( Long.valueOf( 1000000 ), firstOne.getDuration() ); - assertFalse( "Transient is not working", 2000l == firstOne.getDurationInSec() ); - tx.commit(); - s.close(); + sessionFactoryScope.inTransaction( + session -> { + Flight firstOne = session.get( Flight.class, Long.valueOf( 1 ) ); + assertNotNull( firstOne ); + assertEquals( Long.valueOf( 1 ), firstOne.getId() ); + assertEquals( "AF3202", firstOne.getName() ); + assertEquals( Long.valueOf( 1000000 ), firstOne.getDuration() ); + assertFalse( 2000l == firstOne.getDurationInSec(), "Transient is not working" ); + } + ); } @Test - public void testColumn() throws Exception { + public void testColumn(SessionFactoryScope scope) { //put an object in DB - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Flight firstOne = new Flight(); - firstOne.setId( Long.valueOf( 1 ) ); - firstOne.setName( "AF3202" ); - firstOne.setDuration( Long.valueOf( 1000000 ) ); - firstOne.setDurationInSec( 2000 ); - s.save( firstOne ); - s.flush(); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + Flight firstOne = new Flight(); + firstOne.setId( Long.valueOf( 1 ) ); + firstOne.setName( "AF3202" ); + firstOne.setDuration( Long.valueOf( 1000000 ) ); + firstOne.setDurationInSec( 2000 ); + session.save( firstOne ); + session.flush(); + } + ); + scope.inSession( + session -> { + Transaction tx = session.beginTransaction(); + Flight firstOne = new Flight(); + firstOne.setId( Long.valueOf( 1 ) ); + firstOne.setName( null ); - s = openSession(); - tx = s.beginTransaction(); - firstOne = new Flight(); - firstOne.setId( Long.valueOf( 1 ) ); - firstOne.setName( null ); - - try { - s.save( firstOne ); - tx.commit(); - fail( "Name column should be not null" ); - } - catch (HibernateException e) { - //fine - } - finally { - s.close(); - } + try { + session.save( firstOne ); + tx.commit(); + fail( "Name column should be not null" ); + } + catch (HibernateException e) { + //fine + } + } + ); //insert an object and check that name is not updatable - s = openSession(); - tx = s.beginTransaction(); - firstOne = new Flight(); - firstOne.setId( Long.valueOf( 1 ) ); - firstOne.setName( "AF3202" ); - firstOne.setTriggeredData( "should not be insertable" ); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + Flight firstOne = new Flight(); + firstOne.setId( Long.valueOf( 1 ) ); + firstOne.setName( "AF3202" ); + firstOne.setTriggeredData( "should not be insertable" ); + } + ); - s = openSession(); - tx = s.beginTransaction(); - firstOne = (Flight) s.get( Flight.class, Long.valueOf( 1 ) ); - assertNotNull( firstOne ); - assertEquals( Long.valueOf( 1 ), firstOne.getId() ); - assertEquals( "AF3202", firstOne.getName() ); - assertFalse( "should not be insertable".equals( firstOne.getTriggeredData() ) ); - firstOne.setName( "BA1234" ); - firstOne.setTriggeredData( "should not be updatable" ); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + Flight firstOne = session.get( Flight.class, Long.valueOf( 1 ) ); + assertNotNull( firstOne ); + assertEquals( Long.valueOf( 1 ), firstOne.getId() ); + assertEquals( "AF3202", firstOne.getName() ); + assertFalse( "should not be insertable".equals( firstOne.getTriggeredData() ) ); + firstOne.setName( "BA1234" ); + firstOne.setTriggeredData( "should not be updatable" ); + } + ); - s = openSession(); - tx = s.beginTransaction(); - firstOne = (Flight) s.get( Flight.class, Long.valueOf( 1 ) ); - assertNotNull( firstOne ); - assertEquals( Long.valueOf( 1 ), firstOne.getId() ); - assertEquals( "AF3202", firstOne.getName() ); - assertFalse( "should not be updatable".equals( firstOne.getTriggeredData() ) ); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + Flight firstOne = session.get( Flight.class, Long.valueOf( 1 ) ); + assertNotNull( firstOne ); + assertEquals( Long.valueOf( 1 ), firstOne.getId() ); + assertEquals( "AF3202", firstOne.getName() ); + assertFalse( "should not be updatable".equals( firstOne.getTriggeredData() ) ); + } + ); } @Test - public void testColumnUnique() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - Sky sky = new Sky(); - sky.id = Long.valueOf( 2 ); - sky.color = "blue"; - sky.day = "monday"; - sky.month = "January"; + public void testColumnUnique(SessionFactoryScope scope) { + scope.inSession( + session -> { + Transaction tx = session.beginTransaction(); + Sky sky = new Sky(); + sky.id = Long.valueOf( 2 ); + sky.color = "blue"; + sky.day = "monday"; + sky.month = "January"; - Sky sameSky = new Sky(); - sameSky.id = Long.valueOf( 3 ); - sameSky.color = "blue"; - sky.day = "tuesday"; - sky.month = "January"; + Sky sameSky = new Sky(); + sameSky.id = Long.valueOf( 3 ); + sameSky.color = "blue"; + sky.day = "tuesday"; + sky.month = "January"; - try { - s.save( sky ); - s.flush(); - s.save( sameSky ); - tx.commit(); - fail( "unique constraints not respected" ); - } - catch (HibernateException e) { - //success - } - finally { - if ( tx != null ) { - tx.rollback(); - } - s.close(); - } + try { + session.save( sky ); + session.flush(); + session.save( sameSky ); + tx.commit(); + fail( "unique constraints not respected" ); + } + catch (HibernateException e) { + //success + } + finally { + if ( tx != null ) { + tx.rollback(); + } + } + } + ); } @Test - public void testUniqueConstraint() throws Exception { + public void testUniqueConstraint(SessionFactoryScope scope) { int id = 5; - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); Sky sky = new Sky(); sky.id = Long.valueOf( id++ ); sky.color = "green"; @@ -212,244 +218,234 @@ public class EntityTest extends BaseNonConfigCoreFunctionalTestCase { sameSky.day = "monday"; sameSky.month = "March"; - s.save( sky ); - s.flush(); + scope.inTransaction( + session -> { - s.save( otherSky ); - tx.commit(); - s.close(); + session.save( sky ); + session.flush(); - s = openSession(); - tx = s.beginTransaction(); - try { - s.save( sameSky ); - tx.commit(); - fail( "unique constraints not respected" ); - } - catch (PersistenceException e) { - //success - if ( tx != null ) { - tx.rollback(); - } - } - finally { - s.close(); - } + session.save( otherSky ); + } + ); + + scope.inSession( + session -> { + Transaction tx = session.beginTransaction(); + try { + session.save( sameSky ); + tx.commit(); + fail( "unique constraints not respected" ); + } + catch (PersistenceException e) { + //success + if ( tx != null ) { + tx.rollback(); + } + } + } + ); } @Test - public void testVersion() throws Exception { + public void testVersion(SessionFactoryScope scope) { // put an object in DB - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Flight firstOne = new Flight(); - firstOne.setId( Long.valueOf( 2 ) ); - firstOne.setName( "AF3202" ); - firstOne.setDuration( Long.valueOf( 500 ) ); - s.save( firstOne ); - s.flush(); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + Flight firstOne = new Flight(); + firstOne.setId( Long.valueOf( 2 ) ); + firstOne.setName( "AF3202" ); + firstOne.setDuration( Long.valueOf( 500 ) ); + session.save( firstOne ); + session.flush(); + } + ); //read it - s = openSession(); - tx = s.beginTransaction(); - firstOne = (Flight) s.get( Flight.class, Long.valueOf( 2 ) ); - tx.commit(); - s.close(); + Flight firstOne = scope.fromTransaction( + session -> session.get( Flight.class, Long.valueOf( 2 ) ) + ); //read it again - s = openSession(); - tx = s.beginTransaction(); - Flight concurrentOne = (Flight) s.get( Flight.class, Long.valueOf( 2 ) ); - concurrentOne.setDuration( Long.valueOf( 1000 ) ); - s.update( concurrentOne ); - tx.commit(); - s.close(); + Flight concurrentOne = scope.fromTransaction( + session -> { + Flight _concurrentOne = session.get( Flight.class, Long.valueOf( 2 ) ); + _concurrentOne.setDuration( Long.valueOf( 1000 ) ); + session.update( _concurrentOne ); + return _concurrentOne; + } + ); + assertFalse( firstOne == concurrentOne ); assertFalse( firstOne.getVersion().equals( concurrentOne.getVersion() ) ); //reattach the first one - s = openSession(); - tx = s.beginTransaction(); - firstOne.setName( "Second access" ); - s.update( firstOne ); - try { - tx.commit(); - fail( "Optimistic locking should work" ); - } - catch (PersistenceException expected) { - if ( expected.getCause() instanceof StaleStateException ) { - //expected - } - else { - fail( "StaleStateException expected but is " + expected.getCause() ); - } - } - finally { - if ( tx != null ) { - tx.rollback(); - } - s.close(); - } + scope.inSession( + session -> { + Transaction tx = session.beginTransaction(); + firstOne.setName( "Second access" ); + session.update( firstOne ); + try { + tx.commit(); + fail( "Optimistic locking should work" ); + } + catch (PersistenceException expected) { + if ( expected.getCause() instanceof StaleStateException ) { + //expected + } + else { + fail( "StaleStateException expected but is " + expected.getCause() ); + } + } + finally { + if ( tx != null ) { + tx.rollback(); + } + } + } + ); } @Test - public void testFieldAccess() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - Sky sky = new Sky(); + public void testFieldAccess(SessionFactoryScope scope) { + final Sky sky = new Sky(); sky.id = Long.valueOf( 1 ); sky.color = "black"; sky.area = "Paris"; sky.day = "23"; sky.month = "1"; - s.save( sky ); - tx.commit(); - s.close(); + + scope.inTransaction( + session -> session.save( sky ) + ); + sky.area = "London"; - s = openSession(); - tx = s.beginTransaction(); - sky = (Sky) s.get( Sky.class, sky.id ); - assertNotNull( sky ); - assertEquals( "black", sky.color ); - assertFalse( "Paris".equals( sky.area ) ); - tx.commit(); - s.close(); + scope.inTransaction( + session -> { + Sky _sky = session.get( Sky.class, sky.id ); + assertNotNull( _sky ); + assertEquals( "black", _sky.color ); + assertFalse( "Paris".equals( _sky.area ) ); + } + ); } @Test - public void testEntityName() throws Exception { - assertEquals( "Corporation", metadata().getEntityBinding( Company.class.getName() ).getTable().getName() ); - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Company comp = new Company(); - s.persist( comp ); - comp.setName( "JBoss Inc" ); - tx.commit(); - s.close(); + public void testEntityName(DomainModelScope domainModelScope, SessionFactoryScope sessionFactoryScope) { + assertEquals( "Corporation", domainModelScope.getDomainModel().getEntityBinding( Company.class.getName() ).getTable().getName() ); - s = openSession(); - tx = s.beginTransaction(); - List result = s.createQuery( "from Corporation" ).list(); - assertNotNull( result ); - assertEquals( 1, result.size() ); - tx.commit(); - s.close(); + sessionFactoryScope.inTransaction( + session -> { + Company comp = new Company(); + session.persist( comp ); + comp.setName( "JBoss Inc" ); + } + ); + + sessionFactoryScope.inTransaction( + session -> { + List result = session.createQuery( "from Corporation" ).list(); + assertNotNull( result ); + assertEquals( 1, result.size() ); + } + ); } @Test - public void testNonGetter() throws Exception { - Session s = openSession(); - Transaction tx = s.beginTransaction(); + public void testNonGetter(SessionFactoryScope scope) { Flight airFrance = new Flight(); airFrance.setId( Long.valueOf( 747 ) ); airFrance.setName( "Paris-Amsterdam" ); airFrance.setDuration( Long.valueOf( 10 ) ); airFrance.setFactor( 25 ); - s.persist( airFrance ); - tx.commit(); - s.close(); - s = openSession(); - tx = s.beginTransaction(); - airFrance = (Flight) s.get( Flight.class, airFrance.getId() ); - assertNotNull( airFrance ); - assertEquals( Long.valueOf( 10 ), airFrance.getDuration() ); - assertFalse( 25 == airFrance.getFactor( false ) ); - s.delete( airFrance ); - tx.commit(); - s.close(); + scope.inTransaction( + session -> session.persist( airFrance ) + ); + + scope.inTransaction( + session -> { + Flight _airFrance = session.get( Flight.class, airFrance.getId() ); + assertNotNull( _airFrance ); + assertEquals( Long.valueOf( 10 ), _airFrance.getDuration() ); + assertFalse( 25 == _airFrance.getFactor( false ) ); + session.delete( _airFrance ); + } + ); } @Test - @SkipForDialect(value = Oracle10gDialect.class, comment = "oracle12c returns time in getDate. For now, skip.") - public void testTemporalType() throws Exception { - final ZoneId zoneId = ( sessionFactory().getJdbcServices().getDialect() instanceof MySQLDialect ) ? ZoneId.of( "UTC") + @SkipForDialect(dialectClass = OracleDialect.class, version = 1000, reason = "oracle12c returns time in getDate. For now, skip.") + public void testTemporalType(SessionFactoryScope scope) { + final ZoneId zoneId = ( scope.getSessionFactory().getJdbcServices().getDialect() instanceof MySQLDialect ) ? ZoneId.of( "UTC") : ZoneId.systemDefault(); - Flight airFrance = doInHibernate( this::sessionFactory, session -> { - Flight _airFrance = new Flight(); - _airFrance.setId( Long.valueOf( 747 ) ); - _airFrance.setName( "Paris-Amsterdam" ); - _airFrance.setDuration( Long.valueOf( 10 ) ); - _airFrance.setDepartureDate( Date.from(LocalDate.of( 2005, 06, 21 ).atStartOfDay(zoneId).toInstant()) ); - _airFrance.setAlternativeDepartureDate( new GregorianCalendar( 2006, 02, 03, 10, 00 ) ); - _airFrance.getAlternativeDepartureDate().setTimeZone( TimeZone.getTimeZone( "GMT" ) ); - _airFrance.setBuyDate( new java.sql.Timestamp( 122367443 ) ); - _airFrance.setFactor( 25 ); - session.persist( _airFrance ); - - return _airFrance; - } ); - - doInHibernate( this::sessionFactory, session -> { - Query q = session.createQuery( "from Flight f where f.departureDate = :departureDate" ); - q.setParameter( "departureDate", airFrance.getDepartureDate(), StandardBasicTypes.DATE ); - Flight copyAirFrance = (Flight) q.uniqueResult(); - assertNotNull( copyAirFrance ); - assertEquals( - Date.from(LocalDate.of( 2005, 06, 21 ).atStartOfDay(zoneId).toInstant()), - copyAirFrance.getDepartureDate() - ); - assertEquals( df.format( airFrance.getBuyDate() ), df.format( copyAirFrance.getBuyDate() ) ); - - session.delete( copyAirFrance ); - } ); - } - - @Test - public void testBasic() throws Exception { - Session s = openSession(); - Transaction tx = s.beginTransaction(); Flight airFrance = new Flight(); airFrance.setId( Long.valueOf( 747 ) ); airFrance.setName( "Paris-Amsterdam" ); - airFrance.setDuration( null ); - try { - s.persist( airFrance ); - tx.commit(); - fail( "Basic(optional=false) fails" ); - } - catch (Exception e) { - //success - if ( tx != null ) { - tx.rollback(); - } - } - finally { - s.close(); - } + airFrance.setDuration( Long.valueOf( 10 ) ); + airFrance.setDepartureDate( Date.from(LocalDate.of( 2005, 06, 21 ).atStartOfDay(zoneId).toInstant()) ); + airFrance.setAlternativeDepartureDate( new GregorianCalendar( 2006, 02, 03, 10, 00 ) ); + airFrance.getAlternativeDepartureDate().setTimeZone( TimeZone.getTimeZone( "GMT" ) ); + airFrance.setBuyDate( new java.sql.Timestamp( 122367443 ) ); + airFrance.setFactor( 25 ); + + scope.inTransaction( + session -> session.persist( airFrance ) + ); + + scope.inTransaction( + session -> { + Query q = session.createQuery( "from Flight f where f.departureDate = :departureDate" ); + q.setParameter( "departureDate", airFrance.getDepartureDate(), StandardBasicTypes.DATE ); + Flight copyAirFrance = (Flight) q.uniqueResult(); + assertNotNull( copyAirFrance ); + assertEquals( + Date.from(LocalDate.of( 2005, 06, 21 ).atStartOfDay(zoneId).toInstant()), + copyAirFrance.getDepartureDate() + ); + assertEquals( df.format( airFrance.getBuyDate() ), df.format( copyAirFrance.getBuyDate() ) ); + + session.delete( copyAirFrance ); + } + ); } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Flight.class, - Company.class, - Sky.class - }; + @Test + public void testBasic(SessionFactoryScope scope) throws Exception { + scope.inSession( + session -> { + Transaction tx = session.beginTransaction(); + Flight airFrance = new Flight(); + airFrance.setId( Long.valueOf( 747 ) ); + airFrance.setName( "Paris-Amsterdam" ); + airFrance.setDuration( null ); + try { + session.persist( airFrance ); + tx.commit(); + fail( "Basic(optional=false) fails" ); + } + catch (Exception e) { + //success + if ( tx != null ) { + tx.rollback(); + } + } + } + ); } - // tests are leaving data around, so drop/recreate schema for now. this is wha the old tests did + // tests are leaving data around, so drop/recreate schema for now. this is what the old tests did - @Override - protected boolean createSchema() { - return false; + @BeforeEach + public void runCreateSchema(DomainModelScope domainModelScope) { + new SchemaExport().create( EnumSet.of( TargetType.DATABASE ), domainModelScope.getDomainModel() ); } - @Before - public void runCreateSchema() { - new SchemaExport().create( EnumSet.of( TargetType.DATABASE ), metadata() ); - } - - @After - public void runDropSchema() { - new SchemaExport().drop( EnumSet.of( TargetType.DATABASE ), metadata() ); + @AfterEach + public void runDropSchema(DomainModelScope domainModelScope) { + new SchemaExport().drop( EnumSet.of( TargetType.DATABASE ), domainModelScope.getDomainModel() ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/IndexedCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/IndexedCollectionTest.java index a824cc9ca4..b0df0a30ec 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/IndexedCollectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/IndexedCollectionTest.java @@ -22,699 +22,25 @@ import org.hibernate.dialect.HSQLDialect; import org.hibernate.mapping.Collection; import org.hibernate.mapping.Column; -import org.hibernate.testing.RequiresDialect; import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.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; /** * Test index collections * * @author Emmanuel Bernard */ -public class IndexedCollectionTest extends BaseNonConfigCoreFunctionalTestCase { - @Test - public void testJPA2DefaultMapColumns() throws Exception { - isDefaultKeyColumnPresent( Atmosphere.class.getName(), "gasesDef", "_KEY" ); - isDefaultKeyColumnPresent( Atmosphere.class.getName(), "gasesPerKeyDef", "_KEY" ); - isDefaultKeyColumnPresent( Atmosphere.class.getName(), "gasesDefLeg", "_KEY" ); - } - - @Test - public void testJPA2DefaultIndexColumns() throws Exception { - isDefaultKeyColumnPresent( Drawer.class.getName(), "dresses", "_ORDER" ); - } - - private void isDefaultKeyColumnPresent(String collectionOwner, String propertyName, String suffix) { - assertTrue( "Could not find " + propertyName + suffix, - isDefaultColumnPresent(collectionOwner, propertyName, suffix) ); - } - - private boolean isDefaultColumnPresent(String collectionOwner, String propertyName, String suffix) { - final Collection collection = metadata().getCollectionBinding( collectionOwner + "." + propertyName ); - final Iterator columnIterator = collection.getCollectionTable().getColumnIterator(); - boolean hasDefault = false; - while ( columnIterator.hasNext() ) { - Column column = (Column) columnIterator.next(); - if ( (propertyName + suffix).equals( column.getName() ) ) hasDefault = true; - } - return hasDefault; - } - - private void isNotDefaultKeyColumnPresent(String collectionOwner, String propertyName, String suffix) { - assertFalse( "Could not find " + propertyName + suffix, - isDefaultColumnPresent(collectionOwner, propertyName, suffix) ); - } - - @Test - public void testFkList() throws Exception { - Wardrobe w = new Wardrobe(); - Drawer d1 = new Drawer(); - Drawer d2 = new Drawer(); - w.setDrawers( new ArrayList() ); - w.getDrawers().add( d1 ); - w.getDrawers().add( d2 ); - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - s.persist( w ); - - s.flush(); - s.clear(); - - w = (Wardrobe) s.get( Wardrobe.class, w.getId() ); - assertNotNull( w ); - assertNotNull( w.getDrawers() ); - List result = w.getDrawers(); - assertEquals( 2, result.size() ); - assertEquals( d2.getId(), result.get( 1 ).getId() ); - result.remove( d1 ); - s.flush(); - d1 = (Drawer) s.merge( d1 ); - result.add( d1 ); - - s.flush(); - s.clear(); - - w = (Wardrobe) s.get( Wardrobe.class, w.getId() ); - assertNotNull( w ); - assertNotNull( w.getDrawers() ); - result = w.getDrawers(); - assertEquals( 2, result.size() ); - assertEquals( d1.getId(), result.get( 1 ).getId() ); - s.delete( result.get( 0 ) ); - s.delete( result.get( 1 ) ); - s.delete( w ); - s.flush(); - tx.rollback(); - s.close(); - } - - @Test - public void testJoinedTableList() throws Exception { - Wardrobe w = new Wardrobe(); - w.setDrawers( new ArrayList() ); - Drawer d = new Drawer(); - w.getDrawers().add( d ); - Dress d1 = new Dress(); - Dress d2 = new Dress(); - d.setDresses( new ArrayList() ); - d.getDresses().add( d1 ); - d.getDresses().add( d2 ); - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - s.persist( d1 ); - s.persist( d2 ); - s.persist( w ); - - s.flush(); - s.clear(); - - d = (Drawer) s.get( Drawer.class, d.getId() ); - assertNotNull( d ); - assertNotNull( d.getDresses() ); - List result = d.getDresses(); - assertEquals( 2, result.size() ); - assertEquals( d2.getId(), result.get( 1 ).getId() ); - result.remove( d1 ); - s.flush(); - d1 = (Dress) s.merge( d1 ); - result.add( d1 ); - - s.flush(); - s.clear(); - - d = (Drawer) s.get( Drawer.class, d.getId() ); - assertNotNull( d ); - assertNotNull( d.getDresses() ); - result = d.getDresses(); - assertEquals( 2, result.size() ); - assertEquals( d1.getId(), result.get( 1 ).getId() ); - s.delete( result.get( 0 ) ); - s.delete( result.get( 1 ) ); - s.delete( d ); - s.flush(); - tx.rollback(); - s.close(); - } - - @Test - public void testMapKey() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - Software hibernate = new Software(); - hibernate.setName( "Hibernate" ); - Version v1 = new Version(); - v1.setCodeName( "HumbaHumba" ); - v1.setNumber( "1.0" ); - v1.setSoftware( hibernate ); - Version v2 = new Version(); - v2.setCodeName( "Copacabana" ); - v2.setNumber( "2.0" ); - v2.setSoftware( hibernate ); - Version v4 = new Version(); - v4.setCodeName( "Dreamland" ); - v4.setNumber( "4.0" ); - v4.setSoftware( hibernate ); - Map link = new HashMap(); - link.put( v1.getCodeName(), v1 ); - link.put( v2.getCodeName(), v2 ); - link.put( v4.getCodeName(), v4 ); - hibernate.setVersions( link ); - s.persist( hibernate ); - s.persist( v1 ); - s.persist( v2 ); - s.persist( v4 ); - - s.flush(); - s.clear(); - - hibernate = (Software) s.get( Software.class, "Hibernate" ); - assertEquals( 3, hibernate.getVersions().size() ); - assertEquals( "1.0", hibernate.getVersions().get( "HumbaHumba" ).getNumber() ); - assertEquals( "2.0", hibernate.getVersions().get( "Copacabana" ).getNumber() ); - hibernate.getVersions().remove( v4.getCodeName() ); - - s.flush(); - s.clear(); - - hibernate = (Software) s.get( Software.class, "Hibernate" ); - assertEquals( "So effect on collection changes", 3, hibernate.getVersions().size() ); - for ( Version v : hibernate.getVersions().values() ) { - s.delete( v ); - } - s.delete( hibernate ); - - s.flush(); - - tx.rollback(); - s.close(); - } - - @Test - public void testDefaultMapKey() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - AddressBook book = new AddressBook(); - book.setOwner( "Emmanuel" ); - AddressEntryPk helene = new AddressEntryPk( "Helene", "Michau" ); - AddressEntry heleneEntry = new AddressEntry(); - heleneEntry.setBook( book ); - heleneEntry.setCity( "Levallois" ); - heleneEntry.setStreet( "Louis Blanc" ); - heleneEntry.setPerson( helene ); - AddressEntryPk primeMinister = new AddressEntryPk( "Dominique", "Villepin" ); - AddressEntry primeMinisterEntry = new AddressEntry(); - primeMinisterEntry.setBook( book ); - primeMinisterEntry.setCity( "Paris" ); - primeMinisterEntry.setStreet( "Hotel Matignon" ); - primeMinisterEntry.setPerson( primeMinister ); - book.getEntries().put( helene, heleneEntry ); - book.getEntries().put( primeMinister, primeMinisterEntry ); - s.persist( book ); - - s.flush(); - s.clear(); - - book = (AddressBook) s.get( AddressBook.class, book.getId() ); - assertEquals( 2, book.getEntries().size() ); - assertEquals( heleneEntry.getCity(), book.getEntries().get( helene ).getCity() ); - AddressEntryPk fake = new AddressEntryPk( "Fake", "Fake" ); - book.getEntries().put( fake, primeMinisterEntry ); - - s.flush(); - s.clear(); - - book = (AddressBook) s.get( AddressBook.class, book.getId() ); - assertEquals( 2, book.getEntries().size() ); - assertNull( book.getEntries().get( fake ) ); - s.delete( book ); - - s.flush(); - tx.rollback(); - s.close(); - } - - @Test - public void testMapKeyToEntity() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - AlphabeticalDirectory m = new AlphabeticalDirectory(); - m.setName( "M" ); - AlphabeticalDirectory v = new AlphabeticalDirectory(); - v.setName( "V" ); - s.persist( m ); - s.persist( v ); - - AddressBook book = new AddressBook(); - book.setOwner( "Emmanuel" ); - AddressEntryPk helene = new AddressEntryPk( "Helene", "Michau" ); - AddressEntry heleneEntry = new AddressEntry(); - heleneEntry.setBook( book ); - heleneEntry.setCity( "Levallois" ); - heleneEntry.setStreet( "Louis Blanc" ); - heleneEntry.setPerson( helene ); - heleneEntry.setDirectory( m ); - AddressEntryPk primeMinister = new AddressEntryPk( "Dominique", "Villepin" ); - AddressEntry primeMinisterEntry = new AddressEntry(); - primeMinisterEntry.setBook( book ); - primeMinisterEntry.setCity( "Paris" ); - primeMinisterEntry.setStreet( "Hotel Matignon" ); - primeMinisterEntry.setPerson( primeMinister ); - primeMinisterEntry.setDirectory( v ); - book.getEntries().put( helene, heleneEntry ); - book.getEntries().put( primeMinister, primeMinisterEntry ); - s.persist( book ); - - s.flush(); - s.clear(); - - book = (AddressBook) s.get( AddressBook.class, book.getId() ); - assertEquals( 2, book.getEntries().size() ); - assertEquals( heleneEntry.getCity(), book.getEntries().get( helene ).getCity() ); - assertEquals( "M", book.getEntries().get( helene ).getDirectory().getName() ); - - s.delete( book ); - tx.rollback(); - s.close(); - } - - @Test - @RequiresDialect({HSQLDialect.class, H2Dialect.class}) - public void testComponentSubPropertyMapKey() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - AddressBook book = new AddressBook(); - book.setOwner( "Emmanuel" ); - AddressEntryPk helene = new AddressEntryPk( "Helene", "Michau" ); - AddressEntry heleneEntry = new AddressEntry(); - heleneEntry.setBook( book ); - heleneEntry.setCity( "Levallois" ); - heleneEntry.setStreet( "Louis Blanc" ); - heleneEntry.setPerson( helene ); - AddressEntryPk primeMinister = new AddressEntryPk( "Dominique", "Villepin" ); - AddressEntry primeMinisterEntry = new AddressEntry(); - primeMinisterEntry.setBook( book ); - primeMinisterEntry.setCity( "Paris" ); - primeMinisterEntry.setStreet( "Hotel Matignon" ); - primeMinisterEntry.setPerson( primeMinister ); - book.getEntries().put( helene, heleneEntry ); - book.getEntries().put( primeMinister, primeMinisterEntry ); - s.persist( book ); - - s.flush(); - s.clear(); - - book = (AddressBook) s.get( AddressBook.class, book.getId() ); - assertEquals( 2, book.getLastNameEntries().size() ); - assertEquals( heleneEntry.getCity(), book.getLastNameEntries().get( "Michau" ).getCity() ); - AddressEntryPk fake = new AddressEntryPk( "Fake", "Fake" ); - book.getEntries().put( fake, primeMinisterEntry ); - - s.flush(); - s.clear(); - - book = (AddressBook) s.get( AddressBook.class, book.getId() ); - assertEquals( 2, book.getEntries().size() ); - assertNull( book.getEntries().get( fake ) ); - s.delete( book ); - tx.rollback(); - s.close(); - } - - @Test - public void testMapKeyOnManyToMany() throws Exception { - Session s; - s = openSession(); - s.getTransaction().begin(); - News airplane = new News(); - airplane.setTitle( "Crash!" ); - airplane.setDetail( "An airplaned crashed." ); - s.persist( airplane ); - Newspaper lemonde = new Newspaper(); - lemonde.setName( "Lemonde" ); - lemonde.getNews().put( airplane.getTitle(), airplane ); - s.persist( lemonde ); - - s.flush(); - s.clear(); - - lemonde = (Newspaper) s.get( Newspaper.class, lemonde.getId() ); - assertEquals( 1, lemonde.getNews().size() ); - News news = lemonde.getNews().get( airplane.getTitle() ); - assertNotNull( news ); - assertEquals( airplane.getTitle(), news.getTitle() ); - s.delete( lemonde ); - s.delete( news ); - - s.getTransaction().rollback(); - s.close(); - } - - @Test - public void testMapKeyOnManyToManyOnId() throws Exception { - Session s; - s = openSession(); - s.getTransaction().begin(); - News hibernate1 = new News(); - hibernate1.setTitle( "#1 ORM solution in the Java world" ); - hibernate1.setDetail( "Well, that's no news ;-)" ); - s.persist( hibernate1 ); - PressReleaseAgency schwartz = new PressReleaseAgency(); - schwartz.setName( "Schwartz" ); - schwartz.getProvidedNews().put( hibernate1.getId(), hibernate1 ); - s.persist( schwartz ); - - s.flush(); - s.clear(); - - schwartz = (PressReleaseAgency) s.get( PressReleaseAgency.class, schwartz.getId() ); - assertEquals( 1, schwartz.getProvidedNews().size() ); - News news = schwartz.getProvidedNews().get( hibernate1.getId() ); - assertNotNull( news ); - assertEquals( hibernate1.getTitle(), news.getTitle() ); - s.delete( schwartz ); - s.delete( news ); - - s.getTransaction().rollback(); - s.close(); - } - - @Test - public void testMapKeyAndIdClass() throws Exception { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Painter picasso = new Painter(); - Painting laVie = new Painting( "La Vie", "Picasso", 50, 20 ); - picasso.getPaintings().put( "La Vie", laVie ); - Painting famille = new Painting( "La Famille du Saltimbanque", "Picasso", 50, 20 ); - picasso.getPaintings().put( "La Famille du Saltimbanque", famille ); - s.persist( picasso ); - - s.flush(); - s.clear(); - - picasso = (Painter) s.get( Painter.class, picasso.getId() ); - Painting painting = picasso.getPaintings().get( famille.getName() ); - assertNotNull( painting ); - assertEquals( painting.getName(), famille.getName() ); - s.delete( picasso ); - tx.rollback(); - s.close(); - } - - @Test - public void testRealMap() throws Exception { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Atmosphere atm = new Atmosphere(); - Atmosphere atm2 = new Atmosphere(); - GasKey key = new GasKey(); - key.setName( "O2" ); - Gas o2 = new Gas(); - o2.name = "oxygen"; - atm.gases.put( "100%", o2 ); - atm.gasesPerKey.put( key, o2 ); - atm2.gases.put( "100%", o2 ); - atm2.gasesPerKey.put( key, o2 ); - s.persist( key ); - s.persist( atm ); - s.persist( atm2 ); - - s.flush(); - s.clear(); - - atm = (Atmosphere) s.get( Atmosphere.class, atm.id ); - key = (GasKey) s.get( GasKey.class, key.getName() ); - assertEquals( 1, atm.gases.size() ); - assertEquals( o2.name, atm.gases.get( "100%" ).name ); - assertEquals( o2.name, atm.gasesPerKey.get( key ).name ); - tx.rollback(); - s.close(); - } - - @Test - public void testTemporalKeyMap() throws Exception { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Atmosphere atm = new Atmosphere(); - atm.colorPerDate.put( new Date(1234567000), "red" ); - s.persist( atm ); - - s.flush(); - s.clear(); - - atm = (Atmosphere) s.get( Atmosphere.class, atm.id ); - assertEquals( 1, atm.colorPerDate.size() ); - final Date date = atm.colorPerDate.keySet().iterator().next(); - final long diff = new Date( 1234567000 ).getTime() - date.getTime(); - assertTrue( "24h diff max", diff >= 0 && diff < 24*60*60*1000 ); - tx.rollback(); - s.close(); - } - - @Test - public void testEnumKeyType() throws Exception { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Atmosphere atm = new Atmosphere(); - atm.colorPerLevel.put( Atmosphere.Level.HIGH, "red" ); - s.persist( atm ); - - s.flush(); - s.clear(); - - atm = (Atmosphere) s.get( Atmosphere.class, atm.id ); - assertEquals( 1, atm.colorPerLevel.size() ); - assertEquals( "red", atm.colorPerLevel.get(Atmosphere.Level.HIGH) ); - tx.rollback(); - s.close(); - } - - @Test - public void testMapKeyEntityEntity() throws Exception { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - AddressBook book = new AddressBook(); - s.persist( book ); - AddressEntry entry = new AddressEntry(); - entry.setCity( "Atlanta"); - AddressEntryPk pk = new AddressEntryPk("Coca", "Cola" ); - entry.setPerson( pk ); - entry.setBook( book ); - AlphabeticalDirectory ad = new AlphabeticalDirectory(); - ad.setName( "C"); - s.persist( ad ); - entry.setDirectory( ad ); - s.persist( entry ); - book.getDirectoryEntries().put( ad, entry ); - - s.flush(); - s.clear(); - - book = (AddressBook) s.get( AddressBook.class, book.getId() ); - assertEquals( 1, book.getDirectoryEntries().size() ); - assertEquals( "C", book.getDirectoryEntries().keySet().iterator().next().getName() ); - tx.rollback(); - s.close(); - } - - @Test - @TestForIssue( jiraKey = "HHH-8879") - public void testMapKeyEmbeddableWithEntityKey() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - Currency currency1= new Currency(); - Currency currency2= new Currency(); - s.persist( currency1 ); - s.persist( currency2 ); - Integer id1 = currency1.getId(); - Integer id2 = currency2.getId(); - ExchangeRateKey cq = new ExchangeRateKey(20140101, currency1, currency2); - - ExchangeRate m = new ExchangeRate(); - m.setKey( cq ); - s.persist( m ); - ExchangeOffice wm = new ExchangeOffice(); - s.persist( wm ); - - wm.getExchangeRates().put( cq, m ); - m.setParent( wm ); - Integer id = wm.getId(); - s.flush(); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - wm = (ExchangeOffice) s.byId(ExchangeOffice.class).load(id); - assertNotNull(wm); - wm.getExchangeRates().size(); - currency1 = (Currency) s.byId(Currency.class).load(id1); - assertNotNull(currency1); - currency2 = (Currency) s.byId(Currency.class).load(id2); - assertNotNull(currency2); - cq = new ExchangeRateKey(20140101, currency1, currency2); - - m = wm.getExchangeRates().get( cq ); - assertNotNull(m); - tx.commit(); - s.close(); - - } - - @Test - @TestForIssue( jiraKey = "HHH-8994") - public void testEmbeddableWithEntityKey() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - Currency currency1= new Currency(); - Currency currency2= new Currency(); - s.persist( currency1 ); - s.persist( currency2 ); - Integer id1 = currency1.getId(); - Integer id2 = currency2.getId(); - ExchangeRateKey cq = new ExchangeRateKey(20140101, currency1, currency2); - - ExchangeOffice wm = new ExchangeOffice(); - s.persist( wm ); - - final BigDecimal fee = BigDecimal.valueOf( 12, 2 ); - - wm.getExchangeRateFees().put( cq, fee ); - Integer id = wm.getId(); - s.flush(); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - wm = (ExchangeOffice) s.byId(ExchangeOffice.class).load(id); - assertNotNull(wm); - wm.getExchangeRateFees().size(); - currency1 = (Currency) s.byId(Currency.class).load(id1); - assertNotNull(currency1); - currency2 = (Currency) s.byId(Currency.class).load(id2); - assertNotNull(currency2); - cq = new ExchangeRateKey(20140101, currency1, currency2); - - assertEquals( fee, wm.getExchangeRateFees().get( cq ) ); - - tx.commit(); - s.close(); - } - - @Test - public void testEntityKeyElementTarget() throws Exception { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Atmosphere atm = new Atmosphere(); - Gas o2 = new Gas(); - o2.name = "oxygen"; - atm.composition.put( o2, 94.3 ); - s.persist( o2 ); - s.persist( atm ); - - s.flush(); - s.clear(); - - atm = (Atmosphere) s.get( Atmosphere.class, atm.id ); - assertTrue( ! Hibernate.isInitialized( atm.composition ) ); - assertEquals( 1, atm.composition.size() ); - assertEquals( o2.name, atm.composition.keySet().iterator().next().name ); - tx.rollback(); - s.close(); - } - - @Test - public void testSortedMap() { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Training training = new Training(); - Trainee trainee = new Trainee(); - trainee.setName( "Jim" ); - Trainee trainee2 = new Trainee(); - trainee2.setName( "Emmanuel" ); - s.persist( trainee ); - s.persist( trainee2 ); - training.getTrainees().put( "Jim", trainee ); - training.getTrainees().put( "Emmanuel", trainee2 ); - s.persist( training ); - - s.flush(); - s.clear(); - - training = (Training) s.get( Training.class, training.getId() ); - assertEquals( "Emmanuel", training.getTrainees().firstKey() ); - assertEquals( "Jim", training.getTrainees().lastKey() ); - tx.rollback(); - s.close(); - } - - @Test - public void testMapKeyLoad() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - Software hibernate = new Software(); - hibernate.setName( "Hibernate" ); - Version v1 = new Version(); - v1.setCodeName( "HumbaHumba" ); - v1.setNumber( "1.0" ); - v1.setSoftware( hibernate ); - hibernate.addVersion( v1 ); - s.persist( hibernate ); - s.persist( v1 ); - - s.flush(); - s.clear(); - - hibernate = (Software) s.get( Software.class, "Hibernate" ); - assertEquals(1, hibernate.getVersions().size() ); - Version v2 = new Version(); - v2.setCodeName( "HumbaHumba2" ); - v2.setNumber( "2.0" ); - v2.setSoftware( hibernate ); - hibernate.addVersion( v2 ); - assertEquals( "One loaded persisted version, and one just added", 2, hibernate.getVersions().size() ); - - s.flush(); - s.clear(); - - hibernate = (Software) s.get( Software.class, "Hibernate" ); - for ( Version v : hibernate.getVersions().values() ) { - s.delete( v ); - } - s.delete( hibernate ); - tx.rollback(); - s.close(); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ +@DomainModel ( + annotatedClasses = { Wardrobe.class, Drawer.class, Dress.class, @@ -737,6 +63,810 @@ public class IndexedCollectionTest extends BaseNonConfigCoreFunctionalTestCase { Currency.class, ExchangeOffice.class, ExchangeRate.class, - }; + } +) +@SessionFactory +public class IndexedCollectionTest { + @Test + public void testJPA2DefaultMapColumns(SessionFactoryScope scope) { + isDefaultKeyColumnPresent( scope, Atmosphere.class.getName(), "gasesDef", "_KEY" ); + isDefaultKeyColumnPresent( scope, Atmosphere.class.getName(), "gasesPerKeyDef", "_KEY" ); + isDefaultKeyColumnPresent( scope, Atmosphere.class.getName(), "gasesDefLeg", "_KEY" ); + } + + @Test + public void testJPA2DefaultIndexColumns(SessionFactoryScope scope) { + isDefaultKeyColumnPresent( scope, Drawer.class.getName(), "dresses", "_ORDER" ); + } + + private void isDefaultKeyColumnPresent(SessionFactoryScope scope, String collectionOwner, String propertyName, String suffix) { + assertTrue( + isDefaultColumnPresent( scope, collectionOwner, propertyName, suffix ), + "Could not find " + propertyName + suffix + ); + } + + private boolean isDefaultColumnPresent(SessionFactoryScope scope, String collectionOwner, String propertyName, String suffix) { + final Collection collection = scope.getMetadataImplementor().getCollectionBinding( collectionOwner + "." + propertyName ); + final Iterator columnIterator = collection.getCollectionTable().getColumnIterator(); + boolean hasDefault = false; + while ( columnIterator.hasNext() ) { + Column column = (Column) columnIterator.next(); + if ( ( propertyName + suffix ).equals( column.getName() ) ) hasDefault = true; + } + return hasDefault; + } + + @Test + public void testFkList(SessionFactoryScope scope) { + scope.inSession( + s -> { + try { + Wardrobe w = new Wardrobe(); + Drawer d1 = new Drawer(); + Drawer d2 = new Drawer(); + w.setDrawers( new ArrayList<>() ); + w.getDrawers().add( d1 ); + w.getDrawers().add( d2 ); + Transaction tx; + tx = s.beginTransaction(); + s.persist( w ); + + s.flush(); + s.clear(); + + w = s.get( Wardrobe.class, w.getId() ); + assertNotNull( w ); + assertNotNull( w.getDrawers() ); + List result = w.getDrawers(); + assertEquals( 2, result.size() ); + assertEquals( d2.getId(), result.get( 1 ).getId() ); + result.remove( d1 ); + s.flush(); + d1 = (Drawer) s.merge( d1 ); + result.add( d1 ); + + s.flush(); + s.clear(); + + w = s.get( Wardrobe.class, w.getId() ); + assertNotNull( w ); + assertNotNull( w.getDrawers() ); + result = w.getDrawers(); + assertEquals( 2, result.size() ); + assertEquals( d1.getId(), result.get( 1 ).getId() ); + s.delete( result.get( 0 ) ); + s.delete( result.get( 1 ) ); + s.delete( w ); + s.flush(); + tx.rollback(); + } + catch (Exception e) { + if ( s.getTransaction().isActive() ) { + s.getTransaction().rollback(); + } + } + } + ); + } + + @Test + public void testJoinedTableList(SessionFactoryScope scope) { + scope.inSession( + s -> { + try { + Wardrobe w = new Wardrobe(); + w.setDrawers( new ArrayList<>() ); + Drawer d = new Drawer(); + w.getDrawers().add( d ); + Dress d1 = new Dress(); + Dress d2 = new Dress(); + d.setDresses( new ArrayList<>() ); + d.getDresses().add( d1 ); + d.getDresses().add( d2 ); + Transaction tx; + tx = s.beginTransaction(); + s.persist( d1 ); + s.persist( d2 ); + s.persist( w ); + + s.flush(); + s.clear(); + + d = s.get( Drawer.class, d.getId() ); + assertNotNull( d ); + assertNotNull( d.getDresses() ); + List result = d.getDresses(); + assertEquals( 2, result.size() ); + assertEquals( d2.getId(), result.get( 1 ).getId() ); + result.remove( d1 ); + s.flush(); + d1 = (Dress) s.merge( d1 ); + result.add( d1 ); + + s.flush(); + s.clear(); + + d = s.get( Drawer.class, d.getId() ); + assertNotNull( d ); + assertNotNull( d.getDresses() ); + result = d.getDresses(); + assertEquals( 2, result.size() ); + assertEquals( d1.getId(), result.get( 1 ).getId() ); + s.delete( result.get( 0 ) ); + s.delete( result.get( 1 ) ); + s.delete( d ); + s.flush(); + tx.rollback(); + } + catch (Exception e) { + if ( s.getTransaction().isActive() ) { + s.getTransaction().rollback(); + } + } + } + ); + } + + @Test + public void testMapKey(SessionFactoryScope scope) { + scope.inSession( + s -> { + try { + Transaction tx; + tx = s.beginTransaction(); + Software hibernate = new Software(); + hibernate.setName( "Hibernate" ); + Version v1 = new Version(); + v1.setCodeName( "HumbaHumba" ); + v1.setNumber( "1.0" ); + v1.setSoftware( hibernate ); + Version v2 = new Version(); + v2.setCodeName( "Copacabana" ); + v2.setNumber( "2.0" ); + v2.setSoftware( hibernate ); + Version v4 = new Version(); + v4.setCodeName( "Dreamland" ); + v4.setNumber( "4.0" ); + v4.setSoftware( hibernate ); + Map link = new HashMap<>(); + link.put( v1.getCodeName(), v1 ); + link.put( v2.getCodeName(), v2 ); + link.put( v4.getCodeName(), v4 ); + hibernate.setVersions( link ); + s.persist( hibernate ); + s.persist( v1 ); + s.persist( v2 ); + s.persist( v4 ); + + s.flush(); + s.clear(); + + hibernate = s.get( Software.class, "Hibernate" ); + assertEquals( 3, hibernate.getVersions().size() ); + assertEquals( "1.0", hibernate.getVersions().get( "HumbaHumba" ).getNumber() ); + assertEquals( "2.0", hibernate.getVersions().get( "Copacabana" ).getNumber() ); + hibernate.getVersions().remove( v4.getCodeName() ); + + s.flush(); + s.clear(); + + hibernate = s.get( Software.class, "Hibernate" ); + assertEquals( 3, hibernate.getVersions().size(), "So effect on collection changes" ); + for ( Version v : hibernate.getVersions().values() ) { + s.delete( v ); + } + s.delete( hibernate ); + + s.flush(); + + tx.rollback(); + } + catch (Exception e) { + if ( s.getTransaction().isActive() ) { + s.getTransaction().rollback(); + } + } + } + ); + } + + @Test + public void testDefaultMapKey(SessionFactoryScope scope) { + scope.inSession( + s -> { + try { + Transaction tx; + tx = s.beginTransaction(); + AddressBook book = new AddressBook(); + book.setOwner( "Emmanuel" ); + AddressEntryPk helene = new AddressEntryPk( "Helene", "Michau" ); + AddressEntry heleneEntry = new AddressEntry(); + heleneEntry.setBook( book ); + heleneEntry.setCity( "Levallois" ); + heleneEntry.setStreet( "Louis Blanc" ); + heleneEntry.setPerson( helene ); + AddressEntryPk primeMinister = new AddressEntryPk( "Dominique", "Villepin" ); + AddressEntry primeMinisterEntry = new AddressEntry(); + primeMinisterEntry.setBook( book ); + primeMinisterEntry.setCity( "Paris" ); + primeMinisterEntry.setStreet( "Hotel Matignon" ); + primeMinisterEntry.setPerson( primeMinister ); + book.getEntries().put( helene, heleneEntry ); + book.getEntries().put( primeMinister, primeMinisterEntry ); + s.persist( book ); + + s.flush(); + s.clear(); + + book = s.get( AddressBook.class, book.getId() ); + assertEquals( 2, book.getEntries().size() ); + assertEquals( heleneEntry.getCity(), book.getEntries().get( helene ).getCity() ); + AddressEntryPk fake = new AddressEntryPk( "Fake", "Fake" ); + book.getEntries().put( fake, primeMinisterEntry ); + + s.flush(); + s.clear(); + + book = s.get( AddressBook.class, book.getId() ); + assertEquals( 2, book.getEntries().size() ); + assertNull( book.getEntries().get( fake ) ); + s.delete( book ); + + s.flush(); + tx.rollback(); + } + catch (Exception e) { + if ( s.getTransaction().isActive() ) { + s.getTransaction().rollback(); + } + } + } + ); + } + + @Test + public void testMapKeyToEntity(SessionFactoryScope scope) { + scope.inSession( + s -> { + try { + Transaction tx; + tx = s.beginTransaction(); + AlphabeticalDirectory m = new AlphabeticalDirectory(); + m.setName( "M" ); + AlphabeticalDirectory v = new AlphabeticalDirectory(); + v.setName( "V" ); + s.persist( m ); + s.persist( v ); + + AddressBook book = new AddressBook(); + book.setOwner( "Emmanuel" ); + AddressEntryPk helene = new AddressEntryPk( "Helene", "Michau" ); + AddressEntry heleneEntry = new AddressEntry(); + heleneEntry.setBook( book ); + heleneEntry.setCity( "Levallois" ); + heleneEntry.setStreet( "Louis Blanc" ); + heleneEntry.setPerson( helene ); + heleneEntry.setDirectory( m ); + AddressEntryPk primeMinister = new AddressEntryPk( "Dominique", "Villepin" ); + AddressEntry primeMinisterEntry = new AddressEntry(); + primeMinisterEntry.setBook( book ); + primeMinisterEntry.setCity( "Paris" ); + primeMinisterEntry.setStreet( "Hotel Matignon" ); + primeMinisterEntry.setPerson( primeMinister ); + primeMinisterEntry.setDirectory( v ); + book.getEntries().put( helene, heleneEntry ); + book.getEntries().put( primeMinister, primeMinisterEntry ); + s.persist( book ); + + s.flush(); + s.clear(); + + book = s.get( AddressBook.class, book.getId() ); + assertEquals( 2, book.getEntries().size() ); + assertEquals( heleneEntry.getCity(), book.getEntries().get( helene ).getCity() ); + assertEquals( "M", book.getEntries().get( helene ).getDirectory().getName() ); + + s.delete( book ); + tx.rollback(); + } + catch (Exception e) { + if ( s.getTransaction().isActive() ) { + s.getTransaction().rollback(); + } + } + } + ); + } + + @Test + @RequiresDialect(value = HSQLDialect.class) + @RequiresDialect(value = H2Dialect.class) + public void testComponentSubPropertyMapKey(SessionFactoryScope scope) { + scope.inSession( + s -> { + try { + Transaction tx; + tx = s.beginTransaction(); + AddressBook book = new AddressBook(); + book.setOwner( "Emmanuel" ); + AddressEntryPk helene = new AddressEntryPk( "Helene", "Michau" ); + AddressEntry heleneEntry = new AddressEntry(); + heleneEntry.setBook( book ); + heleneEntry.setCity( "Levallois" ); + heleneEntry.setStreet( "Louis Blanc" ); + heleneEntry.setPerson( helene ); + AddressEntryPk primeMinister = new AddressEntryPk( "Dominique", "Villepin" ); + AddressEntry primeMinisterEntry = new AddressEntry(); + primeMinisterEntry.setBook( book ); + primeMinisterEntry.setCity( "Paris" ); + primeMinisterEntry.setStreet( "Hotel Matignon" ); + primeMinisterEntry.setPerson( primeMinister ); + book.getEntries().put( helene, heleneEntry ); + book.getEntries().put( primeMinister, primeMinisterEntry ); + s.persist( book ); + + s.flush(); + s.clear(); + + book = s.get( AddressBook.class, book.getId() ); + assertEquals( 2, book.getLastNameEntries().size() ); + assertEquals( heleneEntry.getCity(), book.getLastNameEntries().get( "Michau" ).getCity() ); + AddressEntryPk fake = new AddressEntryPk( "Fake", "Fake" ); + book.getEntries().put( fake, primeMinisterEntry ); + + s.flush(); + s.clear(); + + book = s.get( AddressBook.class, book.getId() ); + assertEquals( 2, book.getEntries().size() ); + assertNull( book.getEntries().get( fake ) ); + s.delete( book ); + tx.rollback(); + } + catch (Exception e) { + if ( s.getTransaction().isActive() ) { + s.getTransaction().rollback(); + } + } + } + ); + } + + @Test + public void testMapKeyOnManyToMany(SessionFactoryScope scope) { + scope.inSession( + s -> { + try { + s.getTransaction().begin(); + News airplane = new News(); + airplane.setTitle( "Crash!" ); + airplane.setDetail( "An airplaned crashed." ); + s.persist( airplane ); + Newspaper lemonde = new Newspaper(); + lemonde.setName( "Lemonde" ); + lemonde.getNews().put( airplane.getTitle(), airplane ); + s.persist( lemonde ); + + s.flush(); + s.clear(); + + lemonde = s.get( Newspaper.class, lemonde.getId() ); + assertEquals( 1, lemonde.getNews().size() ); + News news = lemonde.getNews().get( airplane.getTitle() ); + assertNotNull( news ); + assertEquals( airplane.getTitle(), news.getTitle() ); + s.delete( lemonde ); + s.delete( news ); + + s.getTransaction().rollback(); + } + catch (Exception e) { + if ( s.getTransaction().isActive() ) { + s.getTransaction().rollback(); + } + } + } + ); + } + + @Test + public void testMapKeyOnManyToManyOnId(SessionFactoryScope scope) { + scope.inSession( + s -> { + try { + s.getTransaction().begin(); + News hibernate1 = new News(); + hibernate1.setTitle( "#1 ORM solution in the Java world" ); + hibernate1.setDetail( "Well, that's no news ;-)" ); + s.persist( hibernate1 ); + PressReleaseAgency schwartz = new PressReleaseAgency(); + schwartz.setName( "Schwartz" ); + schwartz.getProvidedNews().put( hibernate1.getId(), hibernate1 ); + s.persist( schwartz ); + + s.flush(); + s.clear(); + + schwartz = s.get( PressReleaseAgency.class, schwartz.getId() ); + assertEquals( 1, schwartz.getProvidedNews().size() ); + News news = schwartz.getProvidedNews().get( hibernate1.getId() ); + assertNotNull( news ); + assertEquals( hibernate1.getTitle(), news.getTitle() ); + s.delete( schwartz ); + s.delete( news ); + + s.getTransaction().rollback(); + } + catch (Exception e) { + if ( s.getTransaction().isActive() ) { + s.getTransaction().rollback(); + } + } + } + ); + } + + @Test + public void testMapKeyAndIdClass(SessionFactoryScope scope) { + scope.inSession( + s -> { + try { + Transaction tx = s.beginTransaction(); + Painter picasso = new Painter(); + Painting laVie = new Painting( "La Vie", "Picasso", 50, 20 ); + picasso.getPaintings().put( "La Vie", laVie ); + Painting famille = new Painting( "La Famille du Saltimbanque", "Picasso", 50, 20 ); + picasso.getPaintings().put( "La Famille du Saltimbanque", famille ); + s.persist( picasso ); + + s.flush(); + s.clear(); + + picasso = s.get( Painter.class, picasso.getId() ); + Painting painting = picasso.getPaintings().get( famille.getName() ); + assertNotNull( painting ); + assertEquals( painting.getName(), famille.getName() ); + s.delete( picasso ); + tx.rollback(); + } + catch (Exception e) { + if ( s.getTransaction().isActive() ) { + s.getTransaction().rollback(); + } + } + } + ); + } + + @Test + public void testRealMap(SessionFactoryScope scope) { + scope.inSession( + s -> { + try { + Transaction tx = s.beginTransaction(); + Atmosphere atm = new Atmosphere(); + Atmosphere atm2 = new Atmosphere(); + GasKey key = new GasKey(); + key.setName( "O2" ); + Gas o2 = new Gas(); + o2.name = "oxygen"; + atm.gases.put( "100%", o2 ); + atm.gasesPerKey.put( key, o2 ); + atm2.gases.put( "100%", o2 ); + atm2.gasesPerKey.put( key, o2 ); + s.persist( key ); + s.persist( atm ); + s.persist( atm2 ); + + s.flush(); + s.clear(); + + atm = s.get( Atmosphere.class, atm.id ); + key = s.get( GasKey.class, key.getName() ); + assertEquals( 1, atm.gases.size() ); + assertEquals( o2.name, atm.gases.get( "100%" ).name ); + assertEquals( o2.name, atm.gasesPerKey.get( key ).name ); + tx.rollback(); + } + catch (Exception e) { + if ( s.getTransaction().isActive() ) { + s.getTransaction().rollback(); + } + } + } + ); + } + + @Test + public void testTemporalKeyMap(SessionFactoryScope scope) { + scope.inSession( + s -> { + try { + Transaction tx = s.beginTransaction(); + Atmosphere atm = new Atmosphere(); + atm.colorPerDate.put( new Date( 1234567000 ), "red" ); + s.persist( atm ); + + s.flush(); + s.clear(); + + atm = s.get( Atmosphere.class, atm.id ); + assertEquals( 1, atm.colorPerDate.size() ); + final Date date = atm.colorPerDate.keySet().iterator().next(); + final long diff = new Date( 1234567000 ).getTime() - date.getTime(); + assertTrue( diff >= 0 && diff < 24 * 60 * 60 * 1000, "24h diff max" ); + tx.rollback(); + } + catch (Exception e) { + if ( s.getTransaction().isActive() ) { + s.getTransaction().rollback(); + } + } + } + ); + } + + @Test + public void testEnumKeyType(SessionFactoryScope scope) { + scope.inSession( + s -> { + try { + Transaction tx = s.beginTransaction(); + Atmosphere atm = new Atmosphere(); + atm.colorPerLevel.put( Atmosphere.Level.HIGH, "red" ); + s.persist( atm ); + + s.flush(); + s.clear(); + + atm = s.get( Atmosphere.class, atm.id ); + assertEquals( 1, atm.colorPerLevel.size() ); + assertEquals( "red", atm.colorPerLevel.get( Atmosphere.Level.HIGH ) ); + tx.rollback(); + } + catch (Exception e) { + if ( s.getTransaction().isActive() ) { + s.getTransaction().rollback(); + } + } + } + ); + } + + @Test + public void testMapKeyEntityEntity(SessionFactoryScope scope) { + scope.inSession( + s -> { + try { + Transaction tx = s.beginTransaction(); + AddressBook book = new AddressBook(); + s.persist( book ); + AddressEntry entry = new AddressEntry(); + entry.setCity( "Atlanta" ); + AddressEntryPk pk = new AddressEntryPk( "Coca", "Cola" ); + entry.setPerson( pk ); + entry.setBook( book ); + AlphabeticalDirectory ad = new AlphabeticalDirectory(); + ad.setName( "C" ); + s.persist( ad ); + entry.setDirectory( ad ); + s.persist( entry ); + book.getDirectoryEntries().put( ad, entry ); + + s.flush(); + s.clear(); + + book = s.get( AddressBook.class, book.getId() ); + assertEquals( 1, book.getDirectoryEntries().size() ); + assertEquals( "C", book.getDirectoryEntries().keySet().iterator().next().getName() ); + tx.rollback(); + } + catch (Exception e) { + if ( s.getTransaction().isActive() ) { + s.getTransaction().rollback(); + } + } + } + ); + } + + @Test + @TestForIssue(jiraKey = "HHH-8879") + public void testMapKeyEmbeddableWithEntityKey(SessionFactoryScope scope) { + Session s = scope.getSessionFactory().openSession(); + Transaction tx; + tx = s.beginTransaction(); + Currency currency1 = new Currency(); + Currency currency2 = new Currency(); + s.persist( currency1 ); + s.persist( currency2 ); + Integer id1 = currency1.getId(); + Integer id2 = currency2.getId(); + ExchangeRateKey cq = new ExchangeRateKey( 20140101, currency1, currency2 ); + + ExchangeRate m = new ExchangeRate(); + m.setKey( cq ); + s.persist( m ); + ExchangeOffice wm = new ExchangeOffice(); + s.persist( wm ); + + wm.getExchangeRates().put( cq, m ); + m.setParent( wm ); + Integer id = wm.getId(); + s.flush(); + tx.commit(); + s.close(); + + s = scope.getSessionFactory().openSession(); + tx = s.beginTransaction(); + wm = s.byId( ExchangeOffice.class ).load( id ); + assertNotNull( wm ); + wm.getExchangeRates().size(); + currency1 = s.byId( Currency.class ).load( id1 ); + assertNotNull( currency1 ); + currency2 = s.byId( Currency.class ).load( id2 ); + assertNotNull( currency2 ); + cq = new ExchangeRateKey( 20140101, currency1, currency2 ); + + m = wm.getExchangeRates().get( cq ); + assertNotNull( m ); + tx.commit(); + s.close(); + } + + @Test + @TestForIssue(jiraKey = "HHH-8994") + public void testEmbeddableWithEntityKey(SessionFactoryScope scope) { + Session s = scope.getSessionFactory().openSession(); + Transaction tx; + tx = s.beginTransaction(); + Currency currency1 = new Currency(); + Currency currency2 = new Currency(); + s.persist( currency1 ); + s.persist( currency2 ); + Integer id1 = currency1.getId(); + Integer id2 = currency2.getId(); + ExchangeRateKey cq = new ExchangeRateKey( 20140101, currency1, currency2 ); + + ExchangeOffice wm = new ExchangeOffice(); + s.persist( wm ); + + final BigDecimal fee = BigDecimal.valueOf( 12, 2 ); + + wm.getExchangeRateFees().put( cq, fee ); + Integer id = wm.getId(); + s.flush(); + tx.commit(); + s.close(); + + s = scope.getSessionFactory().openSession(); + tx = s.beginTransaction(); + wm = s.byId( ExchangeOffice.class ).load( id ); + assertNotNull( wm ); + wm.getExchangeRateFees().size(); + currency1 = s.byId( Currency.class ).load( id1 ); + assertNotNull( currency1 ); + currency2 = s.byId( Currency.class ).load( id2 ); + assertNotNull( currency2 ); + cq = new ExchangeRateKey( 20140101, currency1, currency2 ); + + assertEquals( fee, wm.getExchangeRateFees().get( cq ) ); + + tx.commit(); + s.close(); + } + + @Test + public void testEntityKeyElementTarget(SessionFactoryScope scope) { + scope.inSession( + s -> { + try { + Transaction tx = s.beginTransaction(); + Atmosphere atm = new Atmosphere(); + Gas o2 = new Gas(); + o2.name = "oxygen"; + atm.composition.put( o2, 94.3 ); + s.persist( o2 ); + s.persist( atm ); + + s.flush(); + s.clear(); + + atm = s.get( Atmosphere.class, atm.id ); + assertTrue( !Hibernate.isInitialized( atm.composition ) ); + assertEquals( 1, atm.composition.size() ); + assertEquals( o2.name, atm.composition.keySet().iterator().next().name ); + tx.rollback(); + } + catch (Exception e) { + if ( s.getTransaction().isActive() ) { + s.getTransaction().rollback(); + } + } + } + ); + } + + @Test + public void testSortedMap(SessionFactoryScope scope) { + scope.inSession( + s -> { + try { + Transaction tx = s.beginTransaction(); + Training training = new Training(); + Trainee trainee = new Trainee(); + trainee.setName( "Jim" ); + Trainee trainee2 = new Trainee(); + trainee2.setName( "Emmanuel" ); + s.persist( trainee ); + s.persist( trainee2 ); + training.getTrainees().put( "Jim", trainee ); + training.getTrainees().put( "Emmanuel", trainee2 ); + s.persist( training ); + + s.flush(); + s.clear(); + + training = s.get( Training.class, training.getId() ); + assertEquals( "Emmanuel", training.getTrainees().firstKey() ); + assertEquals( "Jim", training.getTrainees().lastKey() ); + tx.rollback(); + } + catch (Exception e) { + if ( s.getTransaction().isActive() ) { + s.getTransaction().rollback(); + } + } + } + ); + } + + @Test + public void testMapKeyLoad(SessionFactoryScope scope) { + scope.inSession( + s -> { + try { + Transaction tx; + tx = s.beginTransaction(); + Software hibernate = new Software(); + hibernate.setName( "Hibernate" ); + Version v1 = new Version(); + v1.setCodeName( "HumbaHumba" ); + v1.setNumber( "1.0" ); + v1.setSoftware( hibernate ); + hibernate.addVersion( v1 ); + s.persist( hibernate ); + s.persist( v1 ); + + s.flush(); + s.clear(); + + hibernate = s.get( Software.class, "Hibernate" ); + assertEquals( 1, hibernate.getVersions().size() ); + Version v2 = new Version(); + v2.setCodeName( "HumbaHumba2" ); + v2.setNumber( "2.0" ); + v2.setSoftware( hibernate ); + hibernate.addVersion( v2 ); + assertEquals( 2, hibernate.getVersions().size(), "One loaded persisted version, and one just added" ); + + s.flush(); + s.clear(); + + hibernate = s.get( Software.class, "Hibernate" ); + for ( Version v : hibernate.getVersions().values() ) { + s.delete( v ); + } + s.delete( hibernate ); + tx.rollback(); + } + catch (Exception e) { + if ( s.getTransaction().isActive() ) { + s.getTransaction().rollback(); + } + } + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/component/basic/ComponentTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/component/basic/ComponentTest.java index 025cd64e8b..c8d36e38a7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/component/basic/ComponentTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/component/basic/ComponentTest.java @@ -7,8 +7,7 @@ package org.hibernate.orm.test.component.basic; import java.util.Date; -import java.util.List; -import java.util.Map; + import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Join; @@ -16,9 +15,9 @@ import jakarta.persistence.criteria.JoinType; import jakarta.persistence.criteria.Root; import org.hibernate.Hibernate; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.boot.Metadata; +import org.hibernate.boot.registry.StandardServiceRegistry; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.cfg.Environment; import org.hibernate.dialect.SybaseASE15Dialect; import org.hibernate.dialect.SybaseASEDialect; @@ -27,38 +26,33 @@ import org.hibernate.mapping.Formula; import org.hibernate.mapping.PersistentClass; import org.hibernate.query.TemporalUnit; -import org.hibernate.testing.FailureExpected; -import org.hibernate.testing.RequiresDialect; import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.FailureExpected; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.BaseSessionFactoryFunctionalTest; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; /** * @author Gavin King */ -public class ComponentTest extends BaseNonConfigCoreFunctionalTestCase { +public class ComponentTest extends BaseSessionFactoryFunctionalTest { @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; + public String[] getOrmXmlFiles() { + return new String[] { "org/hibernate/orm/test/component/basic/User.hbm.xml" }; } @Override - public String[] getMappings() { - return new String[] { "component/basic/User.hbm.xml" }; + protected void applySettings(StandardServiceRegistryBuilder builder) { + builder.applySetting( Environment.GENERATE_STATISTICS, "true" ); } @Override - protected void addSettings(Map settings) { - settings.put( Environment.GENERATE_STATISTICS, "true" ); - } - - @Override - protected void afterMetadataBuilt(Metadata metadata) { + public MetadataImplementor produceModel(StandardServiceRegistry serviceRegistry) { + MetadataImplementor metadata = super.produceModel( serviceRegistry ); // Oracle and Postgres do not have year() functions, so we need to // redefine the 'User.person.yob' formula // @@ -72,112 +66,114 @@ public class ComponentTest extends BaseNonConfigCoreFunctionalTestCase { String pattern = metadata.getDatabase().getJdbcEnvironment().getDialect().extractPattern( TemporalUnit.YEAR ); String formula = pattern.replace( "?1", "YEAR" ).replace( "?2", "dob" ); f.setFormula( formula ); + return metadata; } @Test public void testUpdateFalse() { sessionFactory().getStatistics().clear(); - - Session s = openSession(); - Transaction t = s.beginTransaction(); - User u = new User( "gavin", "secret", new Person("Gavin King", new Date(), "Karbarook Ave") ); - s.persist(u); - s.flush(); - u.getPerson().setName("XXXXYYYYY"); - t.commit(); - s.close(); - + + inTransaction( + s -> { + User u = new User( "gavin", "secret", new Person("Gavin King", new Date(), "Karbarook Ave") ); + s.persist(u); + s.flush(); + u.getPerson().setName("XXXXYYYYY"); + } + ); + assertEquals( 1, sessionFactory().getStatistics().getEntityInsertCount() ); assertEquals( 0, sessionFactory().getStatistics().getEntityUpdateCount() ); - s = openSession(); - t = s.beginTransaction(); - u = s.get(User.class, "gavin"); - assertEquals( u.getPerson().getName(), "Gavin King" ); - s.delete(u); - t.commit(); - s.close(); - + inTransaction( + s -> { + User u = s.get(User.class, "gavin"); + assertEquals( u.getPerson().getName(), "Gavin King" ); + s.delete(u); + } + ); + assertEquals( 1, sessionFactory().getStatistics().getEntityDeleteCount() ); } + @Test public void testComponent() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - User u = new User( "gavin", "secret", new Person("Gavin King", new Date(), "Karbarook Ave") ); - s.persist(u); - s.flush(); - u.getPerson().changeAddress("Phipps Place"); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - u = s.get(User.class, "gavin"); - assertEquals( u.getPerson().getAddress(), "Phipps Place" ); - assertEquals( u.getPerson().getPreviousAddress(), "Karbarook Ave" ); - assertEquals( u.getPerson().getYob(), u.getPerson().getDob().getYear()+1900 ); - u.setPassword("$ecret"); - t.commit(); - s.close(); + inTransaction( + s -> { + User u = new User( "gavin", "secret", new Person("Gavin King", new Date(), "Karbarook Ave") ); + s.persist(u); + s.flush(); + u.getPerson().changeAddress("Phipps Place"); + } + ); - s = openSession(); - t = s.beginTransaction(); - u = s.get(User.class, "gavin"); - assertEquals( u.getPerson().getAddress(), "Phipps Place" ); - assertEquals( u.getPerson().getPreviousAddress(), "Karbarook Ave" ); - assertEquals( u.getPassword(), "$ecret" ); - s.delete(u); - t.commit(); - s.close(); + inTransaction( + s -> { + User u = s.get(User.class, "gavin"); + assertEquals( u.getPerson().getAddress(), "Phipps Place" ); + assertEquals( u.getPerson().getPreviousAddress(), "Karbarook Ave" ); + assertEquals( u.getPerson().getYob(), u.getPerson().getDob().getYear()+1900 ); + u.setPassword("$ecret"); + } + ); + + inTransaction( + s -> { + User u = s.get(User.class, "gavin"); + assertEquals( u.getPerson().getAddress(), "Phipps Place" ); + assertEquals( u.getPerson().getPreviousAddress(), "Karbarook Ave" ); + assertEquals( u.getPassword(), "$ecret" ); + s.delete(u); + } + ); } @Test @TestForIssue( jiraKey = "HHH-2366" ) public void testComponentStateChangeAndDirtiness() { - Session s = openSession(); - s.beginTransaction(); - User u = new User( "steve", "hibernater", new Person( "Steve Ebersole", new Date(), "Main St") ); - s.persist( u ); - s.flush(); - long intialUpdateCount = sessionFactory().getStatistics().getEntityUpdateCount(); - u.getPerson().setAddress( "Austin" ); - s.flush(); - assertEquals( intialUpdateCount + 1, sessionFactory().getStatistics().getEntityUpdateCount() ); - intialUpdateCount = sessionFactory().getStatistics().getEntityUpdateCount(); - u.getPerson().setAddress( "Cedar Park" ); - s.flush(); - assertEquals( intialUpdateCount + 1, sessionFactory().getStatistics().getEntityUpdateCount() ); - s.delete( u ); - s.getTransaction().commit(); - s.close(); + inTransaction( + s -> { + User u = new User( "steve", "hibernater", new Person( "Steve Ebersole", new Date(), "Main St") ); + s.persist( u ); + s.flush(); + long intialUpdateCount = sessionFactory().getStatistics().getEntityUpdateCount(); + u.getPerson().setAddress( "Austin" ); + s.flush(); + assertEquals( intialUpdateCount + 1, sessionFactory().getStatistics().getEntityUpdateCount() ); + intialUpdateCount = sessionFactory().getStatistics().getEntityUpdateCount(); + u.getPerson().setAddress( "Cedar Park" ); + s.flush(); + assertEquals( intialUpdateCount + 1, sessionFactory().getStatistics().getEntityUpdateCount() ); + s.delete( u ); + } + ); } @Test public void testComponentQueries() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Employee emp = new Employee(); - emp.setHireDate( new Date() ); - emp.setPerson( new Person() ); - emp.getPerson().setName( "steve" ); - emp.getPerson().setDob( new Date() ); - s.save( emp ); + inTransaction( + s -> { + Employee emp = new Employee(); + emp.setHireDate( new Date() ); + emp.setPerson( new Person() ); + emp.getPerson().setName( "steve" ); + emp.getPerson().setDob( new Date() ); + s.save( emp ); - s.createQuery( "from Employee e where e.person = :p and 1 = 1 and 2=2" ).setParameter( "p", emp.getPerson() ).list(); - s.createQuery( "from Employee e where :p = e.person" ).setParameter( "p", emp.getPerson() ).list(); - // The following fails on Sybase due to HHH-3510. When HHH-3510 - // is fixed, the check for SybaseASE15Dialect should be removed. - if ( ! ( getDialect() instanceof SybaseASE15Dialect ) ) { - s.createQuery( - "from Employee e where e.person = ('', '', current_timestamp, 0.0, 'steve', '', 0)" ) - .list(); - } + s.createQuery( "from Employee e where e.person = :p and 1 = 1 and 2=2" ).setParameter( "p", emp.getPerson() ).list(); + s.createQuery( "from Employee e where :p = e.person" ).setParameter( "p", emp.getPerson() ).list(); + // The following fails on Sybase due to HHH-3510. When HHH-3510 + // is fixed, the check for SybaseASE15Dialect should be removed. + if ( ! ( getDialect() instanceof SybaseASE15Dialect ) ) { + s.createQuery( + "from Employee e where e.person = ('', '', current_timestamp, 0.0, 'steve', '', 0)" ) + .list(); + } - s.delete( emp ); - t.commit(); - s.close(); + s.delete( emp ); + } + ); } @Test @@ -188,235 +184,220 @@ public class ComponentTest extends BaseNonConfigCoreFunctionalTestCase { // This fails currently due to HHH-3510. The following test should be // deleted and testComponentQueries() should be updated (as noted // in that test case) when HHH-3510 is fixed. - Session s = openSession(); - Transaction t = s.beginTransaction(); - Employee emp = new Employee(); - emp.setHireDate( new Date() ); - emp.setPerson( new Person() ); - emp.getPerson().setName( "steve" ); - emp.getPerson().setDob( new Date() ); - s.save( emp ); - s.createQuery( "from Employee e where e.person = (current_timestamp, 'steve')" ).list(); - s.delete( emp ); - t.commit(); - s.close(); + inTransaction( + s -> { + Employee emp = new Employee(); + emp.setHireDate( new Date() ); + emp.setPerson( new Person() ); + emp.getPerson().setName( "steve" ); + emp.getPerson().setDob( new Date() ); + s.save( emp ); + s.createQuery( "from Employee e where e.person = (current_timestamp, 'steve')" ).list(); + s.delete( emp ); + } + ); } @Test public void testComponentFormulaQuery() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - s.createQuery("from User u where u.person.yob = 1999").list(); - CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); - CriteriaQuery criteria = criteriaBuilder.createQuery( User.class ); - Root root = criteria.from( User.class ); - Join person = root.join( "person", JoinType.INNER ); - criteria.where( criteriaBuilder.between( person.get( "yob" ), new Integer(1999), new Integer(2002) ) ); - s.createQuery( criteria ).list(); + inTransaction( + s -> { + s.createQuery("from User u where u.person.yob = 1999").list(); + CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); + CriteriaQuery criteria = criteriaBuilder.createQuery( User.class ); + Root root = criteria.from( User.class ); + Join person = root.join( "person", JoinType.INNER ); + criteria.where( criteriaBuilder.between( person.get( "yob" ), new Integer(1999), new Integer(2002) ) ); + s.createQuery( criteria ).list(); // s.createCriteria(User.class) // .add( Property.forName("person.yob").between( new Integer(1999), new Integer(2002) ) ) // .list(); - s.createQuery("from User u where u.person = ('Peachtree Rd', 'Peachtree Rd', :dob, 34, 'gavin', 'Karbarook Ave', 1974)") - .setParameter("dob", new Date("March 25, 1974")).list(); - s.createQuery("from User where person = ('Peachtree Rd', 'Peachtree Rd', :dob, 34, 'gavin', 'Karbarook Ave', 1974)") - .setParameter("dob", new Date("March 25, 1974")).list(); - t.commit(); - s.close(); + s.createQuery("from User u where u.person = ('Peachtree Rd', 'Peachtree Rd', :dob, 34, 'gavin', 'Karbarook Ave', 1974)") + .setParameter("dob", new Date("March 25, 1974")).list(); + s.createQuery("from User where person = ('Peachtree Rd', 'Peachtree Rd', :dob, 34, 'gavin', 'Karbarook Ave', 1974)") + .setParameter("dob", new Date("March 25, 1974")).list(); + } + ); } @Test public void testCustomColumnReadAndWrite() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - User u = new User( "steve", "hibernater", new Person( "Steve Ebersole", new Date(), "Main St") ); - final double HEIGHT_INCHES = 73; - final double HEIGHT_CENTIMETERS = HEIGHT_INCHES * 2.54d; - u.getPerson().setHeightInches(HEIGHT_INCHES); - s.persist( u ); - s.flush(); - - // Test value conversion during insert - // Value returned by Oracle native query is a Types.NUMERIC, which is mapped to a BigDecimalType; - // Cast returned value to Number then call Number.doubleValue() so it works on all dialects. - Double heightViaSql = - ( (Number)s.createNativeQuery("select height_centimeters from T_USER where T_USER.userName='steve'").uniqueResult()) - .doubleValue(); - assertEquals(HEIGHT_CENTIMETERS, heightViaSql, 0.01d); + inTransaction( + s -> { + User u = new User( "steve", "hibernater", new Person( "Steve Ebersole", new Date(), "Main St") ); + final double HEIGHT_INCHES = 73; + final double HEIGHT_CENTIMETERS = HEIGHT_INCHES * 2.54d; + u.getPerson().setHeightInches(HEIGHT_INCHES); + s.persist( u ); + s.flush(); - // Test projection - Double heightViaHql = (Double)s.createQuery("select u.person.heightInches from User u where u.id = 'steve'").uniqueResult(); - assertEquals(HEIGHT_INCHES, heightViaHql, 0.01d); - - // Test restriction and entity load via criteria - CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); - CriteriaQuery criteria = criteriaBuilder.createQuery( User.class ); - Root root = criteria.from( User.class ); - Join person = root.join( "person", JoinType.INNER ); - criteria.where( criteriaBuilder.between( person.get( "heightInches" ), HEIGHT_INCHES - 0.01d, HEIGHT_INCHES + 0.01d) ); - u = s.createQuery( criteria ).uniqueResult(); + // Test value conversion during insert + // Value returned by Oracle native query is a Types.NUMERIC, which is mapped to a BigDecimalType; + // Cast returned value to Number then call Number.doubleValue() so it works on all dialects. + Double heightViaSql = + ( (Number)s.createNativeQuery("select height_centimeters from T_USER where T_USER.userName='steve'").uniqueResult()) + .doubleValue(); + assertEquals(HEIGHT_CENTIMETERS, heightViaSql, 0.01d); + + // Test projection + Double heightViaHql = (Double)s.createQuery("select u.person.heightInches from User u where u.id = 'steve'").uniqueResult(); + assertEquals(HEIGHT_INCHES, heightViaHql, 0.01d); + + // Test restriction and entity load via criteria + CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); + CriteriaQuery criteria = criteriaBuilder.createQuery( User.class ); + Root root = criteria.from( User.class ); + Join person = root.join( "person", JoinType.INNER ); + criteria.where( criteriaBuilder.between( person.get( "heightInches" ), HEIGHT_INCHES - 0.01d, HEIGHT_INCHES + 0.01d) ); + u = s.createQuery( criteria ).uniqueResult(); // u = (User)s.createCriteria(User.class) // .add(Restrictions.between("person.heightInches", HEIGHT_INCHES - 0.01d, HEIGHT_INCHES + 0.01d)) // .uniqueResult(); - assertEquals(HEIGHT_INCHES, u.getPerson().getHeightInches(), 0.01d); - - // Test predicate and entity load via HQL - u = (User)s.createQuery("from User u where u.person.heightInches between ?1 and ?2") - .setParameter(1, HEIGHT_INCHES - 0.01d) - .setParameter(2, HEIGHT_INCHES + 0.01d) - .uniqueResult(); - assertEquals(HEIGHT_INCHES, u.getPerson().getHeightInches(), 0.01d); - - // Test update - u.getPerson().setHeightInches(1); - s.flush(); - heightViaSql = - ( (Number)s.createNativeQuery("select height_centimeters from T_USER where T_USER.userName='steve'").uniqueResult() ) - .doubleValue(); - assertEquals(2.54d, heightViaSql, 0.01d); - s.delete(u); - t.commit(); - s.close(); + assertEquals(HEIGHT_INCHES, u.getPerson().getHeightInches(), 0.01d); + + // Test predicate and entity load via HQL + u = (User)s.createQuery("from User u where u.person.heightInches between ?1 and ?2") + .setParameter(1, HEIGHT_INCHES - 0.01d) + .setParameter(2, HEIGHT_INCHES + 0.01d) + .uniqueResult(); + assertEquals(HEIGHT_INCHES, u.getPerson().getHeightInches(), 0.01d); + + // Test update + u.getPerson().setHeightInches(1); + s.flush(); + heightViaSql = + ( (Number)s.createNativeQuery("select height_centimeters from T_USER where T_USER.userName='steve'").uniqueResult() ) + .doubleValue(); + assertEquals(2.54d, heightViaSql, 0.01d); + s.delete(u); + } + ); } @Test public void testNamedQuery() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - s.getNamedQuery("userNameIn") - .setParameterList( "nameList", new Object[] {"1ovthafew", "turin", "xam"} ) - .list(); - t.commit(); - s.close(); + inTransaction( + s -> s.getNamedQuery( "userNameIn") + .setParameterList( "nameList", new Object[] {"1ovthafew", "turin", "xam"} ) + .list() + ); } @Test public void testMergeComponent() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Employee emp = new Employee(); - emp.setHireDate( new Date() ); - emp.setPerson( new Person() ); - emp.getPerson().setName( "steve" ); - emp.getPerson().setDob( new Date() ); - s.persist( emp ); - t.commit(); - s.close(); + Long empId = fromTransaction( + s -> { + Employee e = new Employee(); + e.setHireDate( new Date() ); + e.setPerson( new Person() ); + e.getPerson().setName( "steve" ); + e.getPerson().setDob( new Date() ); + s.persist( e ); + return e.getId(); + } + ); - s = openSession(); - t = s.beginTransaction(); - emp = s.get( Employee.class, emp.getId() ); - t.commit(); - s.close(); + Employee emp = fromTransaction( + s -> s.get( Employee.class, empId ) + ); assertNull(emp.getOptionalComponent()); emp.setOptionalComponent( new OptionalComponent() ); emp.getOptionalComponent().setValue1( "emp-value1" ); emp.getOptionalComponent().setValue2( "emp-value2" ); - s = openSession(); - t = s.beginTransaction(); - emp = (Employee)s.merge( emp ); - t.commit(); - s.close(); + inTransaction( + s -> s.merge( emp ) + ); - s = openSession(); - t = s.beginTransaction(); - emp = s.get( Employee.class, emp.getId() ); - t.commit(); - s.close(); + Employee emp2 = fromTransaction( + s -> s.get( Employee.class, empId ) + ); - assertEquals("emp-value1", emp.getOptionalComponent().getValue1()); - assertEquals("emp-value2", emp.getOptionalComponent().getValue2()); - emp.getOptionalComponent().setValue1( null ); - emp.getOptionalComponent().setValue2( null ); + assertEquals("emp-value1", emp2.getOptionalComponent().getValue1()); + assertEquals("emp-value2", emp2.getOptionalComponent().getValue2()); + emp2.getOptionalComponent().setValue1( null ); + emp2.getOptionalComponent().setValue2( null ); - s = openSession(); - t = s.beginTransaction(); - emp = (Employee)s.merge( emp ); - t.commit(); - s.close(); + inTransaction( + s -> s.merge( emp2 ) + ); - s = openSession(); - t = s.beginTransaction(); - emp = s.get( Employee.class, emp.getId() ); - Hibernate.initialize(emp.getDirectReports()); - t.commit(); - s.close(); + Employee emp3 = fromTransaction( + s -> { + Employee _emp = s.get( Employee.class, empId ); + Hibernate.initialize(_emp.getDirectReports()); + return _emp; + } + ); - assertNull(emp.getOptionalComponent()); + assertNull(emp3.getOptionalComponent()); - Employee emp1 = new Employee(); - emp1.setHireDate( new Date() ); - emp1.setPerson( new Person() ); - emp1.getPerson().setName( "bozo" ); - emp1.getPerson().setDob( new Date() ); - emp.getDirectReports().add( emp1 ); + Employee dr = new Employee(); + dr.setHireDate( new Date() ); + dr.setPerson( new Person() ); + dr.getPerson().setName( "bozo" ); + dr.getPerson().setDob( new Date() ); + emp3.getDirectReports().add( dr ); - s = openSession(); - t = s.beginTransaction(); - emp = (Employee)s.merge( emp ); - t.commit(); - s.close(); + inTransaction( + s -> s.merge( emp3 ) + ); - s = openSession(); - t = s.beginTransaction(); - emp = s.get( Employee.class, emp.getId() ); - Hibernate.initialize(emp.getDirectReports()); - t.commit(); - s.close(); + Employee emp4 = fromTransaction( + s -> { + Employee _emp = s.get( Employee.class, empId ); + Hibernate.initialize(_emp.getDirectReports()); + return _emp; + } + ); - assertEquals(1, emp.getDirectReports().size()); - emp1 = (Employee)emp.getDirectReports().iterator().next(); - assertNull( emp1.getOptionalComponent() ); - emp1.setOptionalComponent( new OptionalComponent() ); - emp1.getOptionalComponent().setValue1( "emp1-value1" ); - emp1.getOptionalComponent().setValue2( "emp1-value2" ); + assertEquals(1, emp4.getDirectReports().size()); + dr = (Employee)emp4.getDirectReports().iterator().next(); + assertNull( dr.getOptionalComponent() ); + dr.setOptionalComponent( new OptionalComponent() ); + dr.getOptionalComponent().setValue1( "dr-value1" ); + dr.getOptionalComponent().setValue2( "dr-value2" ); - s = openSession(); - t = s.beginTransaction(); - emp = (Employee)s.merge( emp ); - t.commit(); - s.close(); + inTransaction( + s -> s.merge( emp4 ) + ); - s = openSession(); - t = s.beginTransaction(); - emp = s.get( Employee.class, emp.getId() ); - Hibernate.initialize(emp.getDirectReports()); - t.commit(); - s.close(); + Employee emp5 = fromTransaction( + s -> { + Employee _emp = s.get( Employee.class, empId ); + Hibernate.initialize(_emp.getDirectReports()); + return _emp; + } + ); - assertEquals(1, emp.getDirectReports().size()); - emp1 = (Employee)emp.getDirectReports().iterator().next(); - assertEquals( "emp1-value1", emp1.getOptionalComponent().getValue1()); - assertEquals( "emp1-value2", emp1.getOptionalComponent().getValue2()); - emp1.getOptionalComponent().setValue1( null ); - emp1.getOptionalComponent().setValue2( null ); + assertEquals(1, emp5.getDirectReports().size()); + dr = (Employee)emp5.getDirectReports().iterator().next(); + assertEquals( "dr-value1", dr.getOptionalComponent().getValue1()); + assertEquals( "dr-value2", dr.getOptionalComponent().getValue2()); + dr.getOptionalComponent().setValue1( null ); + dr.getOptionalComponent().setValue2( null ); - s = openSession(); - t = s.beginTransaction(); - emp = (Employee)s.merge( emp ); - t.commit(); - s.close(); + inTransaction( + s -> s.merge( emp5 ) + ); - s = openSession(); - t = s.beginTransaction(); - emp = s.get( Employee.class, emp.getId() ); - Hibernate.initialize(emp.getDirectReports()); - t.commit(); - s.close(); + Employee emp6 = fromTransaction( + s -> { + Employee _emp = s.get( Employee.class, empId ); + Hibernate.initialize(_emp.getDirectReports()); + return _emp; + } + ); - assertEquals(1, emp.getDirectReports().size()); - emp1 = (Employee)emp.getDirectReports().iterator().next(); - assertNull(emp1.getOptionalComponent()); + assertEquals(1, emp6.getDirectReports().size()); + dr = (Employee)emp6.getDirectReports().iterator().next(); + assertNull(dr.getOptionalComponent()); - s = openSession(); - t = s.beginTransaction(); - s.delete( emp ); - t.commit(); - s.close(); + inTransaction( + s -> s.delete( emp6 ) + ); } - } - diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/function/SybaseASE15FunctionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/function/SybaseASE15FunctionTest.java deleted file mode 100644 index 6e6a05ae88..0000000000 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/function/SybaseASE15FunctionTest.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * Copyright (c) 2010, Red Hat Inc. or third-party contributors as - * indicated by the @author tags or express copyright attribution - * statements applied by the authors. All third-party contributions are - * distributed under license by Red Hat Inc. - * - * This copyrighted material is made available to anyone wishing to use, modify, - * copy, or redistribute it subject to the terms and conditions of the GNU - * Lesser General Public License, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this distribution; if not, write to: - * Free Software Foundation, Inc. - * 51 Franklin Street, Fifth Floor - * Boston, MA 02110-1301 USA - */ -package org.hibernate.orm.test.dialect.function; - -import static java.util.Calendar.MONTH; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.math.BigDecimal; -import java.util.Calendar; -import java.util.Date; - -import org.hibernate.dialect.SybaseASEDialect; -import org.hibernate.query.Query; -import org.hibernate.Session; -import org.hibernate.dialect.SybaseASE15Dialect; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; - -/** - * - * @author Richard H. Tingstad - */ -@RequiresDialect(value = { SybaseASEDialect.class }) -public class SybaseASE15FunctionTest extends BaseCoreFunctionalTestCase { - - private Calendar calendar = Calendar.getInstance(); - - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } - - @Override - public String[] getMappings() { - return new String[] { "dialect/function/Product.hbm.xml" }; - } - - @Override - protected void prepareTest() throws Exception { - final Session s = openSession(); - s.getTransaction().begin(); - Product product = new Product(); - product.setPrice(new BigDecimal(0.5)); - product.setDate( calendar.getTime() ); - s.save( product ); - s.getTransaction().commit(); - s.close(); - } - - @Override - protected void cleanupTest() throws Exception { - final Session s = openSession(); - s.getTransaction().begin(); - s.createQuery( "delete from Product" ).executeUpdate(); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testCharLengthFunction() { - final Session s = openSession(); - s.getTransaction().begin(); - Query query = session.createQuery( "select char_length('123456') from Product" ); - assertEquals(6, ((Number) query.uniqueResult()).intValue()); - s.getTransaction().commit(); - s.close(); - } - - @Test - @TestForIssue(jiraKey = "HHH-7070") - public void testDateaddFunction() { - final Session s = openSession(); - s.getTransaction().begin(); - Query query = session.createQuery( "select dateadd(day, 1, p.date) from Product p" ); - assertTrue(calendar.getTime().before((Date) query.uniqueResult())); - s.getTransaction().commit(); - s.close(); - } - - @Test - @TestForIssue(jiraKey = "HHH-7070") - public void testDatepartFunction() { - final Session s = openSession(); - s.getTransaction().begin(); - Query query = session.createQuery( "select datepart(month, p.date) from Product p" ); - assertEquals(calendar.get(MONTH) + 1, ((Number) query.uniqueResult()).intValue()); - s.getTransaction().commit(); - s.close(); - } - - @Test - @TestForIssue(jiraKey = "HHH-7070") - public void testDatediffFunction() { - final Session s = openSession(); - s.getTransaction().begin(); - Query query = session.createQuery( "SELECT DATEDIFF( DAY, '1999/07/19 00:00', '1999/07/23 23:59' ) from Product" ); - assertEquals(4, ((Number) query.uniqueResult()).intValue()); - s.getTransaction().commit(); - s.close(); - } - - @Test - @TestForIssue(jiraKey = "HHH-7070") - public void testAtn2Function() { - final Session s = openSession(); - s.getTransaction().begin(); - Query query = session.createQuery("select atn2(p.price, .48) from Product p"); - assertEquals(0.805803, ((Number) query.uniqueResult()).doubleValue(), 0.000001 ); - s.getTransaction().commit(); - s.close(); - } - -} diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/function/SybaseASEFunctionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/function/SybaseASEFunctionTest.java new file mode 100644 index 0000000000..26a81bd519 --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/function/SybaseASEFunctionTest.java @@ -0,0 +1,131 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2010, Red Hat Inc. or third-party contributors as + * indicated by the @author tags or express copyright attribution + * statements applied by the authors. All third-party contributions are + * distributed under license by Red Hat Inc. + * + * This copyrighted material is made available to anyone wishing to use, modify, + * copy, or redistribute it subject to the terms and conditions of the GNU + * Lesser General Public License, as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this distribution; if not, write to: + * Free Software Foundation, Inc. + * 51 Franklin Street, Fifth Floor + * Boston, MA 02110-1301 USA + */ +package org.hibernate.orm.test.dialect.function; + +import static java.util.Calendar.MONTH; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.math.BigDecimal; +import java.util.Calendar; +import java.util.Date; + +import org.hibernate.dialect.SybaseASEDialect; +import org.hibernate.query.Query; +import org.hibernate.testing.TestForIssue; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +/** + * + * @author Richard H. Tingstad + */ +@DomainModel( + xmlMappings = "org/hibernate/orm/test/dialect/function/Product.hbm.xml" +) +@SessionFactory +@RequiresDialect(value = SybaseASEDialect.class, version = 1100) +public class SybaseASEFunctionTest { + + private Calendar calendar = Calendar.getInstance(); + + @BeforeAll + protected void prepareTest(SessionFactoryScope scope) throws Exception { + scope.inTransaction( + session -> { + Product product = new Product(); + product.setPrice(new BigDecimal(0.5)); + product.setDate( calendar.getTime() ); + session.save( product ); + } + ); + } + + @AfterAll + protected void cleanupTest(SessionFactoryScope scope) throws Exception { + scope.inTransaction( + session -> session.createQuery( "delete from Product" ).executeUpdate() + ); + } + + @Test + public void testCharLengthFunction(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Query query = session.createQuery( "select char_length('123456') from Product" ); + assertEquals(6, ((Number) query.uniqueResult()).intValue()); + } + ); + } + + @Test + @TestForIssue(jiraKey = "HHH-7070") + public void testDateaddFunction(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Query query = session.createQuery( "select dateadd(day, 1, p.date) from Product p" ); + assertTrue(calendar.getTime().before((Date) query.uniqueResult())); + } + ); + } + + @Test + @TestForIssue(jiraKey = "HHH-7070") + public void testDatepartFunction(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Query query = session.createQuery( "select datepart(month, p.date) from Product p" ); + assertEquals(calendar.get(MONTH) + 1, ((Number) query.uniqueResult()).intValue()); + } + ); + } + + @Test + @TestForIssue(jiraKey = "HHH-7070") + public void testDatediffFunction(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Query query = session.createQuery( "SELECT DATEDIFF( DAY, '1999/07/19 00:00', '1999/07/23 23:59' ) from Product" ); + assertEquals(4, ((Number) query.uniqueResult()).intValue()); + } + ); + } + + @Test + @TestForIssue(jiraKey = "HHH-7070") + public void testAtn2Function(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Query query = session.createQuery("select atn2(p.price, .48) from Product p"); + assertEquals(0.805803, ((Number) query.uniqueResult()).doubleValue(), 0.000001 ); + } + ); + } +} diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/HANASearchTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/HANASearchTest.java index ac8536f875..1748c6c859 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/HANASearchTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/HANASearchTest.java @@ -6,241 +6,258 @@ */ package org.hibernate.orm.test.dialect.functional; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; - import java.sql.PreparedStatement; +import org.hibernate.Transaction; +import org.hibernate.cfg.AvailableSettings; +import org.hibernate.dialect.HANAColumnStoreDialect; +import org.hibernate.query.Query; + +import org.hibernate.testing.TestForIssue; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.hibernate.testing.orm.junit.SkipForDialect; + import jakarta.persistence.Entity; import jakarta.persistence.Id; -import org.hibernate.dialect.HANACloudColumnStoreDialect; -import org.hibernate.dialect.HANAColumnStoreDialect; -import org.hibernate.query.Query; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.SkipForDialect; -import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests the correctness of the SAP HANA fulltext-search functions. * * @author Jonathan Bregler */ -@RequiresDialect(value = { HANAColumnStoreDialect.class }) -@SkipForDialect(value = HANACloudColumnStoreDialect.class) -public class HANASearchTest extends BaseCoreFunctionalTestCase { +@ServiceRegistry( + settings = { + @Setting(name = AvailableSettings.HBM2DDL_AUTO, value = "none") + } +) +@DomainModel( + annotatedClasses = { HANASearchTest.SearchEntity.class } +) +@SessionFactory +@RequiresDialect(HANAColumnStoreDialect.class) +@SkipForDialect(dialectClass = HANAColumnStoreDialect.class, version = 400) +public class HANASearchTest { private static final String ENTITY_NAME = "SearchEntity"; - @Override - protected void prepareTest() throws Exception { - doInHibernate( this::sessionFactory, session -> { - session.doWork( connection -> { - try ( PreparedStatement ps = connection.prepareStatement( "CREATE COLUMN TABLE " + ENTITY_NAME - + " (key INTEGER, t TEXT, c NVARCHAR(255), PRIMARY KEY (key))" ) ) { - ps.execute(); + @BeforeAll + protected void prepareTest(SessionFactoryScope scope) throws Exception { + scope.inTransaction( + session -> session.doWork( + connection -> { + try (PreparedStatement ps = connection.prepareStatement( "CREATE COLUMN TABLE " + ENTITY_NAME + + " (key INTEGER, t TEXT, c NVARCHAR(255), PRIMARY KEY (key))" )) { + ps.execute(); + } + try (PreparedStatement ps = connection + .prepareStatement( "CREATE FULLTEXT INDEX FTI ON " + ENTITY_NAME + " (c)" )) { + ps.execute(); + } + } + ) + ); + } + + @AfterAll + protected void cleanupTest(SessionFactoryScope scope) throws Exception { + scope.inTransaction( + session -> session.doWork( + connection -> { + try (PreparedStatement ps = connection.prepareStatement( "DROP TABLE " + ENTITY_NAME + " CASCADE" )) { + ps.execute(); + } + catch (Exception e) { + // Ignore + } + } + ) + ); + } + + @Test + @TestForIssue(jiraKey = "HHH-13021") + public void testTextType(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + SearchEntity entity = new SearchEntity(); + entity.key = Integer.valueOf( 1 ); + entity.t = "TEST TEXT"; + entity.c = "TEST STRING"; + + session.persist( entity ); + session.flush(); + + Query legacyQuery = session.createQuery( "select b, snippets(t), highlighted(t), score() from " + + ENTITY_NAME + " b where contains(b.t, 'text')", Object[].class ); + + Object[] result = legacyQuery.getSingleResult(); + SearchEntity retrievedEntity = (SearchEntity) result[0]; + + assertEquals( 4, result.length ); + + assertEquals( Integer.valueOf( 1 ), retrievedEntity.key ); + assertEquals( "TEST TEXT", retrievedEntity.t ); + assertEquals( "TEST STRING", retrievedEntity.c ); + + assertEquals( "TEST TEXT", result[1] ); + assertEquals( "TEST TEXT", result[2] ); + assertEquals( 0.75d, result[3] ); } - try ( PreparedStatement ps = connection - .prepareStatement( "CREATE FULLTEXT INDEX FTI ON " + ENTITY_NAME + " (c)" ) ) { - ps.execute(); + ); + } + + @Test + @TestForIssue(jiraKey = "HHH-13021") + public void testTextTypeFalse(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + SearchEntity entity = new SearchEntity(); + entity.key = Integer.valueOf( 1 ); + entity.t = "TEST TEXT"; + entity.c = "TEST STRING"; + + session.persist( entity ); + session.flush(); + + Query legacyQuery = session.createQuery( "select b, snippets(t), highlighted(t), score() from " + ENTITY_NAME + + " b where not contains(b.t, 'string')", Object[].class ); + + Object[] result = legacyQuery.getSingleResult(); + SearchEntity retrievedEntity = (SearchEntity) result[0]; + + assertEquals( 4, result.length ); + + assertEquals( Integer.valueOf( 1 ), retrievedEntity.key ); + assertEquals( "TEST TEXT", retrievedEntity.t ); + assertEquals( "TEST STRING", retrievedEntity.c ); + + assertEquals( "TEST TEXT", result[1] ); + assertEquals( "TEST TEXT", result[2] ); + assertEquals( 1d, result[3] ); } - } ); - } ); + ); } - @Override - protected void cleanupTest() throws Exception { - doInHibernate( this::sessionFactory, session -> { - session.doWork( connection -> { - try ( PreparedStatement ps = connection.prepareStatement( "DROP TABLE " + ENTITY_NAME + " CASCADE" ) ) { - ps.execute(); + @Test + @TestForIssue(jiraKey = "HHH-13021") + public void testCharType(SessionFactoryScope scope) throws Exception { + scope.inSession( + session -> { + Transaction t = session.beginTransaction(); + SearchEntity entity = new SearchEntity(); + entity.key = Integer.valueOf( 1 ); + entity.t = "TEST TEXT"; + entity.c = "TEST STRING"; + + session.persist( entity ); + t.commit(); + + session.beginTransaction(); + session.beginTransaction(); + Query legacyQuery = session.createQuery( + "select b, snippets(c), highlighted(c), score() from " + ENTITY_NAME + + " b where contains(b.c, 'string')", + Object[].class + ); + + Object[] result = legacyQuery.getSingleResult(); + SearchEntity retrievedEntity = (SearchEntity) result[0]; + + assertEquals( 4, result.length ); + + assertEquals( Integer.valueOf( 1 ), retrievedEntity.key ); + assertEquals( "TEST TEXT", retrievedEntity.t ); + assertEquals( "TEST STRING", retrievedEntity.c ); + + assertEquals( "TEST STRING", result[1] ); + assertEquals( "TEST STRING", result[2] ); + assertEquals( 0.75d, result[3] ); } - catch (Exception e) { - // Ignore + ); + } + + @Test + @TestForIssue(jiraKey = "HHH-13021") + public void testCharTypeComplexQuery(SessionFactoryScope scope) { + scope.inSession( + session -> { + Transaction t = session.beginTransaction(); + SearchEntity entity = new SearchEntity(); + entity.key = Integer.valueOf( 1 ); + entity.t = "TEST TEXT"; + entity.c = "TEST STRING"; + + session.persist( entity ); + session.flush(); + t.commit(); + + session.beginTransaction(); + Query legacyQuery = session.createQuery( + "select b, snippets(c), highlighted(c), score() from " + ENTITY_NAME + + " b where contains(b.c, 'string') and key=1 and score() > 0.5", + Object[].class ); + + Object[] result = legacyQuery.getSingleResult(); + SearchEntity retrievedEntity = (SearchEntity) result[0]; + + assertEquals( 4, result.length ); + + assertEquals( Integer.valueOf( 1 ), retrievedEntity.key ); + assertEquals( "TEST TEXT", retrievedEntity.t ); + assertEquals( "TEST STRING", retrievedEntity.c ); + + assertEquals( "TEST STRING", result[1] ); + assertEquals( "TEST STRING", result[2] ); + assertEquals( 0.75d, result[3] ); } - } ); - } ); + ); } @Test @TestForIssue(jiraKey = "HHH-13021") - public void testTextType() throws Exception { - doInHibernate( this::sessionFactory, s -> { - SearchEntity entity = new SearchEntity(); - entity.key = Integer.valueOf( 1 ); - entity.t = "TEST TEXT"; - entity.c = "TEST STRING"; + public void testFuzzy(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Transaction t = session.beginTransaction(); + SearchEntity entity = new SearchEntity(); + entity.key = Integer.valueOf( 1 ); + entity.t = "TEST TEXT"; + entity.c = "TEST STRING"; - s.persist( entity ); + session.persist( entity ); + session.flush(); + t.commit(); - s.flush(); + session.beginTransaction(); - Query legacyQuery = s.createQuery( "select b, snippets(t), highlighted(t), score() from " - + ENTITY_NAME + " b where contains(b.t, 'text')", Object[].class ); + Query legacyQuery = session.createQuery( "select b, snippets(c), highlighted(c), score() from " + ENTITY_NAME + + " b where contains(b.c, 'string', FUZZY(0.7))", Object[].class ); - Object[] result = legacyQuery.getSingleResult(); + Object[] result = legacyQuery.getSingleResult(); + SearchEntity retrievedEntity = (SearchEntity) result[0]; - SearchEntity retrievedEntity = (SearchEntity) result[0]; + assertEquals( 4, result.length ); - assertEquals( 4, result.length ); + assertEquals( Integer.valueOf( 1 ), retrievedEntity.key ); + assertEquals( "TEST TEXT", retrievedEntity.t ); + assertEquals( "TEST STRING", retrievedEntity.c ); - assertEquals( Integer.valueOf( 1 ), retrievedEntity.key ); - assertEquals( "TEST TEXT", retrievedEntity.t ); - assertEquals( "TEST STRING", retrievedEntity.c ); - - assertEquals( "TEST TEXT", result[1] ); - assertEquals( "TEST TEXT", result[2] ); - assertEquals( 0.75d, result[3] ); - } ); - } - - @Test - @TestForIssue(jiraKey = "HHH-13021") - public void testTextTypeFalse() throws Exception { - doInHibernate( this::sessionFactory, s -> { - SearchEntity entity = new SearchEntity(); - entity.key = Integer.valueOf( 1 ); - entity.t = "TEST TEXT"; - entity.c = "TEST STRING"; - - s.persist( entity ); - - s.flush(); - - Query legacyQuery = s.createQuery( "select b, snippets(t), highlighted(t), score() from " + ENTITY_NAME - + " b where not contains(b.t, 'string')", Object[].class ); - - Object[] result = legacyQuery.getSingleResult(); - - SearchEntity retrievedEntity = (SearchEntity) result[0]; - - assertEquals( 4, result.length ); - - assertEquals( Integer.valueOf( 1 ), retrievedEntity.key ); - assertEquals( "TEST TEXT", retrievedEntity.t ); - assertEquals( "TEST STRING", retrievedEntity.c ); - - assertEquals( "TEST TEXT", result[1] ); - assertEquals( "TEST TEXT", result[2] ); - assertEquals( 1d, result[3] ); - } ); - } - - @Test - @TestForIssue(jiraKey = "HHH-13021") - public void testCharType() throws Exception { - doInHibernate( this::sessionFactory, s -> { - SearchEntity entity = new SearchEntity(); - entity.key = Integer.valueOf( 1 ); - entity.t = "TEST TEXT"; - entity.c = "TEST STRING"; - - s.persist( entity ); - - s.getTransaction().commit(); - s.beginTransaction(); - - Query legacyQuery = s.createQuery( "select b, snippets(c), highlighted(c), score() from " + ENTITY_NAME - + " b where contains(b.c, 'string')", Object[].class ); - - Object[] result = legacyQuery.getSingleResult(); - - SearchEntity retrievedEntity = (SearchEntity) result[0]; - - assertEquals( 4, result.length ); - - assertEquals( Integer.valueOf( 1 ), retrievedEntity.key ); - assertEquals( "TEST TEXT", retrievedEntity.t ); - assertEquals( "TEST STRING", retrievedEntity.c ); - - assertEquals( "TEST STRING", result[1] ); - assertEquals( "TEST STRING", result[2] ); - assertEquals( 0.75d, result[3] ); - } ); - } - - @Test - @TestForIssue(jiraKey = "HHH-13021") - public void testCharTypeComplexQuery() throws Exception { - doInHibernate( this::sessionFactory, s -> { - SearchEntity entity = new SearchEntity(); - entity.key = Integer.valueOf( 1 ); - entity.t = "TEST TEXT"; - entity.c = "TEST STRING"; - - s.persist( entity ); - - s.flush(); - - s.getTransaction().commit(); - s.beginTransaction(); - - Query legacyQuery = s.createQuery( - "select b, snippets(c), highlighted(c), score() from " + ENTITY_NAME - + " b where contains(b.c, 'string') and key=1 and score() > 0.5", - Object[].class ); - - Object[] result = legacyQuery.getSingleResult(); - - SearchEntity retrievedEntity = (SearchEntity) result[0]; - - assertEquals( 4, result.length ); - - assertEquals( Integer.valueOf( 1 ), retrievedEntity.key ); - assertEquals( "TEST TEXT", retrievedEntity.t ); - assertEquals( "TEST STRING", retrievedEntity.c ); - - assertEquals( "TEST STRING", result[1] ); - assertEquals( "TEST STRING", result[2] ); - assertEquals( 0.75d, result[3] ); - } ); - } - - @Test - @TestForIssue(jiraKey = "HHH-13021") - public void testFuzzy() throws Exception { - doInHibernate( this::sessionFactory, s -> { - SearchEntity entity = new SearchEntity(); - entity.key = Integer.valueOf( 1 ); - entity.t = "TEST TEXT"; - entity.c = "TEST STRING"; - - s.persist( entity ); - - s.flush(); - - s.getTransaction().commit(); - s.beginTransaction(); - - Query legacyQuery = s.createQuery( "select b, snippets(c), highlighted(c), score() from " + ENTITY_NAME - + " b where contains(b.c, 'string', FUZZY(0.7))", Object[].class ); - - Object[] result = legacyQuery.getSingleResult(); - - SearchEntity retrievedEntity = (SearchEntity) result[0]; - - assertEquals( 4, result.length ); - - assertEquals( Integer.valueOf( 1 ), retrievedEntity.key ); - assertEquals( "TEST TEXT", retrievedEntity.t ); - assertEquals( "TEST STRING", retrievedEntity.c ); - - assertEquals( "TEST STRING", result[1] ); - assertEquals( "TEST STRING", result[2] ); - assertEquals( 0.75d, result[3] ); - } ); - } - - @Override - protected boolean createSchema() { - return false; - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ SearchEntity.class }; + assertEquals( "TEST STRING", result[1] ); + assertEquals( "TEST STRING", result[2] ); + assertEquals( 0.75d, result[3] ); + } + ); } @Entity(name = ENTITY_NAME) @@ -253,5 +270,4 @@ public class HANASearchTest extends BaseCoreFunctionalTestCase { public String c; } - } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/MariaDBExtractSequenceMatadataTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/MariaDBExtractSequenceMetadataTest.java similarity index 75% rename from hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/MariaDBExtractSequenceMatadataTest.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/MariaDBExtractSequenceMetadataTest.java index ce6c026fd0..343b9bca89 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/MariaDBExtractSequenceMatadataTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/MariaDBExtractSequenceMetadataTest.java @@ -7,22 +7,22 @@ import java.sql.SQLException; import java.sql.Statement; import org.hibernate.cfg.Environment; -import org.hibernate.dialect.MariaDB103Dialect; +import org.hibernate.dialect.MariaDBDialect; import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; -import org.hibernate.testing.BeforeClassOnce; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.ServiceRegistryBuilder; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * @author Nathan Xu */ -@RequiresDialect(MariaDB103Dialect.class) -public class MariaDBExtractSequenceMatadataTest extends BaseCoreFunctionalTestCase { +@RequiresDialect(value = MariaDBDialect.class, version = 1030) +public class MariaDBExtractSequenceMetadataTest { private static String primaryDbName; private static String primarySequenceName = "seq_HHH13373"; @@ -30,7 +30,7 @@ public class MariaDBExtractSequenceMatadataTest extends BaseCoreFunctionalTestCa private static String secondaryDbName = "secondary_db_HHH13373"; private static String secondarySequenceName = "secondary_seq_HHH13373"; - @BeforeClassOnce + @BeforeAll public static void setUpDBs() throws Exception { try (Connection conn = getConnection()) { try (Statement stmt = conn.createStatement()) { @@ -51,11 +51,11 @@ public class MariaDBExtractSequenceMatadataTest extends BaseCoreFunctionalTestCa @Test @TestForIssue(jiraKey = "HHH-13373") public void testHibernateLaunchedSuccessfully() { - JdbcEnvironment jdbcEnvironment = serviceRegistry().getService( JdbcEnvironment.class ); - Assert.assertFalse( jdbcEnvironment.getExtractedDatabaseMetaData().getSequenceInformationList().isEmpty() ); + JdbcEnvironment jdbcEnvironment = ServiceRegistryBuilder.buildServiceRegistry(Environment.getProperties()).getService( JdbcEnvironment.class ); + Assertions.assertFalse( jdbcEnvironment.getExtractedDatabaseMetaData().getSequenceInformationList().isEmpty() ); } - @AfterClass + @AfterAll public static void tearDownDBs() throws SQLException { try (Connection conn = getConnection()) { try (Statement stmt = conn.createStatement()) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/OracleFollowOnLockingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/OracleFollowOnLockingTest.java index a44b0ac7f0..99c4ce67ec 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/OracleFollowOnLockingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/OracleFollowOnLockingTest.java @@ -14,7 +14,6 @@ import jakarta.persistence.Inheritance; import jakarta.persistence.InheritanceType; import jakarta.persistence.LockModeType; import jakarta.persistence.NamedQuery; -import jakarta.persistence.PersistenceException; import jakarta.persistence.QueryHint; import org.hibernate.LockMode; @@ -22,9 +21,7 @@ import org.hibernate.LockOptions; import org.hibernate.Session; import org.hibernate.annotations.QueryHints; import org.hibernate.boot.SessionFactoryBuilder; -import org.hibernate.dialect.Oracle8iDialect; import org.hibernate.dialect.OracleDialect; -import org.hibernate.exception.SQLGrammarException; import org.hibernate.query.IllegalQueryOperationException; import org.hibernate.testing.RequiresDialect; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/OracleSequenceInfoTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/OracleSequenceInfoTest.java index c866ee2d63..b3da49b7d4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/OracleSequenceInfoTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/OracleSequenceInfoTest.java @@ -6,22 +6,20 @@ */ package org.hibernate.orm.test.dialect.functional; -import org.hibernate.dialect.Oracle8iDialect; +import org.hibernate.dialect.OracleDialect; import org.hibernate.tool.schema.extract.spi.SequenceInformation; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.TestForIssue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; /** * @author Vlad Mihalcea */ @TestForIssue(jiraKey = "HHH-12973") -@RequiresDialect(value = { - Oracle8iDialect.class -}) +@RequiresDialect(value = OracleDialect.class) public class OracleSequenceInfoTest extends SequenceInformationTest { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SequenceInformationMariaDBTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SequenceInformationMariaDBTest.java index 0564a983fc..d712a9c5fe 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SequenceInformationMariaDBTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SequenceInformationMariaDBTest.java @@ -9,7 +9,6 @@ package org.hibernate.orm.test.dialect.functional; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; -import java.util.Map; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; @@ -20,40 +19,40 @@ import jakarta.persistence.Table; import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Environment; -import org.hibernate.dialect.MariaDB103Dialect; +import org.hibernate.dialect.MariaDBDialect; import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl; -import org.hibernate.tool.hbm2ddl.SchemaExport; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.hibernate.testing.RequiresDialect; import org.hibernate.testing.TestForIssue; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.Setting; -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.fail; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; + +import static org.junit.jupiter.api.Assertions.fail; /** * @author Vlad Mihalcea */ @TestForIssue(jiraKey = "HHH-12973") -@RequiresDialect(MariaDB103Dialect.class) -public class SequenceInformationMariaDBTest extends - BaseEntityManagerFunctionalTestCase { +@RequiresDialect(value = MariaDBDialect.class, version = 1030) +@Jpa( + annotatedClasses = { + SequenceInformationMariaDBTest.Book.class, + SequenceInformationMariaDBTest.Author.class + }, + integrationSettings = { + @Setting(name = AvailableSettings.HBM2DDL_AUTO, value = "none") + } +) +public class SequenceInformationMariaDBTest { private DriverManagerConnectionProviderImpl connectionProvider; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Book.class, - Author.class - }; - } - - @Override - public void buildEntityManagerFactory() { + @BeforeAll + public void init() { connectionProvider = new DriverManagerConnectionProviderImpl(); connectionProvider.configure( Environment.getProperties() ); @@ -64,6 +63,7 @@ public class SequenceInformationMariaDBTest extends statement.execute( "DROP SEQUENCE IF EXISTS author_sequence" ); } catch (SQLException e) { + } try { statement.execute( "DROP TABLE TBL_BOOK" ); @@ -101,16 +101,10 @@ public class SequenceInformationMariaDBTest extends catch (SQLException e) { fail(e.getMessage()); } - - super.buildEntityManagerFactory(); } - @Override + @AfterAll public void releaseResources() { - super.releaseResources(); - - super.releaseResources(); - try(Connection connection = connectionProvider.getConnection(); Statement statement = connection.createStatement()) { try { @@ -135,19 +129,16 @@ public class SequenceInformationMariaDBTest extends } } - @Override - protected void addMappings(Map settings) { - settings.put( AvailableSettings.HBM2DDL_AUTO, "none" ); - } - @Test - public void test() { - doInJPA( this::entityManagerFactory, entityManager -> { - Book book = new Book(); - book.setTitle("My Book"); + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + Book book = new Book(); + book.setTitle("My Book"); - entityManager.persist(book); - } ); + entityManager.persist(book); + } + ); } @Entity diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SequenceInformationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SequenceInformationTest.java index 980d946394..615b99d6d2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SequenceInformationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SequenceInformationTest.java @@ -10,6 +10,7 @@ import java.util.EnumSet; import java.util.List; import java.util.Map; import jakarta.persistence.Entity; +import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; @@ -20,42 +21,34 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.cfg.AvailableSettings; import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; import org.hibernate.service.ServiceRegistry; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.schema.TargetType; import org.hibernate.tool.schema.extract.spi.SequenceInformation; -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.DialectFeatureChecks; +import org.hibernate.testing.orm.junit.RequiresDialectFeature; import org.hibernate.testing.TestForIssue; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryBasedFunctionalTest; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Vlad Mihalcea */ @TestForIssue(jiraKey = "HHH-12973") -@RequiresDialectFeature(DialectChecks.SupportsSequences.class) +@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsSequences.class) public class SequenceInformationTest extends - BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class, - Vehicle.class - }; - } + EntityManagerFactoryBasedFunctionalTest { protected ServiceRegistry serviceRegistry; protected MetadataImplementor metadata; @Override - public void buildEntityManagerFactory() { + public EntityManagerFactory produceEntityManagerFactory() { serviceRegistry = new StandardServiceRegistryBuilder().build(); metadata = (MetadataImplementor) new MetadataSources( serviceRegistry ) .addAnnotatedClass( Product.class ) @@ -64,20 +57,18 @@ public class SequenceInformationTest extends new SchemaExport().drop( EnumSet.of( TargetType.DATABASE ), metadata ); new SchemaExport().create( EnumSet.of( TargetType.DATABASE ), metadata ); - super.buildEntityManagerFactory(); + return super.produceEntityManagerFactory(); } - @Override + @AfterAll public void releaseResources() { - super.releaseResources(); - new SchemaExport().drop( EnumSet.of( TargetType.DATABASE ), metadata ); StandardServiceRegistryBuilder.destroy( serviceRegistry ); } @Override - protected void addMappings(Map settings) { - settings.put( AvailableSettings.HBM2DDL_AUTO, "none" ); + protected void addConfigOptions(Map options) { + options.put( AvailableSettings.HBM2DDL_AUTO, "none" ); } @Test diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/generatedkeys/select/MyEntity.hbm.xml b/hibernate-core/src/test/java/org/hibernate/orm/test/generatedkeys/select/MyEntity.hbm.xml index 139b54e7ae..6f1c892446 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/generatedkeys/select/MyEntity.hbm.xml +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/generatedkeys/select/MyEntity.hbm.xml @@ -9,7 +9,7 @@ "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> - + diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/generatedkeys/select/SelectGeneratorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/generatedkeys/select/SelectGeneratorTest.java index bfc188c90a..61da050aa2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/generatedkeys/select/SelectGeneratorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/generatedkeys/select/SelectGeneratorTest.java @@ -6,36 +6,39 @@ */ package org.hibernate.orm.test.generatedkeys.select; -import org.junit.Test; +import org.hibernate.dialect.OracleDialect; -import org.hibernate.Session; -import org.hibernate.dialect.Oracle9iDialect; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.Assert.assertEquals; /** * @author Steve Ebersole */ -@RequiresDialect( Oracle9iDialect.class ) -public class SelectGeneratorTest extends BaseCoreFunctionalTestCase { - public String[] getMappings() { - return new String[] { "generatedkeys/select/MyEntity.hbm.xml" }; - } +@DomainModel( + xmlMappings = "org/hibernate/orm/test/generatedkeys/select/MyEntity.hbm.xml" +) +@SessionFactory +@RequiresDialect(value = OracleDialect.class, version = 900) +public class SelectGeneratorTest { @Test - public void testJDBC3GetGeneratedKeysSupportOnOracle() { - Session session = openSession(); - session.beginTransaction(); + public void testJDBC3GetGeneratedKeysSupportOnOracle(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + MyEntity e = new MyEntity( "entity-1" ); + session.save( e ); - MyEntity e = new MyEntity( "entity-1" ); - session.save( e ); + // this insert should happen immediately! + assertEquals( new Long(1), e.getId(), "id not generated through forced insertion" ); - // this insert should happen immediately! - assertEquals( "id not generated through forced insertion", new Long(1), e.getId() ); - - session.delete( e ); - session.getTransaction().commit(); - session.close(); + session.delete( e ); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/generatedkeys/seqidentity/JoinedSequenceIdentityBatchTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/generatedkeys/seqidentity/JoinedSequenceIdentityBatchTest.java index c33b632ae3..bc6358edab 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/generatedkeys/seqidentity/JoinedSequenceIdentityBatchTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/generatedkeys/seqidentity/JoinedSequenceIdentityBatchTest.java @@ -8,7 +8,6 @@ package org.hibernate.orm.test.generatedkeys.seqidentity; import java.io.Serializable; import java.util.List; -import java.util.Map; import jakarta.persistence.Column; import jakarta.persistence.DiscriminatorColumn; import jakarta.persistence.DiscriminatorType; @@ -25,25 +24,41 @@ import jakarta.persistence.Table; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; import org.hibernate.cfg.AvailableSettings; -import org.hibernate.dialect.Oracle9iDialect; +import org.hibernate.dialect.OracleDialect; -import org.hibernate.testing.RequiresDialect; import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +@ServiceRegistry( + settings = { + @Setting( name = AvailableSettings.STATEMENT_BATCH_SIZE, value = "5" ), + @Setting( name = AvailableSettings.USE_GET_GENERATED_KEYS, value = "true" ) + } +) +@DomainModel( + annotatedClasses = { + JoinedSequenceIdentityBatchTest.Resource.class, + JoinedSequenceIdentityBatchTest.FolderResource.class + } +) +@SessionFactory @TestForIssue( jiraKey = "HHH-13365" ) -@RequiresDialect( Oracle9iDialect.class ) -public class JoinedSequenceIdentityBatchTest extends BaseNonConfigCoreFunctionalTestCase { +@RequiresDialect( value = OracleDialect.class, version = 900 ) +public class JoinedSequenceIdentityBatchTest { @Test - public void testInsertAndUpdate() { - doInHibernate( - this::sessionFactory, + public void testInsertAndUpdate(SessionFactoryScope scope) { + scope.inTransaction( session -> { FolderResource folder = new FolderResource(); folder.name = "PARENT"; @@ -51,19 +66,17 @@ public class JoinedSequenceIdentityBatchTest extends BaseNonConfigCoreFunctional } ); - doInHibernate( - this::sessionFactory, + scope.inTransaction( session -> { List folderResources = session.createQuery( "from FolderResource" ).getResultList(); assertEquals( 1, folderResources.size() ); final FolderResource folderResource = folderResources.get( 0 ); assertNull( folderResource.description ); folderResource.description = "A folder resource"; - } + } ); - doInHibernate( - this::sessionFactory, + scope.inTransaction( session -> { List folderResources = session.createQuery( "from FolderResource" ).getResultList(); assertEquals( 1, folderResources.size() ); @@ -73,19 +86,6 @@ public class JoinedSequenceIdentityBatchTest extends BaseNonConfigCoreFunctional ); } - @Override - @SuppressWarnings( "unchecked" ) - protected void addSettings(Map settings) { - super.addSettings( settings ); - settings.put( AvailableSettings.STATEMENT_BATCH_SIZE, "5" ); - settings.put( AvailableSettings.USE_GET_GENERATED_KEYS, "true" ); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Resource.class, FolderResource.class }; - } - @Entity(name = "Resource") @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "WORKSPACE_RESOURCE") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/generatedkeys/seqidentity/MyEntity.hbm.xml b/hibernate-core/src/test/java/org/hibernate/orm/test/generatedkeys/seqidentity/MyEntity.hbm.xml index 2cd4445a11..fd9b6aa10a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/generatedkeys/seqidentity/MyEntity.hbm.xml +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/generatedkeys/seqidentity/MyEntity.hbm.xml @@ -9,7 +9,7 @@ "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> - + diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/generatedkeys/seqidentity/SequenceIdentityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/generatedkeys/seqidentity/SequenceIdentityTest.java index cc566fd4e1..4f07d78dba 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/generatedkeys/seqidentity/SequenceIdentityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/generatedkeys/seqidentity/SequenceIdentityTest.java @@ -6,47 +6,50 @@ */ package org.hibernate.orm.test.generatedkeys.seqidentity; -import org.junit.Test; - -import org.hibernate.Session; -import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; -import org.hibernate.dialect.Oracle9iDialect; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.hibernate.dialect.OracleDialect; -import static org.junit.Assert.assertNotNull; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Steve Ebersole */ -@RequiresDialect( Oracle9iDialect.class ) -public class SequenceIdentityTest extends BaseCoreFunctionalTestCase { - public void configure(Configuration cfg) { - //this test makes no sense w/o the following property enabled - //note : this property is set to false by default in Oracle9iDialect - //but if this property is set to false, then the AssertionFailure will - //be thrown by {@link org.hibernate.engine.jdbc.internal.StatementPreparerImpl.checkAutoGeneratedKeysSupportEnabled()} - //so let just change this here and this should be invested deeper. - cfg.setProperty( Environment.USE_GET_GENERATED_KEYS, "true" ); - } - - public String[] getMappings() { - return new String[] { "generatedkeys/seqidentity/MyEntity.hbm.xml" }; - } +@ServiceRegistry( + settings = { + //this test makes no sense w/o the following property enabled + //note : this property is set to false by default in Oracle9iDialect + //but if this property is set to false, then the AssertionFailure will + //be thrown by {@link org.hibernate.engine.jdbc.internal.StatementPreparerImpl.checkAutoGeneratedKeysSupportEnabled()} + //so let just change this here and this should be invested deeper. + @Setting( name = Environment.USE_GET_GENERATED_KEYS, value = "true") + } +) +@DomainModel( + xmlMappings = "org/hibernate/orm/test/generatedkeys/seqidentity/MyEntity.hbm.xml" +) +@SessionFactory +@RequiresDialect(value = OracleDialect.class, version = 900) +public class SequenceIdentityTest { @Test - public void testSequenceIdentityGenerator() { - Session session = openSession(); - session.beginTransaction(); + public void testSequenceIdentityGenerator(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + MyEntity e = new MyEntity( "entity-1" ); + session.save( e ); - MyEntity e = new MyEntity( "entity-1" ); - session.save( e ); + // this insert should happen immediately! + assertNotNull( e.getId(), "id not generated through forced insertion" ); - // this insert should happen immediately! - assertNotNull( "id not generated through forced insertion", e.getId() ); - - session.delete( e ); - session.getTransaction().commit(); - session.close(); + session.delete( e ); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/ManipulationCriteriaTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/ManipulationCriteriaTest.java index 620f5b1553..a4cd36de60 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/ManipulationCriteriaTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/ManipulationCriteriaTest.java @@ -6,9 +6,6 @@ */ package org.hibernate.orm.test.jpa.criteria; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import jakarta.persistence.EntityManager; import jakarta.persistence.Query; import jakarta.persistence.criteria.CriteriaBuilder; @@ -21,9 +18,13 @@ import org.hibernate.dialect.MySQLDialect; import org.hibernate.jpa.test.metamodel.AbstractMetamodelSpecificTest; import org.hibernate.jpa.test.metamodel.Customer; import org.hibernate.jpa.test.metamodel.Customer_; -import org.hibernate.testing.SkipForDialect; import org.hibernate.testing.TestForIssue; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SkipForDialect; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Steve Ebersole @@ -181,7 +182,7 @@ public class ManipulationCriteriaTest extends AbstractMetamodelSpecificTest { @Test // MySQL does not allow "delete/update from" and subqueries to use the same table - @SkipForDialect(MySQLDialect.class) + @SkipForDialect(dialectClass = MySQLDialect.class) public void testDeleteWithUnCorrelatedSubquery() { CriteriaBuilder builder = entityManagerFactory().getCriteriaBuilder(); EntityManager em = getOrCreateEntityManager(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/basic/AggregationResultTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/basic/AggregationResultTest.java index ced495276d..95fbc71782 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/basic/AggregationResultTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/basic/AggregationResultTest.java @@ -13,22 +13,23 @@ import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Root; -import junit.framework.AssertionFailedError; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - import org.hibernate.jpa.test.metamodel.AbstractMetamodelSpecificTest; import org.hibernate.jpa.test.metamodel.Product; import org.hibernate.jpa.test.metamodel.Product_; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + /** * @author Steve Ebersole */ public class AggregationResultTest extends AbstractMetamodelSpecificTest { private CriteriaBuilder builder; - @Before + @BeforeEach public void createTestData() { builder = entityManagerFactory().getCriteriaBuilder(); @@ -47,7 +48,7 @@ public class AggregationResultTest extends AbstractMetamodelSpecificTest { em.close(); } - @After + @AfterEach public void cleanUpTestData() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); @@ -154,7 +155,7 @@ public class AggregationResultTest extends AbstractMetamodelSpecificTest { private void assertReturnType(Class expectedType, Object value) { if ( value != null && ! expectedType.isInstance( value ) ) { - throw new AssertionFailedError( + fail( "Result value was not of expected type: expected [" + expectedType.getName() + "] but found [" + value.getClass().getName() + "]" ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/basic/ExpressionsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/basic/ExpressionsTest.java index fe205f4db4..513389c9bd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/basic/ExpressionsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/basic/ExpressionsTest.java @@ -26,13 +26,14 @@ import org.hibernate.jpa.test.metamodel.Phone; import org.hibernate.jpa.test.metamodel.Product; import org.hibernate.jpa.test.metamodel.Product_; -import org.hibernate.testing.SkipForDialect; import org.hibernate.testing.TestForIssue; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SkipForDialect; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests that various expressions operate as expected @@ -42,7 +43,7 @@ import static org.junit.Assert.assertEquals; public class ExpressionsTest extends AbstractMetamodelSpecificTest { private CriteriaBuilder builder; - @Before + @BeforeEach public void prepareTestData() { builder = entityManagerFactory().getCriteriaBuilder(); @@ -61,7 +62,7 @@ public class ExpressionsTest extends AbstractMetamodelSpecificTest { em.close(); } - @After + @AfterEach public void cleanupTestData() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); @@ -218,11 +219,11 @@ public class ExpressionsTest extends AbstractMetamodelSpecificTest { } @Test - @SkipForDialect(value = DerbyDialect.class, comment = "By default, unless some kind of context enables inference," + + @SkipForDialect(dialectClass = DerbyDialect.class, reason = "By default, unless some kind of context enables inference," + "a numeric/decimal parameter has the type DECIMAL(31,31) which might cause an overflow on certain arithmetics." + "Fixing this would require a custom SqmToSqlAstConverter that creates a special JdbcParameter " + "that is always rendered as literal. Since numeric literal + parameter arithmetic is rare, we skip this for now.") - @SkipForDialect(value = DB2Dialect.class, comment = "Same reason as for Derby") + @SkipForDialect(dialectClass = DB2Dialect.class, reason = "Same reason as for Derby") public void testQuotientAndMultiply() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/basic/ListIndexTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/basic/ListIndexTest.java index 61e94608fe..426dbe59de 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/basic/ListIndexTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/basic/ListIndexTest.java @@ -6,9 +6,6 @@ */ package org.hibernate.orm.test.jpa.criteria.basic; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - import java.util.List; import jakarta.persistence.EntityManager; @@ -22,7 +19,12 @@ import org.hibernate.jpa.test.metamodel.Address; import org.hibernate.jpa.test.metamodel.Address_; import org.hibernate.jpa.test.metamodel.Phone; import org.hibernate.testing.TestForIssue; -import org.junit.Test; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Tests usage of {@link ListJoin#index()} @@ -30,7 +32,17 @@ import org.junit.Test; * @author Brett Meyer */ public class ListIndexTest extends AbstractMetamodelSpecificTest { - + + @AfterEach + public void cleanupTestData() { + EntityManager em = getOrCreateEntityManager(); + em.getTransaction().begin(); + em.createQuery( "delete Phone" ).executeUpdate(); + em.createQuery( "delete Address" ).executeUpdate(); + em.getTransaction().commit(); + em.close(); + } + @Test @TestForIssue(jiraKey = "HHH-8404") public void testListIndex() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/basic/PredicateTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/basic/PredicateTest.java index 42650f5d90..8448c036b5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/basic/PredicateTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/basic/PredicateTest.java @@ -13,21 +13,25 @@ import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Path; import jakarta.persistence.criteria.Predicate; import jakarta.persistence.criteria.Root; + import org.hibernate.dialect.CockroachDialect; -import org.hibernate.dialect.Oracle12cDialect; +import org.hibernate.dialect.OracleDialect; import org.hibernate.jpa.test.metamodel.AbstractMetamodelSpecificTest; import org.hibernate.jpa.test.metamodel.CreditCard; import org.hibernate.jpa.test.metamodel.CreditCard_; import org.hibernate.jpa.test.metamodel.Customer_; import org.hibernate.jpa.test.metamodel.Order; import org.hibernate.jpa.test.metamodel.Order_; -import org.hibernate.testing.SkipForDialect; import org.hibernate.testing.TestForIssue; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.SkipForDialect; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test the various predicates. @@ -38,11 +42,11 @@ import static org.junit.Assert.assertTrue; public class PredicateTest extends AbstractMetamodelSpecificTest { private CriteriaBuilder builder; - @Before + @BeforeEach public void prepareTestData() { builder = entityManagerFactory().getCriteriaBuilder(); - EntityManager em = entityManagerFactory().createEntityManager(); + EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( new Order( "order-1", 1.0d ) ); em.persist( new Order( "order-2", 10.0d ) ); @@ -51,6 +55,17 @@ public class PredicateTest extends AbstractMetamodelSpecificTest { em.close(); } + @AfterEach + public void cleanUp() { + EntityManager em = getOrCreateEntityManager(); + em.getTransaction().begin(); + + em.createQuery( "delete from Order" ).executeUpdate(); + + em.getTransaction().commit(); + em.close(); + } + @Test public void testEmptyConjunction() { EntityManager em = getOrCreateEntityManager(); @@ -125,6 +140,7 @@ public class PredicateTest extends AbstractMetamodelSpecificTest { assertEquals( 2, orders.size() ); em.getTransaction().commit(); em.close(); + } /** @@ -224,8 +240,9 @@ public class PredicateTest extends AbstractMetamodelSpecificTest { * Check predicate for field which has simple byte array type (byte[]). */ @Test - @SkipForDialect(value = Oracle12cDialect.class, jiraKey = "HHH-10603", - comment = "Oracle12cDialect uses blob to store byte arrays and it's not possible to compare blobs with simple equality operators.") + @JiraKey( "HHH-10603" ) + @SkipForDialect(dialectClass = OracleDialect.class, version = 1200, + reason = "Oracle12cDialect uses blob to store byte arrays and it's not possible to compare blobs with simple equality operators.") public void testByteArray() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); @@ -244,7 +261,7 @@ public class PredicateTest extends AbstractMetamodelSpecificTest { @Test @TestForIssue( jiraKey = "HHH-5803" ) - @SkipForDialect( value = CockroachDialect.class, comment = "https://github.com/cockroachdb/cockroach/issues/41943") + @SkipForDialect( dialectClass = CockroachDialect.class, reason = "https://github.com/cockroachdb/cockroach/issues/41943") public void testQuotientConversion() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/idclass/IdClassPredicateTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/idclass/IdClassPredicateTest.java index 46e595793e..f2b90b76f3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/idclass/IdClassPredicateTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/idclass/IdClassPredicateTest.java @@ -15,10 +15,10 @@ import jakarta.persistence.criteria.Expression; import jakarta.persistence.criteria.Predicate; import jakarta.persistence.criteria.Root; -import junit.framework.Assert; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +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 org.hibernate.jpa.test.metamodel.AbstractMetamodelSpecificTest; @@ -35,7 +35,7 @@ public class IdClassPredicateTest extends AbstractMetamodelSpecificTest { }; } - @Before + @BeforeEach public void prepareTestData() { EntityManager em = entityManagerFactory().createEntityManager(); em.getTransaction().begin(); @@ -117,7 +117,7 @@ public class IdClassPredicateTest extends AbstractMetamodelSpecificTest { } - @After + @AfterEach public void cleanupTestData() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); @@ -179,7 +179,7 @@ public class IdClassPredicateTest extends AbstractMetamodelSpecificTest { // Retrieving query.; List widgets = em.createQuery( query ).getResultList( ); - Assert.assertEquals( 4, widgets.size() ); + Assertions.assertEquals( 4, widgets.size() ); em.getTransaction().commit(); em.close(); @@ -205,7 +205,7 @@ public class IdClassPredicateTest extends AbstractMetamodelSpecificTest { // Retrieving query. List tools = em.createQuery( query ).getResultList( ); - Assert.assertEquals( 4, tools.size() ); + Assertions.assertEquals( 4, tools.size() ); em.getTransaction().commit(); em.close(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/mapjoin/MapJoinTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/mapjoin/MapJoinTest.java index 489fa631ab..530a155447 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/mapjoin/MapJoinTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/mapjoin/MapJoinTest.java @@ -17,7 +17,8 @@ import org.hibernate.jpa.test.metamodel.MapEntity; import org.hibernate.jpa.test.metamodel.MapEntityLocal; import org.hibernate.jpa.test.metamodel.MapEntityLocal_; import org.hibernate.jpa.test.metamodel.MapEntity_; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class MapJoinTest extends AbstractMetamodelSpecificTest { @@ -25,6 +26,7 @@ public class MapJoinTest extends AbstractMetamodelSpecificTest { public Class[] getAnnotatedClasses() { return new Class[] { MapEntity.class, MapEntityLocal.class }; } + @Test public void allEntities() { EntityManager em = getOrCreateEntityManager(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/nulliteral/CriteriaLiteralInSelectExpressionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/nulliteral/CriteriaLiteralInSelectExpressionTest.java index cfdbf51de3..33b908402c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/nulliteral/CriteriaLiteralInSelectExpressionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/nulliteral/CriteriaLiteralInSelectExpressionTest.java @@ -8,7 +8,6 @@ package org.hibernate.orm.test.jpa.criteria.nulliteral; import jakarta.persistence.Column; import jakarta.persistence.Entity; -import jakarta.persistence.EntityManager; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.Table; @@ -22,210 +21,153 @@ import java.util.List; import org.hibernate.dialect.AbstractHANADialect; import org.hibernate.dialect.DB2Dialect; -import org.hibernate.dialect.Oracle8iDialect; +import org.hibernate.dialect.OracleDialect; import org.hibernate.dialect.SQLServerDialect; import org.hibernate.dialect.SybaseDialect; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.SkipForDialect; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.SkipForDialect; import org.hibernate.testing.TestForIssue; import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; /** * @author Andrea Boriero */ -public class CriteriaLiteralInSelectExpressionTest extends BaseEntityManagerFunctionalTestCase { +@Jpa( + annotatedClasses = {CriteriaLiteralInSelectExpressionTest.MyEntity.class} +) +public class CriteriaLiteralInSelectExpressionTest { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] {MyEntity.class}; + @BeforeAll + public void init(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> entityManager.persist( new MyEntity( "Fab", "A" ) ) + ); } - @Before - public void init() { - final EntityManager entityManager = getOrCreateEntityManager(); - try { - entityManager.getTransaction().begin(); - entityManager.persist( new MyEntity( "Fab", "A" ) ); - entityManager.getTransaction().commit(); - } - catch (Exception e) { - if ( entityManager.getTransaction().isActive() ) { - entityManager.getTransaction().rollback(); - } - throw e; - } - finally { - entityManager.close(); - } + @AfterAll + public void tearDown(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> entityManager.createQuery( "delete from MyEntity" ).executeUpdate() + ); } @Test @TestForIssue(jiraKey = "HHH-10729") - public void testBooleanLiteral() throws Exception { - final EntityManager entityManager = getOrCreateEntityManager(); - try { - entityManager.getTransaction().begin(); + public void testBooleanLiteral(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); + final CriteriaQuery query = criteriaBuilder.createQuery( MyEntityDTO.class ); + final Root entity = query.from( MyEntity.class ); - final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); - final CriteriaQuery query = criteriaBuilder.createQuery( MyEntityDTO.class ); - final Root entity = query.from( MyEntity.class ); + query.multiselect( criteriaBuilder.literal( false ), entity.get( "name" ) ); - query.multiselect( criteriaBuilder.literal( false ), entity.get( "name" ) ); + final List dtos = entityManager.createQuery( query ).getResultList(); - final List dtos = entityManager.createQuery( query ).getResultList(); - - assertThat( dtos.size(), is( 1 ) ); - assertThat( dtos.get( 0 ).active, is( false ) ); - assertThat( dtos.get( 0 ).name, is( "Fab" ) ); - assertThat( dtos.get( 0 ).surname, nullValue() ); - - entityManager.getTransaction().commit(); - } - catch (Exception e) { - if ( entityManager.getTransaction().isActive() ) { - entityManager.getTransaction().rollback(); - } - throw e; - } - finally { - entityManager.close(); - } + assertThat( dtos.size(), is( 1 ) ); + assertThat( dtos.get( 0 ).active, is( false ) ); + assertThat( dtos.get( 0 ).name, is( "Fab" ) ); + assertThat( dtos.get( 0 ).surname, nullValue() ); + } + ); } @Test @TestForIssue(jiraKey = "HHH-10861") - public void testNullLiteral() throws Exception { - final EntityManager entityManager = getOrCreateEntityManager(); - try { - entityManager.getTransaction().begin(); + public void testNullLiteral(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); + final CriteriaQuery query = criteriaBuilder.createQuery( MyEntityDTO.class ); + final Root entity = query.from( MyEntity.class ); - final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); - final CriteriaQuery query = criteriaBuilder.createQuery( MyEntityDTO.class ); - final Root entity = query.from( MyEntity.class ); + query.multiselect( criteriaBuilder.literal( false ), criteriaBuilder.nullLiteral( String.class ) ); - query.multiselect( criteriaBuilder.literal( false ), criteriaBuilder.nullLiteral( String.class ) ); + final List dtos = entityManager.createQuery( query ).getResultList(); - final List dtos = entityManager.createQuery( query ).getResultList(); - - assertThat( dtos.size(), is( 1 ) ); - assertThat( dtos.get( 0 ).active, is( false ) ); - assertThat( dtos.get( 0 ).name, nullValue() ); - assertThat( dtos.get( 0 ).surname, nullValue() ); - - entityManager.getTransaction().commit(); - } - catch (Exception e) { - if ( entityManager.getTransaction().isActive() ) { - entityManager.getTransaction().rollback(); - } - throw e; - } - finally { - entityManager.close(); - } + assertThat( dtos.size(), is( 1 ) ); + assertThat( dtos.get( 0 ).active, is( false ) ); + assertThat( dtos.get( 0 ).name, nullValue() ); + assertThat( dtos.get( 0 ).surname, nullValue() ); + } + ); } @Test @TestForIssue(jiraKey = "HHH-10861") - public void testNullLiteralFirst() throws Exception { - final EntityManager entityManager = getOrCreateEntityManager(); - try { - entityManager.getTransaction().begin(); + public void testNullLiteralFirst(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); + final CriteriaQuery query = criteriaBuilder.createQuery( MyEntityDTO.class ); + final Root entity = query.from( MyEntity.class ); - final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); - final CriteriaQuery query = criteriaBuilder.createQuery( MyEntityDTO.class ); - final Root entity = query.from( MyEntity.class ); + query.multiselect( criteriaBuilder.nullLiteral( String.class ), entity.get( "surname" ) ); - query.multiselect( criteriaBuilder.nullLiteral( String.class ), entity.get( "surname" ) ); + final List dtos = entityManager.createQuery( query ).getResultList(); - final List dtos = entityManager.createQuery( query ).getResultList(); - - assertThat( dtos.size(), is( 1 ) ); - assertThat( dtos.get( 0 ).name, nullValue() ); - assertThat( dtos.get( 0 ).surname, is( "A" ) ); - assertThat( dtos.get( 0 ).active, is( false ) ); - - entityManager.getTransaction().commit(); - } - catch (Exception e) { - if ( entityManager.getTransaction().isActive() ) { - entityManager.getTransaction().rollback(); - } - throw e; - } - finally { - entityManager.close(); - } + assertThat( dtos.size(), is( 1 ) ); + assertThat( dtos.get( 0 ).name, nullValue() ); + assertThat( dtos.get( 0 ).surname, is( "A" ) ); + assertThat( dtos.get( 0 ).active, is( false ) ); + } + ); } @Test @TestForIssue(jiraKey = "HHH-10729") - public void testStringLiteral() throws Exception { - final EntityManager entityManager = getOrCreateEntityManager(); - try { - entityManager.getTransaction().begin(); + public void testStringLiteral(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); + final CriteriaQuery query = criteriaBuilder.createQuery( MyEntityDTO.class ); + final Root entity = query.from( MyEntity.class ); - final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); - final CriteriaQuery query = criteriaBuilder.createQuery( MyEntityDTO.class ); - final Root entity = query.from( MyEntity.class ); + query.multiselect( criteriaBuilder.literal( "Leo" ), entity.get( "surname" ) ); - query.multiselect( criteriaBuilder.literal( "Leo" ), entity.get( "surname" ) ); + final List dtos = entityManager.createQuery( query ).getResultList(); - final List dtos = entityManager.createQuery( query ).getResultList(); - - assertThat( dtos.size(), is( 1 ) ); - assertThat( dtos.get( 0 ).name, is( "Leo" ) ); - assertThat( dtos.get( 0 ).surname, is( "A" ) ); - assertThat( dtos.get( 0 ).active, is( false ) ); - - entityManager.getTransaction().commit(); - } - catch (Exception e) { - if ( entityManager.getTransaction().isActive() ) { - entityManager.getTransaction().rollback(); - } - throw e; - } - finally { - entityManager.close(); - } + assertThat( dtos.size(), is( 1 ) ); + assertThat( dtos.get( 0 ).name, is( "Leo" ) ); + assertThat( dtos.get( 0 ).surname, is( "A" ) ); + assertThat( dtos.get( 0 ).active, is( false ) ); + } + ); } @Test @TestForIssue(jiraKey = "HHH-9021") - @SkipForDialect( value= { - Oracle8iDialect.class, - DB2Dialect.class, - SQLServerDialect.class, - SybaseDialect.class, - AbstractHANADialect.class - }) - public void testStringLiteral2() { - final EntityManager entityManager = getOrCreateEntityManager(); - try { - final CriteriaBuilder builder = entityManager.getCriteriaBuilder(); - final CriteriaQuery criteriaQuery = builder.createQuery( Tuple.class ); - criteriaQuery.from( MyEntity.class ); - criteriaQuery.multiselect( builder.equal( builder.literal( 1 ), builder.literal( 2 ) ) ); + @SkipForDialect( dialectClass = OracleDialect.class) + @SkipForDialect( dialectClass = DB2Dialect.class) + @SkipForDialect( dialectClass = SQLServerDialect.class) + @SkipForDialect( dialectClass = SybaseDialect.class) + @SkipForDialect( dialectClass = AbstractHANADialect.class) + public void testStringLiteral2(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + final CriteriaBuilder builder = entityManager.getCriteriaBuilder(); + final CriteriaQuery criteriaQuery = builder.createQuery( Tuple.class ); + criteriaQuery.from( MyEntity.class ); + criteriaQuery.multiselect( builder.equal( builder.literal( 1 ), builder.literal( 2 ) ) ); - final TypedQuery typedQuery = entityManager.createQuery( criteriaQuery ); + final TypedQuery typedQuery = entityManager.createQuery( criteriaQuery ); - final List results = typedQuery.getResultList(); + final List results = typedQuery.getResultList(); - assertThat( results.size(), is( 1 ) ); - assertThat( results.get( 0 ).getElements().size(), is( 1 ) ); - assertThat( results.get( 0 ).get( 0 ), is( false ) ); - } - finally { - entityManager.close(); - } + assertThat( results.size(), is( 1 ) ); + assertThat( results.get( 0 ).getElements().size(), is( 1 ) ); + assertThat( results.get( 0 ).get( 0 ), is( false ) ); + } + ); } @Entity(name = "MyEntity") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/paths/AbstractPathImplTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/paths/AbstractPathImplTest.java index 99ebeb6b21..b3d002c5aa 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/paths/AbstractPathImplTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/paths/AbstractPathImplTest.java @@ -12,25 +12,25 @@ import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Path; import jakarta.persistence.criteria.Root; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - import org.hibernate.jpa.test.metamodel.AbstractMetamodelSpecificTest; import org.hibernate.jpa.test.metamodel.Order; -import org.hibernate.jpa.test.metamodel.Order_; import org.hibernate.jpa.test.metamodel.Thing; import org.hibernate.jpa.test.metamodel.ThingWithQuantity; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import org.hibernate.testing.orm.junit.ExpectedException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Michael Rudolf * @author James Gilbertson */ public class AbstractPathImplTest extends AbstractMetamodelSpecificTest { - @Before + @BeforeEach public void prepareTestData() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); @@ -55,7 +55,7 @@ public class AbstractPathImplTest extends AbstractMetamodelSpecificTest { em.close(); } - @After + @AfterEach public void cleanupTestData() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); @@ -66,7 +66,8 @@ public class AbstractPathImplTest extends AbstractMetamodelSpecificTest { em.close(); } - @Test(expected = IllegalArgumentException.class) + @ExpectedException(value = IllegalArgumentException.class) + @Test public void testGetNonExistingAttributeViaName() { EntityManager em = getOrCreateEntityManager(); try { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/paths/FetchAndJoinTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/paths/FetchAndJoinTest.java index 582dd28218..4d9302d0d7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/paths/FetchAndJoinTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/paths/FetchAndJoinTest.java @@ -31,14 +31,14 @@ import jakarta.persistence.criteria.Join; import jakarta.persistence.criteria.JoinType; import jakarta.persistence.criteria.Root; -import org.junit.Test; - import org.hibernate.jpa.test.metamodel.AbstractMetamodelSpecificTest; import org.hibernate.jpa.test.metamodel.Entity1; import org.hibernate.jpa.test.metamodel.Entity1_; import org.hibernate.jpa.test.metamodel.Entity2; import org.hibernate.jpa.test.metamodel.Entity2_; +import org.junit.jupiter.api.Test; + /** * @author Gail Badner */ diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/paths/PluralAttributeExpressionsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/paths/PluralAttributeExpressionsTest.java index 7fc3070296..d424873a53 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/paths/PluralAttributeExpressionsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/paths/PluralAttributeExpressionsTest.java @@ -9,10 +9,7 @@ package org.hibernate.orm.test.jpa.criteria.paths; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import java.util.Map; -import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; -import jakarta.persistence.criteria.Expression; import jakarta.persistence.criteria.Root; import org.hibernate.jpa.test.metamodel.AbstractMetamodelSpecificTest; @@ -27,9 +24,9 @@ import org.hibernate.jpa.test.metamodel.Translation; import org.hibernate.query.criteria.HibernateCriteriaBuilder; import org.hibernate.query.criteria.JpaExpression; -import org.hibernate.testing.FailureExpected; import org.hibernate.testing.TestForIssue; -import org.junit.Test; + +import org.junit.jupiter.api.Test; import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/subquery/CorrelatedSubqueryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/subquery/CorrelatedSubqueryTest.java index 58a6519993..91022e43fb 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/subquery/CorrelatedSubqueryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/subquery/CorrelatedSubqueryTest.java @@ -6,19 +6,16 @@ */ package org.hibernate.orm.test.jpa.criteria.subquery; -import static org.junit.Assert.assertEquals; - import java.util.Set; import jakarta.persistence.EntityManager; -import jakarta.persistence.criteria.CollectionJoin; import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Join; import jakarta.persistence.criteria.Root; import jakarta.persistence.criteria.Subquery; -import org.hibernate.dialect.SybaseASE15Dialect; +import org.hibernate.dialect.SybaseASEDialect; import org.hibernate.jpa.test.metamodel.AbstractMetamodelSpecificTest; import org.hibernate.jpa.test.metamodel.Customer; import org.hibernate.jpa.test.metamodel.Customer_; @@ -26,9 +23,13 @@ import org.hibernate.jpa.test.metamodel.LineItem; import org.hibernate.jpa.test.metamodel.LineItem_; import org.hibernate.jpa.test.metamodel.Order; import org.hibernate.jpa.test.metamodel.Order_; -import org.hibernate.testing.SkipForDialect; import org.hibernate.testing.TestForIssue; -import org.junit.Test; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.SkipForDialect; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Steve Ebersole @@ -78,7 +79,8 @@ public class CorrelatedSubqueryTest extends AbstractMetamodelSpecificTest { } @Test - @SkipForDialect(value=SybaseASE15Dialect.class, jiraKey="HHH-3032") + @JiraKey("HHH-3032") + @SkipForDialect(dialectClass= SybaseASEDialect.class, version = 1500) public void testCorrelationExplicitSelectionCorrelation() { CriteriaBuilder builder = entityManagerFactory().getCriteriaBuilder(); EntityManager em = getOrCreateEntityManager(); @@ -114,7 +116,7 @@ public class CorrelatedSubqueryTest extends AbstractMetamodelSpecificTest { Subquery customerSubquery = criteria.subquery( Customer.class ); Root orderRootCorrelation = customerSubquery.correlate( orderRoot ); Join orderCustomerJoin = orderRootCorrelation.join( "customer" ); - customerSubquery.where( builder.like( orderCustomerJoin.get( "name" ), "%Caruso" ) ); + customerSubquery.where( builder.like( orderCustomerJoin.get( "name" ), "%Caruso" ) ); criteria.where( builder.exists( customerSubquery ) ); em.createQuery( criteria ).getResultList(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/subquery/UncorrelatedSubqueryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/subquery/UncorrelatedSubqueryTest.java index 58b83371a8..f41894d295 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/subquery/UncorrelatedSubqueryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/subquery/UncorrelatedSubqueryTest.java @@ -19,10 +19,10 @@ import org.hibernate.jpa.test.metamodel.Customer_; import org.hibernate.jpa.test.metamodel.Order; import org.hibernate.jpa.test.metamodel.Order_; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Steve Ebersole diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/tuple/TupleCriteriaTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/tuple/TupleCriteriaTest.java index aed7d6b1c6..704c1c5732 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/tuple/TupleCriteriaTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/tuple/TupleCriteriaTest.java @@ -16,16 +16,16 @@ import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Path; import jakarta.persistence.criteria.Root; -import org.junit.Test; - import org.hibernate.jpa.test.metamodel.AbstractMetamodelSpecificTest; import org.hibernate.jpa.test.metamodel.Customer; import org.hibernate.jpa.test.metamodel.Customer_; -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 org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Emmanuel Bernard @@ -89,7 +89,7 @@ public class TupleCriteriaTest extends AbstractMetamodelSpecificTest { List results = em.createQuery( criteria ).getResultList(); assertEquals( 1, results.size() ); Object resultElement = results.get( 0 ); - assertTrue( "Check result 'row' as Tuple", Tuple.class.isInstance( resultElement ) ); + assertTrue( Tuple.class.isInstance( resultElement ), "Check result 'row' as Tuple" ); Tuple resultElementTuple = (Tuple) resultElement; Object[] tupleArray = resultElementTuple.toArray(); assertEquals( 2, tupleArray.length ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/lock/LockExceptionTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/lock/LockExceptionTests.java index 4f18d38c4f..e3b493118f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/lock/LockExceptionTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/lock/LockExceptionTests.java @@ -14,23 +14,18 @@ import jakarta.persistence.PessimisticLockException; import org.hibernate.LockOptions; import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Configuration; -import org.hibernate.dialect.MariaDBDialect; import org.hibernate.dialect.SQLServerDialect; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.hibernate.testing.DialectChecks; import org.hibernate.testing.RequiresDialectFeature; -import org.hibernate.testing.SkipForDialect; -import org.hibernate.testing.SkipForDialects; import org.hibernate.testing.TestForIssue; import org.hibernate.testing.jdbc.SQLServerSnapshotIsolationConnectionProvider; import org.hibernate.testing.transaction.TransactionUtil2; -import org.hibernate.testing.util.ExceptionUtil; import org.hibernate.test.jpa.AbstractJPATest; import org.hibernate.test.jpa.Item; import org.junit.Test; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** @@ -78,7 +73,7 @@ public class LockExceptionTests extends AbstractJPATest { Item.class, item.getId(), LockModeType.PESSIMISTIC_WRITE, - Collections.singletonMap( AvailableSettings.JPA_LOCK_TIMEOUT, LockOptions.NO_WAIT ) + Collections.singletonMap( AvailableSettings.JAKARTA_LOCK_TIMEOUT, LockOptions.NO_WAIT ) ); fail( "Expecting a failure" ); } @@ -122,7 +117,7 @@ public class LockExceptionTests extends AbstractJPATest { secondSession.refresh( item2, LockModeType.PESSIMISTIC_WRITE, - Collections.singletonMap( AvailableSettings.JPA_LOCK_TIMEOUT, LockOptions.NO_WAIT ) + Collections.singletonMap( AvailableSettings.JAKARTA_LOCK_TIMEOUT, LockOptions.NO_WAIT ) ); fail( "Expecting a failure" ); } @@ -163,7 +158,7 @@ public class LockExceptionTests extends AbstractJPATest { secondSession.lock( item2, LockModeType.PESSIMISTIC_WRITE, - Collections.singletonMap( AvailableSettings.JPA_LOCK_TIMEOUT, LockOptions.NO_WAIT ) + Collections.singletonMap( AvailableSettings.JAKARTA_LOCK_TIMEOUT, LockOptions.NO_WAIT ) ); fail( "Expecting a failure" ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/NamedQueryCommentTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/NamedQueryCommentTest.java index d477b79da7..772c04df71 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/NamedQueryCommentTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/NamedQueryCommentTest.java @@ -7,7 +7,6 @@ package org.hibernate.orm.test.jpa.query; import java.util.List; -import java.util.Map; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; @@ -21,202 +20,222 @@ import org.hibernate.annotations.NamedQuery; import org.hibernate.cfg.AvailableSettings; import org.hibernate.dialect.H2Dialect; import org.hibernate.dialect.MySQLDialect; -import org.hibernate.dialect.Oracle8iDialect; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.dialect.OracleDialect; +import org.hibernate.resource.jdbc.spi.StatementInspector; -import org.hibernate.testing.RequiresDialect; import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.jdbc.SQLStatementInterceptor; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.jdbc.SQLStatementInspector; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.Setting; +import org.hibernate.testing.orm.junit.SettingProvider; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ +@Jpa( + annotatedClasses = { NamedQueryCommentTest.Game.class }, + integrationSettings = { + @Setting( name = AvailableSettings.USE_SQL_COMMENTS, value = "true" ) + }, + settingProviders = { + @SettingProvider( + settingName = AvailableSettings.STATEMENT_INSPECTOR, + provider = NamedQueryCommentTest.StatementInspectorSettingProvider.class + ) + } +) @TestForIssue(jiraKey = "HHH-11640") -public class NamedQueryCommentTest extends BaseEntityManagerFunctionalTestCase { +public class NamedQueryCommentTest { - private SQLStatementInterceptor sqlStatementInterceptor; - - @Override - protected void addConfigOptions(Map options) { - sqlStatementInterceptor = new SQLStatementInterceptor( options ); - options.put( AvailableSettings.USE_SQL_COMMENTS, Boolean.TRUE.toString() ); - } + private static SQLStatementInspector statementInspector; private static final String[] GAME_TITLES = { "Halo", "Grand Theft Auto", "NetHack" }; - @Override - public Class[] getAnnotatedClasses() { - return new Class[] { Game.class }; + @BeforeAll + public void setUp(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + for ( String title : GAME_TITLES ) { + Game game = new Game( title ); + entityManager.persist( game ); + } + } + ); } - @Before - public void setUp() { - doInJPA( this::entityManagerFactory, entityManager -> { - for ( String title : GAME_TITLES ) { - Game game = new Game( title ); - entityManager.persist( game ); - } - } ); - } - - @After - public void tearDown() { - doInJPA( this::entityManagerFactory, entityManager -> { - entityManager.createQuery( "delete from Game" ).executeUpdate(); - } ); + @AfterAll + public void tearDown(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> entityManager.createQuery( "delete from Game" ).executeUpdate() + ); } @Test - public void testSelectNamedQueryWithSqlComment() { - doInJPA( this::entityManagerFactory, entityManager -> { - sqlStatementInterceptor.clear(); + public void testSelectNamedQueryWithSqlComment(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + statementInspector.clear(); - TypedQuery query = entityManager.createNamedQuery( "SelectNamedQuery", Game.class ); - query.setParameter( "title", GAME_TITLES[0] ); - List list = query.getResultList(); - assertEquals( 1, list.size() ); + TypedQuery query = entityManager.createNamedQuery( "SelectNamedQuery", Game.class ); + query.setParameter( "title", GAME_TITLES[0] ); + List list = query.getResultList(); + assertEquals( 1, list.size() ); - sqlStatementInterceptor.assertExecutedCount(1); + statementInspector.assertExecutedCount(1); - sqlStatementInterceptor.assertExecuted( - "/* COMMENT_SELECT_INDEX_game_title */ select g1_0.id,g1_0.title from game g1_0 where g1_0.title=?" - ); - } ); + statementInspector.assertExecuted( + "/* COMMENT_SELECT_INDEX_game_title */ select g1_0.id,g1_0.title from game g1_0 where g1_0.title=?" + ); + } + ); } @Test - public void testSelectNamedNativeQueryWithSqlComment() { - doInJPA( this::entityManagerFactory, entityManager -> { - sqlStatementInterceptor.clear(); + public void testSelectNamedNativeQueryWithSqlComment(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + statementInspector.clear(); - TypedQuery query = entityManager.createNamedQuery( "SelectNamedNativeQuery", Game.class ); - query.setParameter( "title", GAME_TITLES[0] ); - List list = query.getResultList(); - assertEquals( 1, list.size() ); + TypedQuery query = entityManager.createNamedQuery( "SelectNamedNativeQuery", Game.class ); + query.setParameter( "title", GAME_TITLES[0] ); + List list = query.getResultList(); + assertEquals( 1, list.size() ); - sqlStatementInterceptor.assertExecutedCount(1); + statementInspector.assertExecutedCount(1); - sqlStatementInterceptor.assertExecuted( - "/* + INDEX (game idx_game_title) */ select * from game g where title = ?" + statementInspector.assertExecuted( + "/* + INDEX (game idx_game_title) */ select * from game g where title = ?" - ); - } ); + ); + } + ); } @Test - public void testUpdateNamedQueryWithSqlComment() { - doInJPA( this::entityManagerFactory, entityManager -> { - sqlStatementInterceptor.clear(); + public void testUpdateNamedQueryWithSqlComment(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + statementInspector.clear(); - Query query = entityManager.createNamedQuery( "UpdateNamedNativeQuery" ); - query.setParameter( "title", GAME_TITLES[0] ); - query.setParameter( "id", 1L ); - int updateCount = query.executeUpdate(); - assertEquals( 1, updateCount ); + Query query = entityManager.createNamedQuery( "UpdateNamedNativeQuery" ); + query.setParameter( "title", GAME_TITLES[0] ); + query.setParameter( "id", 1L ); + int updateCount = query.executeUpdate(); + assertEquals( 1, updateCount ); - sqlStatementInterceptor.assertExecutedCount(1); + statementInspector.assertExecutedCount(1); - sqlStatementInterceptor.assertExecuted( - "/* COMMENT_INDEX_game_title */ update game set title = ? where id = ?" - ); - } ); + statementInspector.assertExecuted( + "/* COMMENT_INDEX_game_title */ update game set title = ? where id = ?" + ); + } + ); } @Test - public void testUpdateNamedNativeQueryWithSqlComment() { - doInJPA( this::entityManagerFactory, entityManager -> { - sqlStatementInterceptor.clear(); + public void testUpdateNamedNativeQueryWithSqlComment(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + statementInspector.clear(); - Query query = entityManager.createNamedQuery( "UpdateNamedNativeQuery" ); - query.setParameter( "title", GAME_TITLES[0] ); - query.setParameter( "id", 1L ); - int updateCount = query.executeUpdate(); - assertEquals( 1, updateCount ); + Query query = entityManager.createNamedQuery( "UpdateNamedNativeQuery" ); + query.setParameter( "title", GAME_TITLES[0] ); + query.setParameter( "id", 1L ); + int updateCount = query.executeUpdate(); + assertEquals( 1, updateCount ); - sqlStatementInterceptor.assertExecutedCount(1); + statementInspector.assertExecutedCount(1); - sqlStatementInterceptor.assertExecuted( - "/* COMMENT_INDEX_game_title */ update game set title = ? where id = ?" - ); - } ); + statementInspector.assertExecuted( + "/* COMMENT_INDEX_game_title */ update game set title = ? where id = ?" + ); + } + ); } @Test - @RequiresDialect(Oracle8iDialect.class) - public void testUpdateNamedNativeQueryWithQueryHintUsingOracle() { - doInJPA( this::entityManagerFactory, entityManager -> { - sqlStatementInterceptor.clear(); + @RequiresDialect(value = OracleDialect.class) + public void testUpdateNamedNativeQueryWithQueryHintUsingOracle(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + statementInspector.clear(); - Query query = entityManager.createNamedQuery( "UpdateNamedNativeQuery" ); - query.setParameter( "title", GAME_TITLES[0] ); - query.setParameter( "id", 1L ); - query.unwrap( org.hibernate.query.Query.class ).addQueryHint( "INDEX (game idx_game_id)" ); - int updateCount = query.executeUpdate(); - assertEquals( 1, updateCount ); + Query query = entityManager.createNamedQuery( "UpdateNamedNativeQuery" ); + query.setParameter( "title", GAME_TITLES[0] ); + query.setParameter( "id", 1L ); + query.unwrap( org.hibernate.query.Query.class ).addQueryHint( "INDEX (game idx_game_id)" ); + int updateCount = query.executeUpdate(); + assertEquals( 1, updateCount ); - sqlStatementInterceptor.assertExecutedCount(1); + statementInspector.assertExecutedCount(1); - sqlStatementInterceptor.assertExecuted( - "/* COMMENT_INDEX_game_title */ update /*+ INDEX (game idx_game_id) */ game set title = ? where id = ?" - ); - } ); + statementInspector.assertExecuted( + "/* COMMENT_INDEX_game_title */ update /*+ INDEX (game idx_game_id) */ game set title = ? where id = ?" + ); + } + ); } @Test @RequiresDialect(H2Dialect.class) - public void testUpdateNamedNativeQueryWithQueryHintUsingIndex() { - doInJPA( this::entityManagerFactory, entityManager -> { - sqlStatementInterceptor.clear(); + public void testUpdateNamedNativeQueryWithQueryHintUsingIndex(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + statementInspector.clear(); - Query query = entityManager.createNamedQuery( "UpdateNamedNativeQuery" ); - query.setParameter( "title", GAME_TITLES[0] ); - query.setParameter( "id", 1L ); - query.unwrap( org.hibernate.query.Query.class ).addQueryHint( "INDEX (game idx_game_id)" ); - int updateCount = query.executeUpdate(); - assertEquals( 1, updateCount ); + Query query = entityManager.createNamedQuery( "UpdateNamedNativeQuery" ); + query.setParameter( "title", GAME_TITLES[0] ); + query.setParameter( "id", 1L ); + query.unwrap( org.hibernate.query.Query.class ).addQueryHint( "INDEX (game idx_game_id)" ); + int updateCount = query.executeUpdate(); + assertEquals( 1, updateCount ); - sqlStatementInterceptor.assertExecutedCount(1); + statementInspector.assertExecutedCount(1); - sqlStatementInterceptor.assertExecuted( - "/* COMMENT_INDEX_game_title */ update game set title = ? where id = ?" - ); - } ); + statementInspector.assertExecuted( + "/* COMMENT_INDEX_game_title */ update game set title = ? where id = ?" + ); + } + ); } @Test @RequiresDialect(MySQLDialect.class) @RequiresDialect(H2Dialect.class) - public void testSelectNamedNativeQueryWithQueryHintUsingIndex() { - doInJPA( this::entityManagerFactory, entityManager -> { - sqlStatementInterceptor.clear(); + public void testSelectNamedNativeQueryWithQueryHintUsingIndex(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + statementInspector.clear(); - Query query = entityManager.createNamedQuery( "SelectNamedQuery" ); - query.setParameter( "title", GAME_TITLES[0] ); - query.unwrap( org.hibernate.query.Query.class ).addQueryHint( "idx_game_id" ); - List list = query.getResultList(); - assertEquals( 1, list.size() ); + Query query = entityManager.createNamedQuery( "SelectNamedQuery" ); + query.setParameter( "title", GAME_TITLES[0] ); + query.unwrap( org.hibernate.query.Query.class ).addQueryHint( "idx_game_id" ); + List list = query.getResultList(); + assertEquals( 1, list.size() ); - sqlStatementInterceptor.assertExecutedCount(1); + statementInspector.assertExecutedCount(1); - sqlStatementInterceptor.assertExecuted( - "/* COMMENT_SELECT_INDEX_game_title */ select g1_0.id,g1_0.title from game g1_0 use index (idx_game_id) where g1_0.title=?" - ); - } ); + statementInspector.assertExecuted( + "/* COMMENT_SELECT_INDEX_game_title */ select g1_0.id,g1_0.title from game g1_0 use index (idx_game_id) where g1_0.title=?" + ); + } + ); } @Entity(name = "Game") @Table( name = "game", indexes = { - @Index(name = "idx_game_title", columnList = "title"), - @Index(name = "idx_game_id", columnList = "id") + @Index(name = "idx_game_title", columnList = "title"), + @Index(name = "idx_game_id", columnList = "id") } ) @NamedQuery( @@ -230,10 +249,10 @@ public class NamedQueryCommentTest extends BaseEntityManagerFunctionalTestCase { comment = "INDEX (game idx_game_title) " ) @NamedNativeQuery( - name = "SelectNamedNativeQuery", - query = "select * from game g where title = :title", - comment = "+ INDEX (game idx_game_title) ", - resultClass = Game.class + name = "SelectNamedNativeQuery", + query = "select * from game g where title = :title", + comment = "+ INDEX (game idx_game_title) ", + resultClass = Game.class ) @NamedNativeQuery( name = "UpdateNamedNativeQuery", @@ -272,4 +291,12 @@ public class NamedQueryCommentTest extends BaseEntityManagerFunctionalTestCase { this.title = title; } } + + public static class StatementInspectorSettingProvider implements SettingProvider.Provider { + @Override + public StatementInspector getSetting() { + statementInspector = new SQLStatementInspector(); + return statementInspector; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/NativeQueryOrdinalParametersTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/NativeQueryOrdinalParametersTest.java index 19f5f5ce52..960f84a0de 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/NativeQueryOrdinalParametersTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/NativeQueryOrdinalParametersTest.java @@ -18,106 +18,114 @@ import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; import org.hibernate.Session; -import org.hibernate.dialect.PostgreSQL82Dialect; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.dialect.CockroachDialect; +import org.hibernate.dialect.PostgreSQLDialect; import org.hibernate.query.NativeQuery; - -import org.hibernate.testing.RequiresDialect; import org.hibernate.testing.TestForIssue; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.RequiresDialect; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Andrea Boriero */ -public class NativeQueryOrdinalParametersTest extends BaseEntityManagerFunctionalTestCase { +@Jpa( + annotatedClasses = { + NativeQueryOrdinalParametersTest.Game.class, + NativeQueryOrdinalParametersTest.Node.class + } +) +public class NativeQueryOrdinalParametersTest { private static final String[] GAME_TITLES = { "Super Mario Brothers", "Mario Kart", "F-Zero" }; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Game.class, - Node.class - }; + @BeforeAll + public void setUp(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + for ( String title : GAME_TITLES ) { + Game game = new Game( title ); + entityManager.persist( game ); + } + } + ); } - @Before - public void setUp() { - doInJPA( this::entityManagerFactory, entityManager -> { - for ( String title : GAME_TITLES ) { - Game game = new Game( title ); - entityManager.persist( game ); - } - } ); - } - - @After - public void tearDown() { - doInJPA( this::entityManagerFactory, entityManager -> { - entityManager.createQuery( "delete from Game" ).executeUpdate(); - } ); + @AfterAll + public void tearDown(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> entityManager.createQuery( "delete from Game" ).executeUpdate() + ); } @Test @TestForIssue(jiraKey = "HHH-10885") - public void testNativeQueryIndexedOrdinalParameter() { - doInJPA( this::entityManagerFactory, entityManager -> { - Query query = entityManager.createNativeQuery( "SELECT * FROM GAME g WHERE title = ?1" ); - query.setParameter( 1, "Super Mario Brothers" ); - List list = query.getResultList(); - assertEquals( 1, list.size() ); - } ); + public void testNativeQueryIndexedOrdinalParameter(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + Query query = entityManager.createNativeQuery( "SELECT * FROM GAME g WHERE title = ?1" ); + query.setParameter( 1, "Super Mario Brothers" ); + List list = query.getResultList(); + assertEquals( 1, list.size() ); + } + ); } @Test @TestForIssue(jiraKey = "HHH-10885") - public void testNativeQueryOrdinalParameter() { - doInJPA( this::entityManagerFactory, entityManager -> { - Query query = entityManager.createNativeQuery( "SELECT * FROM GAME g WHERE title = ?" ); - query.setParameter( 1, "Super Mario Brothers" ); - List list = query.getResultList(); - assertEquals( 1, list.size() ); - } ); + public void testNativeQueryOrdinalParameter(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + Query query = entityManager.createNativeQuery( "SELECT * FROM GAME g WHERE title = ?" ); + query.setParameter( 1, "Super Mario Brothers" ); + List list = query.getResultList(); + assertEquals( 1, list.size() ); + } + ); } @Test @TestForIssue(jiraKey = "HHH-11121") - public void testConflictWithSessionNativeQuery() { + public void testConflictWithSessionNativeQuery(EntityManagerFactoryScope scope) { final String sqlString = "SELECT * FROM GAME g WHERE title = ?"; - doInJPA( this::entityManagerFactory, entityManager -> { - NativeQuery sqlQuery = entityManager.unwrap( Session.class ).createNativeQuery( sqlString ); - sqlQuery.setParameter( 1, "Super Mario Brothers" ).setCacheable( true ); + scope.inTransaction( + entityManager -> { + NativeQuery sqlQuery = entityManager.unwrap( Session.class ).createNativeQuery( sqlString ); + sqlQuery.setParameter( 1, "Super Mario Brothers" ).setCacheable( true ); - List results = sqlQuery.list(); - assertEquals( 1, results.size() ); + List results = sqlQuery.list(); + assertEquals( 1, results.size() ); - NativeQuery query = (NativeQuery) entityManager.createNativeQuery( sqlString ); - query.setParameter( 1, "Super Mario Brothers" ); - List list = query.list(); - assertEquals( 1, list.size() ); + NativeQuery query = (NativeQuery) entityManager.createNativeQuery( sqlString ); + query.setParameter( 1, "Super Mario Brothers" ); + List list = query.list(); + assertEquals( 1, list.size() ); - sqlQuery = entityManager.unwrap( Session.class ).createNativeQuery( sqlString ); - sqlQuery.setParameter( 1, "Super Mario Brothers" ).setCacheable( true ); + sqlQuery = entityManager.unwrap( Session.class ).createNativeQuery( sqlString ); + sqlQuery.setParameter( 1, "Super Mario Brothers" ).setCacheable( true ); - results = sqlQuery.list(); - assertEquals( 1, results.size() ); + results = sqlQuery.list(); + assertEquals( 1, results.size() ); - query.setParameter( 1, "Super Mario Brothers" ); - } ); + query.setParameter( 1, "Super Mario Brothers" ); + } + ); } @Test @TestForIssue(jiraKey = "HHH-12532") // Add RequiresDialect be Cockroach version 201 - @RequiresDialect({ PostgreSQL82Dialect.class}) - public void testCteNativeQueryOrdinalParameter() { + @RequiresDialect( value = PostgreSQLDialect.class, version = 820 ) + @RequiresDialect( value = CockroachDialect.class, version = 2010 ) + public void testCteNativeQueryOrdinalParameter(EntityManagerFactoryScope scope) { Node root1 = new Node(); root1.setCode( "ABC" ); @@ -133,43 +141,47 @@ public class NativeQueryOrdinalParametersTest extends BaseEntityManagerFunctiona Node node211 = new Node(); node211.setParent( node21 ); - doInJPA( this::entityManagerFactory, entityManager -> { - entityManager.persist( root1 ); - entityManager.persist( root2 ); + scope.inTransaction( + entityManager -> { + entityManager.persist( root1 ); + entityManager.persist( root2 ); - entityManager.persist( node11 ); - entityManager.persist( node21 ); + entityManager.persist( node11 ); + entityManager.persist( node21 ); - entityManager.persist( node211 ); - } ); + entityManager.persist( node211 ); + } + ); - doInJPA( this::entityManagerFactory, entityManager -> { - Query cte = entityManager.createNativeQuery( - "WITH RECURSIVE CTE(id, parent_id) AS ( " + - " SELECT id, parent_id " + - " FROM Node " + - " WHERE code like ?1 and parent_id is null" + - " UNION ALL " + - " SELECT child.id, child.parent_id " + - " FROM Node child " + - " JOIN CTE cte " + - " ON cte.id = child.parent_id " + - ") SELECT DISTINCT id as integer " + - " FROM CTE cte" ); + scope.inTransaction( + entityManager -> { + Query cte = entityManager.createNativeQuery( + "WITH RECURSIVE CTE(id, parent_id) AS ( " + + " SELECT id, parent_id " + + " FROM Node " + + " WHERE code like ?1 and parent_id is null" + + " UNION ALL " + + " SELECT child.id, child.parent_id " + + " FROM Node child " + + " JOIN CTE cte " + + " ON cte.id = child.parent_id " + + ") SELECT DISTINCT id as integer " + + " FROM CTE cte" ); - List root1Ids = cte.setParameter( 1, "AB%" ).getResultList(); - assertEquals( 2, root1Ids.size() ); - assertTrue( root1Ids.contains( root1.getId() ) ); - assertTrue( root1Ids.contains( node11.getId() ) ); + List root1Ids = cte.setParameter( 1, "AB%" ).getResultList(); + assertEquals( 2, root1Ids.size() ); + assertTrue( root1Ids.contains( root1.getId() ) ); + assertTrue( root1Ids.contains( node11.getId() ) ); - List root2Ids = cte.setParameter( 1, "DE%" ).getResultList(); - assertEquals( 3, root2Ids.size() ); - assertTrue( root2Ids.contains( root2.getId() ) ); - assertTrue( root2Ids.contains( node21.getId() ) ); - assertTrue( root2Ids.contains( node211.getId() ) ); - } ); + List root2Ids = cte.setParameter( 1, "DE%" ).getResultList(); + assertEquals( 3, root2Ids.size() ); + assertTrue( root2Ids.contains( root2.getId() ) ); + assertTrue( root2Ids.contains( node21.getId() ) ); + assertTrue( root2Ids.contains( node211.getId() ) ); + } + ); } @Entity(name = "Game") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/OracleConstructorResultNativeQueryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/OracleConstructorResultNativeQueryTest.java index 25c2cf6dd7..d0057a1e32 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/OracleConstructorResultNativeQueryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/OracleConstructorResultNativeQueryTest.java @@ -12,7 +12,6 @@ import jakarta.persistence.Column; import jakarta.persistence.ColumnResult; import jakarta.persistence.ConstructorResult; import jakarta.persistence.Entity; -import jakarta.persistence.EntityManager; import jakarta.persistence.Id; import jakarta.persistence.NamedNativeQueries; import jakarta.persistence.NamedNativeQuery; @@ -21,14 +20,17 @@ import jakarta.persistence.SqlResultSetMappings; import jakarta.persistence.Temporal; import jakarta.persistence.TemporalType; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import org.hibernate.dialect.Oracle8iDialect; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.dialect.OracleDialect; -import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; -import static org.junit.Assert.assertEquals; +import org.hibernate.testing.TestForIssue; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.RequiresDialect; + +import static org.hibernate.testing.orm.junit.ExtraAssertions.assertTyping; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Oracle needs to have the column result type specified for the Integer ID because the @@ -42,8 +44,79 @@ import static org.junit.Assert.assertEquals; * * @author Steve Ebersole */ -@RequiresDialect(value = Oracle8iDialect.class, jiraKey = "HHH-10323") -public class OracleConstructorResultNativeQueryTest extends BaseEntityManagerFunctionalTestCase { +@Jpa( + annotatedClasses = { + OracleConstructorResultNativeQueryTest.Person.class + } +) +@TestForIssue(jiraKey = "HHH-10323") +@RequiresDialect(value = OracleDialect.class) +public class OracleConstructorResultNativeQueryTest { + + @Test + public void testConstructorResultNativeQuery(EntityManagerFactoryScope scope) { + scope.inTransaction( + em -> em.persist( new Person( 1, "John", new Date() ) ) + ); + + scope.inTransaction( + em -> { + List results = em.createNativeQuery( + "select p.id, p.p_name from person p order by p.p_name", + "person-id-and-name" + ).getResultList(); + assertEquals( 1, results.size() ); + assertTyping( Person.class, results.get( 0 ) ); + } + ); + + scope.inTransaction( + em -> em.createQuery( "delete from Person" ).executeUpdate() + ); + } + + + @Test + public void testMultipleConstructorResultNativeQuery(EntityManagerFactoryScope scope) { + scope.inTransaction( + em -> em.persist( new Person( 1, "John", new Date() ) ) + ); + + scope.inTransaction( + em -> { + List results = em.createNamedQuery( "person-id-and-name2" ).getResultList(); + assertEquals( 1, results.size() ); + Object[] result = assertTyping( Object[].class, results.get( 0 ) ); + assertEquals( 2, result.length ); + assertTyping( Person.class, result[0] ); + assertTyping( Person.class, result[1] ); + } + ); + + scope.inTransaction( + em -> em.createQuery( "delete from Person" ).executeUpdate() + ); + } + + @Test + public void testConstructorResultNativeQuerySpecifyingType(EntityManagerFactoryScope scope) { + scope.inTransaction( + em -> em.persist( new Person( 1, "John", "85" ) ) + ); + + scope.inTransaction( + em -> { + List results = em.createNamedQuery( "person-id-and-name-and-weight" ).getResultList(); + assertEquals( 1, results.size() ); + assertTyping( Person.class, results.get( 0 ) ); + } + ); + + scope.inTransaction( + em -> em.createQuery( "delete from Person" ).executeUpdate() + ); + } + @Entity( name = "Person" ) @SqlResultSetMappings( value = { @@ -95,21 +168,21 @@ public class OracleConstructorResultNativeQueryTest extends BaseEntityManagerFun ) @NamedNativeQueries( value = { - @NamedNativeQuery( - name = "person-id-and-name", - query = "select p.id, p.p_name from person p order by p.p_name", - resultSetMapping = "person-id-and-name" - ), - @NamedNativeQuery( - name = "person-id-and-name2", - query = "select p.id, p.p_name, p.id as id2, p.p_name as p_name2 from person p order by p.p_name", - resultSetMapping = "person-id-and-name2" - ), - @NamedNativeQuery( - name = "person-id-and-name-and-weight", - query = "select p.id, p.p_name, p.p_weight from person p order by p.p_name", - resultSetMapping = "person-id-and-name-and-weight" - ) + @NamedNativeQuery( + name = "person-id-and-name", + query = "select p.id, p.p_name from person p order by p.p_name", + resultSetMapping = "person-id-and-name" + ), + @NamedNativeQuery( + name = "person-id-and-name2", + query = "select p.id, p.p_name, p.id as id2, p.p_name as p_name2 from person p order by p.p_name", + resultSetMapping = "person-id-and-name2" + ), + @NamedNativeQuery( + name = "person-id-and-name-and-weight", + query = "select p.id, p.p_name, p.p_weight from person p order by p.p_name", + resultSetMapping = "person-id-and-name-and-weight" + ) } ) public static class Person { @@ -142,86 +215,4 @@ public class OracleConstructorResultNativeQueryTest extends BaseEntityManagerFun this.weight = Integer.valueOf(weight); } } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Person.class }; - } - - - @Test - public void testConstructorResultNativeQuery() { - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); - em.persist( new Person( 1, "John", new Date() ) ); - em.getTransaction().commit(); - em.close(); - - em = getOrCreateEntityManager(); - em.getTransaction().begin(); - List results = em.createNativeQuery( - "select p.id, p.p_name from person p order by p.p_name", - "person-id-and-name" - ).getResultList(); - assertEquals( 1, results.size() ); - assertTyping( Person.class, results.get( 0 ) ); - em.getTransaction().commit(); - em.close(); - - em = getOrCreateEntityManager(); - em.getTransaction().begin(); - em.createQuery( "delete from Person" ).executeUpdate(); - em.getTransaction().commit(); - em.close(); - } - - - @Test - public void testMultipleConstructorResultNativeQuery() { - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); - em.persist( new Person( 1, "John", new Date() ) ); - em.getTransaction().commit(); - em.close(); - - em = getOrCreateEntityManager(); - em.getTransaction().begin(); - List results = em.createNamedQuery( "person-id-and-name2" ).getResultList(); - assertEquals( 1, results.size() ); - Object[] result = assertTyping( Object[].class, results.get( 0 ) ); - assertEquals( 2, result.length ); - assertTyping( Person.class, result[0] ); - assertTyping( Person.class, result[1] ); - em.getTransaction().commit(); - em.close(); - - em = getOrCreateEntityManager(); - em.getTransaction().begin(); - em.createQuery( "delete from Person" ).executeUpdate(); - em.getTransaction().commit(); - em.close(); - } - - @Test - public void testConstructorResultNativeQuerySpecifyingType() { - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); - em.persist( new Person( 1, "John", "85" ) ); - em.getTransaction().commit(); - em.close(); - - em = getOrCreateEntityManager(); - em.getTransaction().begin(); - List results = em.createNamedQuery( "person-id-and-name-and-weight" ).getResultList(); - assertEquals( 1, results.size() ); - assertTyping( Person.class, results.get( 0 ) ); - em.getTransaction().commit(); - em.close(); - - em = getOrCreateEntityManager(); - em.getTransaction().begin(); - em.createQuery( "delete from Person" ).executeUpdate(); - em.getTransaction().commit(); - em.close(); - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/loading/multiLoad/MultiLoadSubSelectCollectionDialectWithLimitTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/loading/multiLoad/MultiLoadSubSelectCollectionDialectWithLimitTest.java index 17b1d7b333..0b598791c5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/loading/multiLoad/MultiLoadSubSelectCollectionDialectWithLimitTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/loading/multiLoad/MultiLoadSubSelectCollectionDialectWithLimitTest.java @@ -48,7 +48,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; public class MultiLoadSubSelectCollectionDialectWithLimitTest { - public static class TestSettingProvider implements SettingProvider.Provider { + public static class TestSettingProvider implements SettingProvider.Provider { @Override public String getSetting() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/locking/HANAOptimisticLockingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/locking/HANAOptimisticLockingTest.java index 4814a8cc91..a6a64c9b53 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/locking/HANAOptimisticLockingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/locking/HANAOptimisticLockingTest.java @@ -6,79 +6,85 @@ */ package org.hibernate.orm.test.locking; +import org.hibernate.dialect.HANAColumnStoreDialect; +import org.hibernate.dialect.HANARowStoreDialect; + import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.LockModeType; import jakarta.persistence.Version; -import org.hibernate.dialect.HANAColumnStoreDialect; -import org.hibernate.dialect.HANARowStoreDialect; -import org.junit.Test; - -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.RequiresDialects; import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.RequiresDialects; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertNotNull; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Chris Cranford */ +@DomainModel( + annotatedClasses = { + HANAOptimisticLockingTest.SomeEntity.class + } +) +@SessionFactory @TestForIssue(jiraKey = "HHH-11656") -@RequiresDialects( { @RequiresDialect(HANAColumnStoreDialect.class), @RequiresDialect(HANARowStoreDialect.class) }) -public class HANAOptimisticLockingTest extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { SomeEntity.class }; +@RequiresDialects({ @RequiresDialect(HANAColumnStoreDialect.class), @RequiresDialect(HANARowStoreDialect.class) }) +public class HANAOptimisticLockingTest { + + @Test + public void testOptimisticLock(SessionFactoryScope scope) { + testWithSpecifiedLockMode( scope, LockModeType.OPTIMISTIC ); } @Test - public void testOptimisticLock() throws Exception { - testWithSpecifiedLockMode( LockModeType.OPTIMISTIC ); + public void testOptimisticLockForceIncrement(SessionFactoryScope scope) { + testWithSpecifiedLockMode( scope, LockModeType.OPTIMISTIC_FORCE_INCREMENT ); } - @Test - public void testOptimisticLockForceIncrement() throws Exception { - testWithSpecifiedLockMode( LockModeType.OPTIMISTIC_FORCE_INCREMENT ); - } - - private void testWithSpecifiedLockMode(LockModeType lockModeType) { + private void testWithSpecifiedLockMode(SessionFactoryScope scope, LockModeType lockModeType) { // makes sure we have an entity to actually query - final Object id = doInHibernate( this::sessionFactory, session -> { - return session.save( new SomeEntity() ); - } ); + Object id = scope.fromTransaction( + session -> session.save( new SomeEntity() ) + ); // tests that both the query execution doesn't throw a SQL syntax (which is the main bug) and that // the query returns an expected entity object. - doInHibernate( this::sessionFactory, session -> { - /** - * This generates the wrong SQL query for HANA. - * Using optimistic lock and string query cause a bug. - * - * Generated SQL query for HANA is as follows: - * - * SELECT - * someentity0_.id as id1_0_, - * someentity0_.version as version2_0_ - * FROM SomeEntity someentity0_ - * WHERE someentity0_ = 1 of someentity0_.id - * - * The exception thrown by HANA is: - * com.sap.db.jdbc.exceptions.JDBCDriverException: SAP DBTech JDBC: [257]: - * sql syntax error: incorrect syntax near "of": line 1 - * - */ - SomeEntity entity = session - .createQuery( "SELECT e FROM SomeEntity e WHERE e.id = :id", SomeEntity.class ) - .setParameter( "id", id ) - .setLockMode( lockModeType ) - .uniqueResult(); + scope.inTransaction( + session -> { + /** + * This generates the wrong SQL query for HANA. + * Using optimistic lock and string query cause a bug. + * + * Generated SQL query for HANA is as follows: + * + * SELECT + * someentity0_.id as id1_0_, + * someentity0_.version as version2_0_ + * FROM SomeEntity someentity0_ + * WHERE someentity0_ = 1 of someentity0_.id + * + * The exception thrown by HANA is: + * com.sap.db.jdbc.exceptions.JDBCDriverException: SAP DBTech JDBC: [257]: + * sql syntax error: incorrect syntax near "of": line 1 + * + */ + SomeEntity entity = session + .createQuery( "SELECT e FROM SomeEntity e WHERE e.id = :id", SomeEntity.class ) + .setParameter( "id", id ) + .setLockMode( lockModeType ) + .uniqueResult(); - assertNotNull( entity ); - } ); + assertNotNull( entity ); + } + ); } @Entity(name = "SomeEntity") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/locking/LockModeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/locking/LockModeTest.java index 7f7287fe2b..c8f05406ab 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/locking/LockModeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/locking/LockModeTest.java @@ -16,30 +16,32 @@ import jakarta.persistence.criteria.CriteriaQuery; import org.hibernate.LockMode; import org.hibernate.LockOptions; import org.hibernate.Session; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; import org.hibernate.dialect.CockroachDialect; import org.hibernate.dialect.SQLServerDialect; -import org.hibernate.dialect.SybaseASE15Dialect; +import org.hibernate.dialect.SybaseASEDialect; import org.hibernate.dialect.SybaseDialect; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.query.criteria.HibernateCriteriaBuilder; import org.hibernate.query.criteria.JpaCriteriaQuery; import org.hibernate.query.sqm.tree.domain.SqmPath; -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; -import org.hibernate.testing.SkipForDialect; +import org.hibernate.testing.orm.junit.BaseSessionFactoryFunctionalTest; +import org.hibernate.testing.orm.junit.DialectFeatureChecks; +import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.SkipForDialect; import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import org.hibernate.testing.transaction.TransactionUtil; import org.hibernate.testing.util.ExceptionUtil; -import org.junit.Test; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; /** * Make sure that directly specifying lock modes, even though deprecated, continues to work until removed. @@ -47,9 +49,9 @@ import static org.junit.Assert.fail; * @author Steve Ebersole */ @TestForIssue( jiraKey = "HHH-5275") -@SkipForDialect(value=SybaseASE15Dialect.class, strictMatching=true, - comment = "skip this test on Sybase ASE 15.5, but run it on 15.7, see HHH-6820") -public class LockModeTest extends BaseCoreFunctionalTestCase { +@SkipForDialect(dialectClass = SybaseASEDialect.class, version = 1500, + reason = "skip this test on Sybase ASE 15.5, but run it on 15.7, see HHH-6820") +public class LockModeTest extends BaseSessionFactoryFunctionalTest { private Long id; @@ -61,22 +63,24 @@ public class LockModeTest extends BaseCoreFunctionalTestCase { } @Override - protected void configure(Configuration configuration) { + protected void applySettings(StandardServiceRegistryBuilder ssrBuilder) { + super.applySettings( ssrBuilder ); // We can't use a shared connection provider if we use TransactionUtil.setJdbcTimeout because that is set on the connection level - configuration.getProperties().remove( AvailableSettings.CONNECTION_PROVIDER ); + ssrBuilder.getSettings().remove( AvailableSettings.CONNECTION_PROVIDER ); } - @Override + @BeforeEach public void prepareTest() throws Exception { doInHibernate( this::sessionFactory, session -> { id = (Long) session.save( new A( "it" ) ); } ); } + @Override protected boolean isCleanupTestDataRequired(){return true;} @Test - @RequiresDialectFeature( value = DialectChecks.SupportsLockTimeouts.class ) + @RequiresDialectFeature( feature = DialectFeatureChecks.SupportsLockTimeouts.class ) @SuppressWarnings( {"deprecation"}) public void testLoading() { // open a session, begin a transaction and lock row @@ -92,7 +96,7 @@ public class LockModeTest extends BaseCoreFunctionalTestCase { } @Test - @RequiresDialectFeature( value = DialectChecks.SupportsLockTimeouts.class ) + @RequiresDialectFeature( feature = DialectFeatureChecks.SupportsLockTimeouts.class ) public void testCriteria() { // open a session, begin a transaction and lock row doInHibernate( this::sessionFactory, session -> { @@ -114,7 +118,7 @@ public class LockModeTest extends BaseCoreFunctionalTestCase { } @Test - @RequiresDialectFeature( value = DialectChecks.SupportsLockTimeouts.class ) + @RequiresDialectFeature( feature = DialectFeatureChecks.SupportsLockTimeouts.class ) public void testCriteriaAliasSpecific() { // open a session, begin a transaction and lock row doInHibernate( this::sessionFactory, session -> { @@ -138,7 +142,7 @@ public class LockModeTest extends BaseCoreFunctionalTestCase { } @Test - @RequiresDialectFeature( value = DialectChecks.SupportsLockTimeouts.class ) + @RequiresDialectFeature( feature = DialectFeatureChecks.SupportsLockTimeouts.class ) public void testQuery() { // open a session, begin a transaction and lock row doInHibernate( this::sessionFactory, session -> { @@ -226,7 +230,7 @@ public class LockModeTest extends BaseCoreFunctionalTestCase { @Test @TestForIssue(jiraKey = "HHH-12257") - @SkipForDialect( value = CockroachDialect.class ) + @SkipForDialect( dialectClass = CockroachDialect.class ) public void testRefreshWithExplicitHigherLevelLockMode() { doInHibernate( this::sessionFactory, session -> { A a = session.get( A.class, id ); @@ -271,8 +275,7 @@ public class LockModeTest extends BaseCoreFunctionalTestCase { // To be able to cater to the second type, we run this block in a separate thread to be able to "time it out" try { - executeSync( () -> { - doInHibernate( this::sessionFactory, _session -> { + executeSync( () -> doInHibernate( this::sessionFactory, _session -> { TransactionUtil.setJdbcTimeout( _session ); try { // We used to load with write lock here to deal with databases that block (wait indefinitely) @@ -300,11 +303,11 @@ public class LockModeTest extends BaseCoreFunctionalTestCase { fail( "Unexpected error type testing pessimistic locking : " + e.getClass().getName() ); } } - } ); - } ); + } ) + ); } catch (Exception e) { - //MariaDB throws a time out nd closes the underlying connection + //MariaDB throws a timeout nd closes the underlying connection if( !ExceptionUtil.isConnectionClose(e)) { fail("Unknown exception thrown: " + e.getMessage()); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/ComponentOwner.hbm.xml b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/ComponentOwner.hbm.xml index a0924f96fd..a617848c0f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/ComponentOwner.hbm.xml +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/ComponentOwner.hbm.xml @@ -9,7 +9,7 @@ "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> - + diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/PartiallyGeneratedComponentTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/PartiallyGeneratedComponentTest.java index cce7de7f14..4814288e1f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/PartiallyGeneratedComponentTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/PartiallyGeneratedComponentTest.java @@ -6,58 +6,60 @@ */ package org.hibernate.orm.test.mapping.generated; -import org.junit.Test; +import org.hibernate.dialect.OracleDialect; -import org.hibernate.Session; -import org.hibernate.dialect.Oracle9iDialect; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * {@inheritDoc} * * @author Steve Ebersole */ -@RequiresDialect( Oracle9iDialect.class ) -public class PartiallyGeneratedComponentTest extends BaseCoreFunctionalTestCase { - public String[] getMappings() { - return new String[] { "generated/ComponentOwner.hbm.xml" }; - } +@DomainModel( + xmlMappings = "org/hibernate/orm/test/generated/mapping/ComponentOwner.hbm.xml" +) +@SessionFactory +@RequiresDialect( value = OracleDialect.class, version = 900 ) +public class PartiallyGeneratedComponentTest { @Test - public void testPartialComponentGeneration() { + public void testPartialComponentGeneration(SessionFactoryScope scope) { ComponentOwner owner = new ComponentOwner( "initial" ); - Session s = openSession(); - s.beginTransaction(); - s.save( owner ); - s.getTransaction().commit(); - s.close(); + scope.inTransaction( + s -> s.save( owner ) + ); - assertNotNull( "expecting insert value generation", owner.getComponent() ); + assertNotNull( owner.getComponent(), "expecting insert value generation" ); int previousValue = owner.getComponent().getGenerated(); - assertFalse( "expecting insert value generation", 0 == previousValue ); + assertFalse( 0 == previousValue, "expecting insert value generation" ); - s = openSession(); - s.beginTransaction(); - owner = ( ComponentOwner ) s.get( ComponentOwner.class, owner.getId() ); - assertEquals( "expecting insert value generation", previousValue, owner.getComponent().getGenerated() ); - owner.setName( "subsequent" ); - s.getTransaction().commit(); - s.close(); + ComponentOwner owner2 = scope.fromTransaction( + s -> { + ComponentOwner _owner = s.get( ComponentOwner.class, owner.getId() ); + assertEquals( previousValue, _owner.getComponent().getGenerated(), "expecting insert value generation" ); + _owner.setName( "subsequent" ); + return _owner; + } + ); - assertNotNull( owner.getComponent() ); - previousValue = owner.getComponent().getGenerated(); + assertNotNull( owner2.getComponent() ); + int previousValue2 = owner2.getComponent().getGenerated(); - s = openSession(); - s.beginTransaction(); - owner = ( ComponentOwner ) s.get( ComponentOwner.class, owner.getId() ); - assertEquals( "expecting update value generation", previousValue, owner.getComponent().getGenerated() ); - s.delete( owner ); - s.getTransaction().commit(); - s.close(); + scope.inTransaction( + s -> { + ComponentOwner _owner = s.get( ComponentOwner.class, owner.getId() ); + assertEquals( previousValue2, _owner.getComponent().getGenerated(), "expecting update value generation" ); + s.delete( _owner ); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/OracleStoredProcedureTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/OracleStoredProcedureTest.java index da25144c0b..c091cee962 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/OracleStoredProcedureTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/OracleStoredProcedureTest.java @@ -65,7 +65,7 @@ import static org.junit.jupiter.api.Assertions.fail; Vote.class } ) -@RequiresDialect(value = OracleDialect.class, version = 800) +@RequiresDialect(value = OracleDialect.class) public class OracleStoredProcedureTest { @NamedStoredProcedureQueries({ diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/MaxInExpressionParameterPaddingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/MaxInExpressionParameterPaddingTest.java index 1060228083..f7999525a8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/MaxInExpressionParameterPaddingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/MaxInExpressionParameterPaddingTest.java @@ -14,11 +14,11 @@ import org.hibernate.dialect.H2Dialect; import org.hibernate.testing.TestForIssue; import org.hibernate.testing.jdbc.SQLStatementInspector; -import org.hibernate.testing.orm.jpa.NonStringValueSettingProvider; import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; import org.hibernate.testing.orm.junit.Jpa; import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.orm.junit.Setting; +import org.hibernate.testing.orm.junit.SettingProvider; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -38,19 +38,19 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @Setting(name = AvailableSettings.USE_SQL_COMMENTS, value = "true"), @Setting(name = AvailableSettings.IN_CLAUSE_PARAMETER_PADDING, value = "true"), }, - nonStringValueSettingProviders = MaxInExpressionParameterPaddingTest.DialectProvider.class, + settingProviders ={ + @SettingProvider( + settingName = AvailableSettings.DIALECT, + provider = MaxInExpressionParameterPaddingTest.DialectProvider.class + ), + }, statementInspectorClass = SQLStatementInspector.class ) public class MaxInExpressionParameterPaddingTest { - public static class DialectProvider extends NonStringValueSettingProvider { + public static class DialectProvider implements SettingProvider.Provider { @Override - public String getKey() { - return AvailableSettings.DIALECT; - } - - @Override - public Object getValue() { + public String getSetting() { return MaxInExpressionParameterPaddingTest.MaxCountInExpressionH2Dialect.class.getName(); } } @@ -75,11 +75,11 @@ public class MaxInExpressionParameterPaddingTest { final SQLStatementInspector statementInspector = (SQLStatementInspector) scope.getStatementInspector(); statementInspector.clear(); - scope.inTransaction( entityManager -> { + scope.inTransaction( entityManager -> entityManager.createQuery( "select p from Person p where p.id in :ids" ) .setParameter( "ids", IntStream.range( 0, MAX_COUNT ).boxed().collect( Collectors.toList() ) ) - .getResultList(); - } ); + .getResultList() + ); StringBuilder expectedInClause = new StringBuilder(); expectedInClause.append( "in(?" ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/CountExpressionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/CountExpressionTest.java index 1c543dcd9d..f5597beac6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/CountExpressionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/CountExpressionTest.java @@ -17,11 +17,6 @@ import jakarta.persistence.Id; import jakarta.persistence.MapKeyColumn; import jakarta.persistence.OneToMany; -import org.hibernate.dialect.DerbyDialect; -import org.hibernate.dialect.H2Dialect; - -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.SkipForDialect; import org.hibernate.testing.TestForIssue; import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import org.junit.Test; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/jdbc/autocommit/AbstractSkipAutoCommitTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/jdbc/autocommit/AbstractSkipAutoCommitTest.java index 14f1971eea..c1a186e262 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/jdbc/autocommit/AbstractSkipAutoCommitTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/jdbc/autocommit/AbstractSkipAutoCommitTest.java @@ -11,29 +11,32 @@ import java.sql.SQLException; import java.util.List; import java.util.Map; import jakarta.persistence.Entity; +import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.Id; import javax.sql.DataSource; import org.hibernate.cfg.AvailableSettings; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.dialect.Dialect; -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.DialectContext; +import org.hibernate.testing.orm.junit.DialectFeatureChecks; +import org.hibernate.testing.orm.junit.RequiresDialectFeature; import org.hibernate.testing.orm.jdbc.PreparedStatementSpyConnectionProvider; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryBasedFunctionalTest; -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; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; /** * @author Vlad Mihalcea */ -@RequiresDialectFeature(DialectChecks.SupportsJdbcDriverProxying.class) -public abstract class AbstractSkipAutoCommitTest extends BaseEntityManagerFunctionalTestCase { +@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsJdbcDriverProxying.class) +public abstract class AbstractSkipAutoCommitTest extends EntityManagerFactoryBasedFunctionalTest { private PreparedStatementSpyConnectionProvider connectionProvider = new PreparedStatementSpyConnectionProvider( false, true ) { @@ -59,8 +62,13 @@ public abstract class AbstractSkipAutoCommitTest extends BaseEntityManagerFuncti protected abstract DataSource dataSource(); @Override - public void releaseResources() { - super.releaseResources(); + protected boolean isCleanupTestDataRequired() { + return true; + } + + @Override + protected void cleanupTestData() { + super.cleanupTestData(); connectionProvider.stop(); } @@ -71,25 +79,37 @@ public abstract class AbstractSkipAutoCommitTest extends BaseEntityManagerFuncti }; } + protected Dialect getDialect() { + return DialectContext.getDialect(); + } + @Test public void test() { - connectionProvider.clear(); - doInJPA( this::entityManagerFactory, entityManager -> { - City city = new City(); - city.setId( 1L ); - city.setName( "Cluj-Napoca" ); - entityManager.persist( city ); + inTransaction( + entityManager -> { + // Moved inside the transaction because the new base class defers the EMF creation w/ respect to the + // former base class, so the connections used in that process can now only be cleared after the EMF is built + // Could also override entityManagerFactoryBuilt(EntityManagerFactory factory) and do it there. + connectionProvider.clear(); - assertTrue( connectionProvider.getAcquiredConnections().isEmpty() ); - assertTrue( connectionProvider.getReleasedConnections().isEmpty() ); - } ); + City city = new City(); + city.setId( 1L ); + city.setName( "Cluj-Napoca" ); + entityManager.persist( city ); + + assertTrue( connectionProvider.getAcquiredConnections().isEmpty() ); + assertTrue( connectionProvider.getReleasedConnections().isEmpty() ); + } + ); verifyConnections(); connectionProvider.clear(); - doInJPA( this::entityManagerFactory, entityManager -> { - City city = entityManager.find( City.class, 1L ); - assertEquals( "Cluj-Napoca", city.getName() ); - } ); + inTransaction( + entityManager -> { + City city = entityManager.find( City.class, 1L ); + assertEquals( "Cluj-Napoca", city.getName() ); + } + ); verifyConnections(); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/jdbc/autocommit/H2SkipAutoCommitTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/jdbc/autocommit/H2SkipAutoCommitTest.java index 2815fed2f9..7b6d686f6b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/jdbc/autocommit/H2SkipAutoCommitTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/jdbc/autocommit/H2SkipAutoCommitTest.java @@ -12,7 +12,7 @@ import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Environment; import org.hibernate.dialect.H2Dialect; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.util.ReflectionUtil; /** diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/jdbc/autocommit/MySQLSkipAutoCommitTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/jdbc/autocommit/MySQLSkipAutoCommitTest.java index 526fdb5c3f..7e2d8d2140 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/jdbc/autocommit/MySQLSkipAutoCommitTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/jdbc/autocommit/MySQLSkipAutoCommitTest.java @@ -13,7 +13,7 @@ import org.hibernate.cfg.Environment; import org.hibernate.dialect.MariaDBDialect; import org.hibernate.dialect.MySQLDialect; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.util.ReflectionUtil; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/jdbc/autocommit/OracleSkipAutoCommitTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/jdbc/autocommit/OracleSkipAutoCommitTest.java index 58577f45e8..b106901a69 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/jdbc/autocommit/OracleSkipAutoCommitTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/jdbc/autocommit/OracleSkipAutoCommitTest.java @@ -10,15 +10,15 @@ import javax.sql.DataSource; import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Environment; -import org.hibernate.dialect.Oracle8iDialect; +import org.hibernate.dialect.OracleDialect; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.util.ReflectionUtil; /** * @author Vlad Mihalcea */ -@RequiresDialect(Oracle8iDialect.class) +@RequiresDialect(value = OracleDialect.class) public class OracleSkipAutoCommitTest extends AbstractSkipAutoCommitTest { @Override diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/jdbc/autocommit/PostgreSQLSkipAutoCommitTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/jdbc/autocommit/PostgreSQLSkipAutoCommitTest.java index 356cf50624..fb8c4eff51 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/jdbc/autocommit/PostgreSQLSkipAutoCommitTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/jdbc/autocommit/PostgreSQLSkipAutoCommitTest.java @@ -12,7 +12,7 @@ import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Environment; import org.hibernate.dialect.PostgreSQLDialect; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.util.ReflectionUtil; /** diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/jdbc/autocommit/SQLServerSkipAutoCommitTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/jdbc/autocommit/SQLServerSkipAutoCommitTest.java index f138ac3441..d0dd5fa24b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/jdbc/autocommit/SQLServerSkipAutoCommitTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/jdbc/autocommit/SQLServerSkipAutoCommitTest.java @@ -12,7 +12,7 @@ import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Environment; import org.hibernate.dialect.SQLServerDialect; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.util.ReflectionUtil; /** diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/AbstractAlterTableQuoteSchemaTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/AbstractAlterTableQuoteSchemaTest.java index 9f0ed7d66e..5571ea0433 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/AbstractAlterTableQuoteSchemaTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/AbstractAlterTableQuoteSchemaTest.java @@ -7,21 +7,16 @@ package org.hibernate.orm.test.schemaupdate; import org.hibernate.dialect.Dialect; -import org.hibernate.dialect.H2Dialect; -import org.hibernate.dialect.MySQLDialect; -import org.hibernate.dialect.PostgreSQL82Dialect; -import org.hibernate.dialect.SQLServerDialect; -import org.hibernate.testing.RequiresDialect; import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.hibernate.testing.orm.junit.BaseSessionFactoryFunctionalTest; import org.hibernate.testing.orm.junit.DialectContext; /** * @author Vlad Mihalcea */ @TestForIssue(jiraKey = "HHH-12939") -public abstract class AbstractAlterTableQuoteSchemaTest extends BaseCoreFunctionalTestCase { +public abstract class AbstractAlterTableQuoteSchemaTest extends BaseSessionFactoryFunctionalTest { private final Dialect dialect = DialectContext.getDialect(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/AlterTableQuoteDefaultSchemaTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/AlterTableQuoteDefaultSchemaTest.java index 36e4344fba..1ee3228368 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/AlterTableQuoteDefaultSchemaTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/AlterTableQuoteDefaultSchemaTest.java @@ -23,67 +23,71 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.cfg.AvailableSettings; import org.hibernate.dialect.H2Dialect; -import org.hibernate.dialect.PostgreSQL82Dialect; -import org.hibernate.dialect.SQLServer2012Dialect; -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; +import org.hibernate.dialect.PostgreSQLDialect; +import org.hibernate.dialect.SQLServerDialect; import org.hibernate.tool.hbm2ddl.SchemaUpdate; import org.hibernate.tool.schema.TargetType; -import org.hibernate.testing.RequiresDialect; import org.hibernate.testing.TestForIssue; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DialectFeatureChecks; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Guillaume Smet */ @TestForIssue(jiraKey = "HHH-12939") -@RequiresDialect(value = { - H2Dialect.class, - PostgreSQL82Dialect.class, - SQLServer2012Dialect.class, -}) -@RequiresDialectFeature(DialectChecks.SupportSchemaCreation.class) +@RequiresDialect(value = H2Dialect.class) +@RequiresDialect(value = PostgreSQLDialect.class, version = 820) +@RequiresDialect(value = SQLServerDialect.class, version = 11) +@RequiresDialectFeature(feature = DialectFeatureChecks.SupportSchemaCreation.class) public class AlterTableQuoteDefaultSchemaTest extends AbstractAlterTableQuoteSchemaTest { - @Override - protected void afterSessionFactoryBuilt() { + @BeforeEach + protected void init() { try { - doInHibernate( this::sessionFactory, session -> { - session.createNativeQuery( "DROP TABLE " + quote( "default-schema", "my_entity" ) ) - .executeUpdate(); - } ); + inTransaction( + session -> session.createNativeQuery( "DROP TABLE " + quote( "default-schema", "my_entity" ) ) + .executeUpdate() + ); } - catch (Exception ignore) { + catch (Exception e) { } try { - doInHibernate( this::sessionFactory, session -> { - session.createNativeQuery( "DROP SCHEMA " + quote( "default-schema" ) ) - .executeUpdate(); - } ); + inTransaction( + session -> session.createNativeQuery( "DROP SCHEMA " + quote( "default-schema" ) ) + .executeUpdate() + ); } - catch (Exception ignore) { + catch (Exception e) { + } + try { + inTransaction( + session -> session.createNativeQuery( "CREATE SCHEMA " + quote( "default-schema" ) ) + .executeUpdate() + ); + } + catch (Exception e) { } - doInHibernate( this::sessionFactory, session -> { - session.createNativeQuery( "CREATE SCHEMA " + quote( "default-schema" ) ) - .executeUpdate(); - } ); } - @Override - protected void cleanupTest() { + @AfterEach + protected void tearDown() { try { - doInHibernate( this::sessionFactory, session -> { - session.createNativeQuery( "DROP SCHEMA " + quote( "default-schema" ) ) - .executeUpdate(); - } ); + inTransaction( + session -> session.createNativeQuery( "DROP SCHEMA " + quote( "default-schema" ) ) + .executeUpdate() + ); } - catch (Exception ignore) { + catch (Exception e) { } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/AlterTableQuoteSpecifiedSchemaTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/AlterTableQuoteSpecifiedSchemaTest.java index db4423f265..5cd677c56e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/AlterTableQuoteSpecifiedSchemaTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/AlterTableQuoteSpecifiedSchemaTest.java @@ -22,69 +22,71 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.cfg.AvailableSettings; import org.hibernate.dialect.H2Dialect; -import org.hibernate.dialect.PostgreSQL82Dialect; -import org.hibernate.dialect.SQLServer2012Dialect; -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; +import org.hibernate.dialect.PostgreSQLDialect; +import org.hibernate.dialect.SQLServerDialect; import org.hibernate.tool.hbm2ddl.SchemaUpdate; import org.hibernate.tool.schema.TargetType; -import org.hibernate.testing.RequiresDialect; import org.hibernate.testing.TestForIssue; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DialectFeatureChecks; +import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Guillaume Smet */ @TestForIssue(jiraKey = "HHH-12939") -@RequiresDialect(value = { - H2Dialect.class, - PostgreSQL82Dialect.class, - SQLServer2012Dialect.class, -}) -@RequiresDialectFeature(DialectChecks.SupportSchemaCreation.class) +@RequiresDialect(value = H2Dialect.class) +@RequiresDialect(value = PostgreSQLDialect.class, version = 820) +@RequiresDialect(value = SQLServerDialect.class, version = 11) +@RequiresDialectFeature(feature = DialectFeatureChecks.SupportSchemaCreation.class) public class AlterTableQuoteSpecifiedSchemaTest extends AbstractAlterTableQuoteSchemaTest { - @Override - protected void afterSessionFactoryBuilt() { - + @BeforeEach + protected void init() { try { - doInHibernate( this::sessionFactory, session -> { - session.createNativeQuery( "DROP TABLE " + quote( "my-schema", "my_entity" ) ) - .executeUpdate(); - } ); + inTransaction( + session -> session.createNativeQuery( "DROP TABLE " + quote( "my-schema", "my_entity" ) ) + .executeUpdate() + ); } - catch (Exception ignore) { + catch (Exception e) { } try { - doInHibernate( this::sessionFactory, session -> { - session.createNativeQuery( "DROP SCHEMA " + quote( "my-schema" ) ) - .executeUpdate(); - } ); + inTransaction( + session -> session.createNativeQuery( "DROP SCHEMA " + quote( "my-schema" ) ) + .executeUpdate() + ); } - catch (Exception ignore) { + catch (Exception e) { + } + try { + inTransaction( + session -> session.createNativeQuery( "CREATE SCHEMA " + quote( "my-schema" ) ) + .executeUpdate() + ); + } + catch (Exception e) { } - doInHibernate( this::sessionFactory, session -> { - session.createNativeQuery( "CREATE SCHEMA " + quote( "my-schema" ) ) - .executeUpdate(); - } ); } - @Override - protected void cleanupTest() { + @AfterEach + protected void cleanupTestData() { try { - doInHibernate( this::sessionFactory, session -> { - session.createNativeQuery( "DROP SCHEMA " + quote( "my-schema" ) ) - .executeUpdate(); - } ); - + inTransaction( + session -> session.createNativeQuery( "DROP SCHEMA " + quote( "my-schema" ) ) + .executeUpdate() + ); } - catch (Exception ignore) { + catch (Exception e) { } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateSchemaNameTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateSchemaNameTest.java index 8fb3886716..df3a31bd01 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateSchemaNameTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateSchemaNameTest.java @@ -18,17 +18,14 @@ import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Configuration; -import org.hibernate.dialect.Dialect; -import org.hibernate.dialect.MySQL5Dialect; -import org.hibernate.engine.spi.Mapping; -import org.hibernate.tool.schema.extract.spi.TableInformation; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.dialect.MySQLDialect; -import org.hibernate.testing.RequiresDialect; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseUnitTestCase; /** * Test to illustrate that the org.hibernate.mapping.Table#sqlAlterStrings method @@ -37,12 +34,12 @@ import org.hibernate.testing.junit4.BaseUnitTestCase; * * @author Chris Cranford */ -@RequiresDialect(MySQL5Dialect.class) +@RequiresDialect( value = MySQLDialect.class, version = 500 ) @TestForIssue(jiraKey = "HHH-11455") -public class SchemaUpdateSchemaNameTest extends BaseUnitTestCase { +public class SchemaUpdateSchemaNameTest { - @Before - public void buildInitialSchema() throws Exception { + @BeforeAll + public static void buildInitialSchema() { // Builds the initial table in the schema. StandardServiceRegistry ssr = null; try { @@ -59,8 +56,8 @@ public class SchemaUpdateSchemaNameTest extends BaseUnitTestCase { } } - @After - public void cleanup() { + @AfterAll + public static void cleanup() { // Drops the table after the sql alter test. StandardServiceRegistry ssr = null; try { @@ -75,7 +72,7 @@ public class SchemaUpdateSchemaNameTest extends BaseUnitTestCase { .applySettings( cfg.getProperties() ) .build(); - try (SessionFactory sf = cfg.buildSessionFactory();) { + try (SessionFactory sf = cfg.buildSessionFactory()) { Session session = sf.openSession(); try { session.getTransaction().begin(); @@ -99,7 +96,7 @@ public class SchemaUpdateSchemaNameTest extends BaseUnitTestCase { } @Test - public void testSqlAlterWithTableSchemaName() throws Exception { + public void testSqlAlterWithTableSchemaName() { StandardServiceRegistry ssr = null; try { final Configuration cfg = buildConfiguration( SimpleNext.class ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemavalidation/SynonymValidationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemavalidation/SynonymValidationTest.java index 6a0eccdda5..02c07ed78e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemavalidation/SynonymValidationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemavalidation/SynonymValidationTest.java @@ -16,17 +16,17 @@ import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.AvailableSettings; -import org.hibernate.dialect.Oracle9iDialect; +import org.hibernate.dialect.OracleDialect; import org.hibernate.tool.hbm2ddl.SchemaValidator; import org.hibernate.tool.schema.JdbcMetadaAccessStrategy; -import org.hibernate.testing.RequiresDialect; import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.hibernate.testing.transaction.TransactionUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.BaseSessionFactoryFunctionalTest; +import org.hibernate.testing.orm.junit.RequiresDialect; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * Allows the BaseCoreFunctionalTestCase to create the schema using TestEntity. The test method validates against an @@ -37,8 +37,9 @@ import org.junit.Test; * * @author Brett Meyer */ -@RequiresDialect(Oracle9iDialect.class) -public class SynonymValidationTest extends BaseNonConfigCoreFunctionalTestCase { +@RequiresDialect(value = OracleDialect.class, version = 900) +public class SynonymValidationTest extends BaseSessionFactoryFunctionalTest { + private StandardServiceRegistry ssr; @Override @@ -46,18 +47,18 @@ public class SynonymValidationTest extends BaseNonConfigCoreFunctionalTestCase { return new Class[] {TestEntity.class}; } - @Before + @BeforeAll public void setUp() { - TransactionUtil.doInHibernate( this::sessionFactory, session -> { - session.createNativeQuery( "CREATE SYNONYM test_synonym FOR test_entity" ).executeUpdate(); - } ); + inTransaction( + session -> session.createNativeQuery( "CREATE SYNONYM test_synonym FOR test_entity" ).executeUpdate() + ); } - @After + @AfterAll public void tearDown() { - TransactionUtil.doInHibernate( this::sessionFactory, session -> { - session.createNativeQuery( "DROP SYNONYM test_synonym FORCE" ).executeUpdate(); - }); + inTransaction( + session -> session.createNativeQuery( "DROP SYNONYM test_synonym FORCE" ).executeUpdate() + ); } @Test diff --git a/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/BaseSessionFactoryFunctionalTest.java b/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/BaseSessionFactoryFunctionalTest.java index d5e38b92fa..546feaae50 100644 --- a/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/BaseSessionFactoryFunctionalTest.java +++ b/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/BaseSessionFactoryFunctionalTest.java @@ -10,6 +10,10 @@ import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.Locale; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; import java.util.function.Consumer; import java.util.function.Function; @@ -48,6 +52,8 @@ public abstract class BaseSessionFactoryFunctionalTest DomainModelProducer, DomainModelScopeAware, SessionFactoryProducer, SessionFactoryScopeAware { + protected static final Dialect DIALECT = DialectContext.getDialect(); + protected static final Class[] NO_CLASSES = new Class[0]; protected static final String[] NO_MAPPINGS = new String[0]; @@ -57,6 +63,8 @@ public abstract class BaseSessionFactoryFunctionalTest private DomainModelScope modelScope; private SessionFactoryScope sessionFactoryScope; + private final ExecutorService executorService = Executors.newSingleThreadExecutor(); + protected SessionFactoryScope sessionFactoryScope() { return sessionFactoryScope; } @@ -290,4 +298,20 @@ public abstract class BaseSessionFactoryFunctionalTest return false; } + protected Future executeAsync(Runnable callable) { + return executorService.submit(callable); + } + + protected void executeSync(Runnable callable) { + try { + executeAsync( callable ).get(); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + catch (ExecutionException e) { + throw new RuntimeException( e.getCause() ); + } + } + } diff --git a/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/EntityManagerFactoryBasedFunctionalTest.java b/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/EntityManagerFactoryBasedFunctionalTest.java index 97725a1949..4f3730bf54 100644 --- a/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/EntityManagerFactoryBasedFunctionalTest.java +++ b/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/EntityManagerFactoryBasedFunctionalTest.java @@ -279,6 +279,9 @@ public class EntityManagerFactoryBasedFunctionalTest return false; } + /** + * Tests should ideally override this standard implementation; it may not work in all cases (e.g. with @Embeddable entities) + */ protected void cleanupTestData() { doInJPA( this::entityManagerFactory, entityManager -> { Arrays.stream( diff --git a/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/SettingProvider.java b/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/SettingProvider.java index f5c95efd3b..51c2befaef 100644 --- a/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/SettingProvider.java +++ b/hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/SettingProvider.java @@ -15,5 +15,5 @@ public @interface SettingProvider { } String settingName(); - Class provider(); + Class> provider(); }