hibernate-testing cleanup

This commit is contained in:
Steve Ebersole 2021-03-05 07:28:18 -06:00
parent 6250942e7f
commit 2ee5ed0e52
25 changed files with 269 additions and 992 deletions

View File

@ -20,11 +20,11 @@ import javax.persistence.Table;
import org.hibernate.PropertyValueException; import org.hibernate.PropertyValueException;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit5.SessionFactoryBasedFunctionalTest; import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@ -32,25 +32,30 @@ import static org.junit.Assert.fail;
* @author Andrea Boriero * @author Andrea Boriero
*/ */
@TestForIssue(jiraKey = "HHH-11596") @TestForIssue(jiraKey = "HHH-11596")
public class OneToOneJoinTableNonOptionalTest extends SessionFactoryBasedFunctionalTest { @DomainModel(
annotatedClasses = {
@Override OneToOneJoinTableNonOptionalTest.Show.class,
protected Class[] getAnnotatedClasses() { OneToOneJoinTableNonOptionalTest.ShowDescription.class
return new Class[] {Show.class, ShowDescription.class};
} }
)
@SessionFactory
public class OneToOneJoinTableNonOptionalTest {
@Test @Test
public void testSavingEntitiesWithANullOneToOneAssociationValue() { public void testSavingEntitiesWithANullOneToOneAssociationValue(SessionFactoryScope scope) {
doInHibernate( this::sessionFactory, session -> { scope.inTransaction(
(session) -> {
Show show = new Show(); Show show = new Show();
session.save( show ); session.save( show );
} ); }
);
try { try {
doInHibernate( this::sessionFactory, session -> { scope.inTransaction(
(session) -> {
ShowDescription showDescription = new ShowDescription(); ShowDescription showDescription = new ShowDescription();
session.save( showDescription ); session.save( showDescription );
} ); }
);
fail(); fail();
} }
catch (PropertyValueException expected) { catch (PropertyValueException expected) {

View File

@ -18,34 +18,39 @@ import javax.persistence.OneToOne;
import javax.persistence.Table; import javax.persistence.Table;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit5.SessionFactoryBasedFunctionalTest; import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate;
/** /**
* @author Andrea Boriero * @author Andrea Boriero
*/ */
@TestForIssue(jiraKey = "HHH-11596") @TestForIssue(jiraKey = "HHH-11596")
public class OneToOneJoinTableOptionalTest extends SessionFactoryBasedFunctionalTest { @DomainModel(
annotatedClasses = {
@Override OneToOneJoinTableOptionalTest.Show.class,
protected Class[] getAnnotatedClasses() { OneToOneJoinTableOptionalTest.ShowDescription.class
return new Class[] {Show.class, ShowDescription.class};
} }
)
@SessionFactory
public class OneToOneJoinTableOptionalTest {
@Test @Test
public void testSavingEntitiesWithANullOneToOneAssociationValue() { public void testSavingEntitiesWithANullOneToOneAssociationValue(SessionFactoryScope scope) {
doInHibernate( this::sessionFactory, session -> { scope.inTransaction(
(session) -> {
Show show = new Show(); Show show = new Show();
session.save( show ); session.save( show );
} ); }
);
doInHibernate( this::sessionFactory, session -> { scope.inTransaction(
(session) -> {
ShowDescription showDescription = new ShowDescription(); ShowDescription showDescription = new ShowDescription();
session.save( showDescription ); session.save( showDescription );
} ); }
);
} }
@Entity(name = "Show") @Entity(name = "Show")

View File

@ -11,14 +11,11 @@ import javax.persistence.Id;
import javax.persistence.MapsId; import javax.persistence.MapsId;
import javax.persistence.OneToOne; import javax.persistence.OneToOne;
import org.hibernate.id.enhanced.SequenceStyleGenerator;
import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import org.hibernate.persister.entity.AbstractEntityPersister; import org.hibernate.persister.entity.AbstractEntityPersister;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit5.EntityManagerFactoryBasedFunctionalTest; import org.hibernate.testing.junit5.EntityManagerFactoryBasedFunctionalTest;
import org.hibernate.testing.junit5.SessionFactoryBasedFunctionalTest;
import org.hibernate.testing.logger.LoggerInspectionRule; import org.hibernate.testing.logger.LoggerInspectionRule;
import org.hibernate.testing.logger.Triggerable; import org.hibernate.testing.logger.Triggerable;
import org.junit.Rule; import org.junit.Rule;

View File

@ -12,7 +12,9 @@ import org.hibernate.Transaction;
import org.hibernate.exception.ConstraintViolationException; import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit5.SessionFactoryBasedFunctionalTest; import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -20,12 +22,14 @@ import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@TestForIssue(jiraKey = "HHH-9798") @TestForIssue(jiraKey = "HHH-9798")
public class OneToOneJoinTableTest extends SessionFactoryBasedFunctionalTest { @DomainModel( annotatedClasses = { Shipment.class, Item.class } )
@SessionFactory
public class OneToOneJoinTableTest {
@Test @Test
public void storeNonUniqueRelationship() { public void storeNonUniqueRelationship(SessionFactoryScope scope) {
inSession( scope.inSession(
session -> { (session) -> {
try { try {
Transaction tx = session.beginTransaction(); Transaction tx = session.beginTransaction();
@ -57,20 +61,12 @@ public class OneToOneJoinTableTest extends SessionFactoryBasedFunctionalTest {
} }
@AfterEach @AfterEach
public void cleanUpData() { public void cleanUpData(SessionFactoryScope scope) {
inTransaction( scope.inTransaction(
session -> { session -> {
session.createQuery( "delete Shipment" ).executeUpdate(); session.createQuery( "delete Shipment" ).executeUpdate();
session.createQuery( "delete Item" ).executeUpdate(); session.createQuery( "delete Item" ).executeUpdate();
} }
); );
} }
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] {
Shipment.class,
Item.class
};
}
} }

View File

@ -12,7 +12,9 @@ import javax.persistence.Entity;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
import javax.persistence.Id; import javax.persistence.Id;
import org.hibernate.testing.junit5.SessionFactoryBasedFunctionalTest; import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -21,39 +23,12 @@ import static org.junit.Assert.assertEquals;
/** /**
* @author Chris Cranford * @author Chris Cranford
*/ */
public class DateQueryParameterTest extends SessionFactoryBasedFunctionalTest { @DomainModel( annotatedClasses = DateQueryParameterTest.DateEntity.class )
@Entity(name = "DateEntity") @SessionFactory
public static class DateEntity { public class DateQueryParameterTest {
@Id
@GeneratedValue
private Integer id;
private Date timestamp;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
}
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] { DateEntity.class };
}
@Test @Test
public void testDateEntityQuery() { public void testDateEntityQuery(SessionFactoryScope scope) {
long current = System.currentTimeMillis(); long current = System.currentTimeMillis();
long timestamp1 = current - 2222; long timestamp1 = current - 2222;
long timestamp2 = current - 1111; long timestamp2 = current - 1111;
@ -61,7 +36,7 @@ public class DateQueryParameterTest extends SessionFactoryBasedFunctionalTest {
long timestamp4 = current + 1111; long timestamp4 = current + 1111;
long timestamp5 = current + 2222; long timestamp5 = current + 2222;
inTransaction( scope.inTransaction(
session -> { session -> {
final DateEntity entity = new DateEntity(); final DateEntity entity = new DateEntity();
entity.setTimestamp( new Date(timestamp2) ); entity.setTimestamp( new Date(timestamp2) );
@ -69,7 +44,7 @@ public class DateQueryParameterTest extends SessionFactoryBasedFunctionalTest {
} }
); );
inTransaction( scope.inTransaction(
session -> { session -> {
final DateEntity entity = new DateEntity(); final DateEntity entity = new DateEntity();
entity.setTimestamp( new Date(timestamp4) ); entity.setTimestamp( new Date(timestamp4) );
@ -77,7 +52,7 @@ public class DateQueryParameterTest extends SessionFactoryBasedFunctionalTest {
} }
); );
inTransaction( scope.inTransaction(
session -> { session -> {
// Test nothing before timestamp1 // Test nothing before timestamp1
List<DateEntity> results = session List<DateEntity> results = session
@ -104,11 +79,35 @@ public class DateQueryParameterTest extends SessionFactoryBasedFunctionalTest {
} }
@AfterEach @AfterEach
public void cleanUpData() { public void cleanUpData(SessionFactoryScope scope) {
inTransaction( scope.inTransaction(
session -> { session -> {
session.createQuery( "delete DateEntity" ).executeUpdate(); session.createQuery( "delete DateEntity" ).executeUpdate();
} }
); );
} }
@Entity(name = "DateEntity")
public static class DateEntity {
@Id
@GeneratedValue
private Integer id;
private Date timestamp;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
}
} }

View File

@ -16,7 +16,9 @@ import javax.persistence.Id;
import org.hibernate.annotations.NamedQueries; import org.hibernate.annotations.NamedQueries;
import org.hibernate.annotations.NamedQuery; import org.hibernate.annotations.NamedQuery;
import org.hibernate.testing.junit5.SessionFactoryBasedFunctionalTest; import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -25,42 +27,39 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.containsInAnyOrder;
public class NamedHqlQueriesTest extends SessionFactoryBasedFunctionalTest { @DomainModel( annotatedClasses = NamedHqlQueriesTest.VideoGame.class )
@SessionFactory
public class NamedHqlQueriesTest {
final VideoGame GOD_OF_WAR = new VideoGame( "GOW_2018", "God of war", LocalDate.of( 2018, Month.APRIL, 20 ) ); final VideoGame GOD_OF_WAR = new VideoGame( "GOW_2018", "God of war", LocalDate.of( 2018, Month.APRIL, 20 ) );
final VideoGame THE_LAST_OF_US = new VideoGame( final VideoGame THE_LAST_OF_US = new VideoGame(
"TLOU_2013", "The last of us", LocalDate.of( 2013, Month.JUNE, 14 ) ); "TLOU_2013", "The last of us", LocalDate.of( 2013, Month.JUNE, 14 ) );
@Override
protected Class[] getAnnotatedClasses() {
return new Class[] {
VideoGame.class,
};
}
@Test @Test
public void testQueryWithoutParameters() { public void testQueryWithoutParameters(SessionFactoryScope scope) {
inTransaction( scope.inTransaction(
session -> { session -> {
List<VideoGame> results = session.createNamedQuery( "videogames" ).list(); List<VideoGame> results = session.createNamedQuery( "videogames", VideoGame.class ).list();
assertThat( results, containsInAnyOrder( GOD_OF_WAR, THE_LAST_OF_US ) ); assertThat( results, containsInAnyOrder( GOD_OF_WAR, THE_LAST_OF_US ) );
} ); }
);
} }
@Test @Test
public void testQueryWithSingleParameters() { public void testQueryWithSingleParameters(SessionFactoryScope scope) {
inTransaction( scope.inTransaction(
session -> { session -> {
List<VideoGame> results = session.createNamedQuery( "title" ) List<VideoGame> results = session.createNamedQuery( "title", VideoGame.class )
.setParameter("title", GOD_OF_WAR.getTitle() ) .setParameter("title", GOD_OF_WAR.getTitle() )
.list(); .list();
assertThat( results, contains( GOD_OF_WAR ) ); assertThat( results, contains( GOD_OF_WAR ) );
} ); }
);
} }
@BeforeEach @BeforeEach
public void setUp() { public void setUp(SessionFactoryScope scope) {
inTransaction( scope.inTransaction(
session -> { session -> {
session.save( GOD_OF_WAR ); session.save( GOD_OF_WAR );
session.save( THE_LAST_OF_US ); session.save( THE_LAST_OF_US );
@ -68,8 +67,8 @@ public class NamedHqlQueriesTest extends SessionFactoryBasedFunctionalTest {
} }
@AfterEach @AfterEach
public void tearDown() { public void tearDown(SessionFactoryScope scope) {
inTransaction( scope.inTransaction(
session -> { session -> {
session.createQuery( "from VideoGame vg" ) session.createQuery( "from VideoGame vg" )
.list() .list()

View File

@ -9,8 +9,10 @@ package org.hibernate.orm.test.query.hql;
import java.util.Calendar; import java.util.Calendar;
import java.util.List; import java.util.List;
import org.hibernate.testing.junit5.SessionFactoryBasedFunctionalTest;
import org.hibernate.testing.orm.domain.gambit.SimpleEntity; import org.hibernate.testing.orm.domain.gambit.SimpleEntity;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -21,18 +23,12 @@ import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* @author Andrea Boriero * @author Andrea Boriero
*/ */
public class SubqueryLimitOffsetTest extends SessionFactoryBasedFunctionalTest { @DomainModel( annotatedClasses = SimpleEntity.class )
@SessionFactory
@Override public class SubqueryLimitOffsetTest {
protected Class[] getAnnotatedClasses() {
return new Class[] {
SimpleEntity.class,
};
}
@Test @Test
public void testSubqueryLimitOffset() { public void testSubqueryLimitOffset(SessionFactoryScope scope) {
inTransaction( scope.inTransaction(
session -> { session -> {
List results = session.createQuery( List results = session.createQuery(
"select o from SimpleEntity o where o.someString = ( select oSub.someString from SimpleEntity oSub order by oSub.someString limit 1 )" ) "select o from SimpleEntity o where o.someString = ( select oSub.someString from SimpleEntity oSub order by oSub.someString limit 1 )" )
@ -42,8 +38,8 @@ public class SubqueryLimitOffsetTest extends SessionFactoryBasedFunctionalTest {
} }
@BeforeEach @BeforeEach
public void setUp() { public void setUp(SessionFactoryScope scope) {
inTransaction( scope.inTransaction(
session -> { session -> {
SimpleEntity entity = new SimpleEntity( SimpleEntity entity = new SimpleEntity(
1, 1,
@ -69,12 +65,11 @@ public class SubqueryLimitOffsetTest extends SessionFactoryBasedFunctionalTest {
} }
@AfterEach @AfterEach
public void tearDown() { public void tearDown(SessionFactoryScope scope) {
inTransaction( scope.inTransaction(
session -> { session -> session.createQuery( "from SimpleEntity e" )
session.createQuery( "from SimpleEntity e" )
.list() .list()
.forEach( simpleEntity -> session.delete( simpleEntity ) ); .forEach( simpleEntity -> session.delete( simpleEntity ) )
} ); );
} }
} }

View File

@ -6,55 +6,54 @@
*/ */
package org.hibernate.orm.test.query.hql; package org.hibernate.orm.test.query.hql;
import org.hibernate.testing.junit5.SessionFactoryBasedFunctionalTest; import java.util.Calendar;
import java.util.List;
import org.hibernate.testing.orm.domain.gambit.SimpleEntity; import org.hibernate.testing.orm.domain.gambit.SimpleEntity;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.util.Calendar;
import java.util.List;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* @author Gavin King * @author Gavin King
*/ */
public class SubqueryOperatorsTest extends SessionFactoryBasedFunctionalTest { @DomainModel( annotatedClasses = SimpleEntity.class )
@SessionFactory
@Override public class SubqueryOperatorsTest {
protected Class[] getAnnotatedClasses() {
return new Class[] {
SimpleEntity.class,
};
}
@Test @Test
public void testEvery() { public void testEvery(SessionFactoryScope scope) {
inTransaction( scope.inTransaction(
session -> { session -> {
List results = session.createQuery( List results = session.createQuery(
"from SimpleEntity o where o.someString >= every (select someString from SimpleEntity)" ) "from SimpleEntity o where o.someString >= every (select someString from SimpleEntity)" )
.list(); .list();
assertThat( results.size(), is( 1 ) ); assertThat( results.size(), is( 1 ) );
} ); }
);
} }
@Test @Test
public void testAny() { public void testAny(SessionFactoryScope scope) {
inTransaction( scope.inTransaction(
session -> { session -> {
List results = session.createQuery( List results = session.createQuery(
"from SimpleEntity o where o.someString >= any (select someString from SimpleEntity)" ) "from SimpleEntity o where o.someString >= any (select someString from SimpleEntity)" )
.list(); .list();
assertThat( results.size(), is( 2 ) ); assertThat( results.size(), is( 2 ) );
} ); }
);
} }
@Test @Test
public void testSubqueryInVariousClauses() { public void testSubqueryInVariousClauses(SessionFactoryScope scope) {
inTransaction( scope.inTransaction(
session -> { session -> {
List res0 = session.createQuery( List res0 = session.createQuery(
"select (select cast(1 as Integer)) as one, (select cast('foo' as String)) as foo order by one, foo, (select 2)" ) "select (select cast(1 as Integer)) as one, (select cast('foo' as String)) as foo order by one, foo, (select 2)" )
@ -76,12 +75,13 @@ public class SubqueryOperatorsTest extends SessionFactoryBasedFunctionalTest {
"from SimpleEntity o where o.id = (select y.id from SimpleEntity y where y.id = o.id)" ) "from SimpleEntity o where o.id = (select y.id from SimpleEntity y where y.id = o.id)" )
.list(); .list();
assertThat( res4.size(), is( 2 ) ); assertThat( res4.size(), is( 2 ) );
} ); }
);
} }
@Test @Test
public void testExists() { public void testExists(SessionFactoryScope scope) {
inTransaction( scope.inTransaction(
session -> { session -> {
List results = session.createQuery( List results = session.createQuery(
"from SimpleEntity o where exists (select someString from SimpleEntity where someString>o.someString)" ) "from SimpleEntity o where exists (select someString from SimpleEntity where someString>o.someString)" )
@ -91,12 +91,13 @@ public class SubqueryOperatorsTest extends SessionFactoryBasedFunctionalTest {
"from SimpleEntity o where not exists (select someString from SimpleEntity where someString>o.someString)" ) "from SimpleEntity o where not exists (select someString from SimpleEntity where someString>o.someString)" )
.list(); .list();
assertThat( results.size(), is( 1 ) ); assertThat( results.size(), is( 1 ) );
} ); }
);
} }
@BeforeEach @BeforeEach
public void setUp() { public void setUp(SessionFactoryScope scope) {
inTransaction( scope.inTransaction(
session -> { session -> {
SimpleEntity entity = new SimpleEntity( SimpleEntity entity = new SimpleEntity(
1, 1,
@ -118,14 +119,16 @@ public class SubqueryOperatorsTest extends SessionFactoryBasedFunctionalTest {
); );
session.save( second_entity ); session.save( second_entity );
} ); }
);
} }
@AfterEach @AfterEach
public void tearDown() { public void tearDown(SessionFactoryScope scope) {
inTransaction( scope.inTransaction(
session -> { session -> {
session.createQuery( "delete SimpleEntity" ).executeUpdate(); session.createQuery( "delete SimpleEntity" ).executeUpdate();
} ); }
);
} }
} }

View File

@ -6,30 +6,24 @@
*/ */
package org.hibernate.orm.test.query.sqm.exec; package org.hibernate.orm.test.query.sqm.exec;
import org.hibernate.testing.junit5.SessionFactoryBasedFunctionalTest;
import org.hibernate.testing.orm.domain.gambit.SimpleEntity; import org.hibernate.testing.orm.domain.gambit.SimpleEntity;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
/** /**
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public class CrossJoinTest extends SessionFactoryBasedFunctionalTest { @DomainModel( annotatedClasses = SimpleEntity.class )
@SessionFactory
@Override public class CrossJoinTest {
protected Class[] getAnnotatedClasses() {
return new Class[] {
SimpleEntity.class,
};
}
@Test @Test
public void testSimpleCrossJoin() { public void testSimpleCrossJoin(SessionFactoryScope scope) {
inTransaction( final String QRY_STRING = "from SimpleEntity e1, SimpleEntity e2 where e1.id = e2.id and e1.someDate = {ts '2018-01-01 00:00:00'}";
scope.inTransaction(
session -> { session -> {
session.createQuery( session.createQuery( QRY_STRING ).list();
"from SimpleEntity e1, SimpleEntity e2 where e1.id = e2.id and e1.someDate = {ts '2018-01-01 00:00:00'}" )
.list();
} }
); );
} }

View File

@ -6,46 +6,40 @@
*/ */
package org.hibernate.orm.test.query.sqm.exec; package org.hibernate.orm.test.query.sqm.exec;
import org.hibernate.boot.MetadataSources;
import org.hibernate.testing.junit5.SessionFactoryBasedFunctionalTest;
import org.hibernate.testing.orm.domain.StandardDomainModel; import org.hibernate.testing.orm.domain.StandardDomainModel;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
/** @DomainModel( standardModels = StandardDomainModel.GAMBIT )
* @author Steve Ebersole @SessionFactory
*/ public class LiteralTests {
public class LiteralTests extends SessionFactoryBasedFunctionalTest {
@Override @Test
protected void applyMetadataSources(MetadataSources metadataSources) { public void testTimestampLiteral(SessionFactoryScope scope) {
StandardDomainModel.GAMBIT.getDescriptor().applyDomainModel( metadataSources ); final String queryString = "from EntityOfBasics e1 where e1.theTimestamp = {ts '2018-01-01T12:30:00'}";
scope.inTransaction(
session -> session.createQuery( queryString ).list()
);
} }
@Test @Test
public void testTimestampLiteral() { public void testDateLiteral(SessionFactoryScope scope) {
inTransaction( scope.inTransaction(
session -> { session -> {
session.createQuery( "from EntityOfBasics e1 where e1.theTimestamp = {ts '2018-01-01T12:30:00'}" ) final String queryString = "from EntityOfBasics e1 where e1.theDate = {d '2018-01-01'}";
.list(); session.createQuery( queryString ).list();
} }
); );
} }
@Test @Test
public void testDateLiteral() { public void testTimeLiteral(SessionFactoryScope scope) {
inTransaction( scope.inTransaction(
session -> { session -> {
session.createQuery( "from EntityOfBasics e1 where e1.theDate = {d '2018-01-01'}" ).list(); final String queryString = "from EntityOfBasics e1 where e1.theTime = {t '12:30:00'}";
} session.createQuery( queryString ).list();
);
}
@Test
public void testTimeLiteral() {
inTransaction(
session -> {
session.createQuery( "from EntityOfBasics e1 where e1.theTime = {t '12:30:00'}" ).list();
} }
); );
} }

View File

@ -6,27 +6,22 @@
*/ */
package org.hibernate.orm.test.query.sqm.exec; package org.hibernate.orm.test.query.sqm.exec;
import org.hibernate.boot.MetadataSources;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit5.SessionFactoryBasedFunctionalTest;
import org.hibernate.testing.orm.domain.StandardDomainModel; import org.hibernate.testing.orm.domain.StandardDomainModel;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
/** /**
* Tests for order-by clauses * Tests for order-by clauses
* @author Steve Ebersole
*/ */
public class OrderingTests extends SessionFactoryBasedFunctionalTest { @DomainModel( standardModels = StandardDomainModel.RETAIL )
@SessionFactory
@Override public class OrderingTests {
protected void applyMetadataSources(MetadataSources metadataSources) {
StandardDomainModel.RETAIL.getDescriptor().applyDomainModel( metadataSources );
}
@Test @Test
public void testBasicOrdering() { public void testBasicOrdering(SessionFactoryScope scope) {
inTransaction( scope.inTransaction(
session -> { session -> {
session.createQuery( "from SalesAssociate p order by p.name.familiarName" ) session.createQuery( "from SalesAssociate p order by p.name.familiarName" )
.list(); .list();
@ -36,8 +31,8 @@ public class OrderingTests extends SessionFactoryBasedFunctionalTest {
@Test @Test
@TestForIssue( jiraKey = "HHH-1356" ) @TestForIssue( jiraKey = "HHH-1356" )
public void testFunctionBasedOrdering() { public void testFunctionBasedOrdering(SessionFactoryScope scope) {
inTransaction( scope.inTransaction(
session -> { session -> {
session.createQuery( "from SalesAssociate p order by upper( p.name.familiarName )" ) session.createQuery( "from SalesAssociate p order by upper( p.name.familiarName )" )
.list(); .list();
@ -47,8 +42,8 @@ public class OrderingTests extends SessionFactoryBasedFunctionalTest {
@Test @Test
@TestForIssue( jiraKey = "HHH-11688" ) @TestForIssue( jiraKey = "HHH-11688" )
public void testSelectAliasOrdering() { public void testSelectAliasOrdering(SessionFactoryScope scope) {
inTransaction( scope.inTransaction(
session -> { session -> {
session.createQuery( "select v.name as n from Vendor v order by n" ) session.createQuery( "select v.name as n from Vendor v order by n" )
.list(); .list();
@ -58,8 +53,8 @@ public class OrderingTests extends SessionFactoryBasedFunctionalTest {
@Test @Test
@TestForIssue( jiraKey = "HHH-11688" ) @TestForIssue( jiraKey = "HHH-11688" )
public void testSelectPositionOrdering() { public void testSelectPositionOrdering(SessionFactoryScope scope) {
inTransaction( scope.inTransaction(
session -> { session -> {
session.createQuery( "select v.name as n from Vendor v order by 1" ) session.createQuery( "select v.name as n from Vendor v order by 1" )
.list(); .list();

View File

@ -6,25 +6,21 @@
*/ */
package org.hibernate.orm.test.query.sqm.exec; package org.hibernate.orm.test.query.sqm.exec;
import org.hibernate.boot.MetadataSources;
import org.hibernate.testing.junit5.SessionFactoryBasedFunctionalTest;
import org.hibernate.testing.orm.domain.StandardDomainModel; import org.hibernate.testing.orm.domain.StandardDomainModel;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
/** /**
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public class ParameterTest extends SessionFactoryBasedFunctionalTest { @DomainModel( standardModels = StandardDomainModel.RETAIL )
@SessionFactory
@Override public class ParameterTest {
protected void applyMetadataSources(MetadataSources metadataSources) {
StandardDomainModel.RETAIL.getDescriptor().applyDomainModel( metadataSources );
}
@Test @Test
public void testReusedNamedParam() { public void testReusedNamedParam(SessionFactoryScope scope) {
inTransaction( scope.inTransaction(
session -> { session -> {
session.createQuery( "from SalesAssociate p where p.name.familiarName = :name or p.name.familyName = :name" ) session.createQuery( "from SalesAssociate p where p.name.familiarName = :name or p.name.familyName = :name" )
.setParameter( "name", "a name" ) .setParameter( "name", "a name" )
@ -34,8 +30,8 @@ public class ParameterTest extends SessionFactoryBasedFunctionalTest {
} }
@Test @Test
public void testReusedOrdinalParam() { public void testReusedOrdinalParam(SessionFactoryScope scope) {
inTransaction( scope.inTransaction(
session -> { session -> {
session.createQuery( "from SalesAssociate p where p.name.familiarName = ?1 or p.name.familyName = ?1" ) session.createQuery( "from SalesAssociate p where p.name.familiarName = ?1 or p.name.familyName = ?1" )
.setParameter( 1, "a name" ) .setParameter( 1, "a name" )

View File

@ -8,8 +8,11 @@ package org.hibernate.orm.test.query.sqm.exec;
import java.util.List; import java.util.List;
import org.hibernate.testing.junit5.SessionFactoryBasedFunctionalTest;
import org.hibernate.testing.orm.domain.gambit.BasicEntity; import org.hibernate.testing.orm.domain.gambit.BasicEntity;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -19,32 +22,12 @@ import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* @author Chris Cranford * @author Chris Cranford
*/ */
public class SubQueryTest extends SessionFactoryBasedFunctionalTest { @DomainModel( annotatedClasses = BasicEntity.class )
@SessionFactory
@Override public class SubQueryTest {
protected Class[] getAnnotatedClasses() {
return new Class[] {
BasicEntity.class
};
}
@BeforeAll
public void prepareData() {
inTransaction(
session -> {
BasicEntity entity1 = new BasicEntity( 1, "e1" );
BasicEntity entity2 = new BasicEntity( 2, "e2" );
BasicEntity entity3 = new BasicEntity( 3, "e1" );
session.save( entity1 );
session.save( entity2 );
session.save( entity3 );
}
);
}
@Test @Test
public void testSubQueryWithMaxFunction() { public void testSubQueryWithMaxFunction(SessionFactoryScope scope) {
inTransaction( scope.inTransaction(
session -> { session -> {
final String hql = "SELECT e FROM BasicEntity e WHERE e.id = " + final String hql = "SELECT e FROM BasicEntity e WHERE e.id = " +
"(SELECT max(e1.id) FROM BasicEntity e1 WHERE e1.data = :data)"; "(SELECT max(e1.id) FROM BasicEntity e1 WHERE e1.data = :data)";
@ -61,8 +44,8 @@ public class SubQueryTest extends SessionFactoryBasedFunctionalTest {
} }
@Test @Test
public void testSubQueryWithMinFunction() { public void testSubQueryWithMinFunction(SessionFactoryScope scope) {
inTransaction( scope.inTransaction(
session -> { session -> {
final String hql = "SELECT e FROM BasicEntity e WHERE e.id = " + final String hql = "SELECT e FROM BasicEntity e WHERE e.id = " +
"(SELECT min(e1.id) FROM BasicEntity e1 WHERE e1.data = :data)"; "(SELECT min(e1.id) FROM BasicEntity e1 WHERE e1.data = :data)";
@ -77,4 +60,25 @@ public class SubQueryTest extends SessionFactoryBasedFunctionalTest {
} }
); );
} }
@BeforeAll
public void prepareData(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
BasicEntity entity1 = new BasicEntity( 1, "e1" );
BasicEntity entity2 = new BasicEntity( 2, "e2" );
BasicEntity entity3 = new BasicEntity( 3, "e1" );
session.save( entity1 );
session.save( entity2 );
session.save( entity3 );
}
);
}
@AfterAll
public void dropData(SessionFactoryScope scope) {
scope.inTransaction(
session -> session.createQuery( "delete BasicEntity" ).executeUpdate()
);
}
} }

View File

@ -11,8 +11,10 @@ import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.OneToOne; import javax.persistence.OneToOne;
import org.hibernate.testing.junit5.SessionFactoryBasedFunctionalTest; import org.hibernate.testing.orm.junit.DomainModel;
import org.junit.jupiter.api.Disabled; import org.hibernate.testing.orm.junit.NotImplementedYet;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
@ -20,22 +22,21 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
/** /**
* @author Andrea Boriero * @author Andrea Boriero
*/ */
@Disabled("non-aggregated composite-id not yet implemented") @NotImplementedYet( reason = "non-aggregated composite-id not yet implemented" )
public class OneToOneWithDerivedIdentityTest extends SessionFactoryBasedFunctionalTest { @DomainModel(
annotatedClasses = {
OneToOneWithDerivedIdentityTest.Person.class,
OneToOneWithDerivedIdentityTest.PersonInfo.class
}
)
@SessionFactory
public class OneToOneWithDerivedIdentityTest {
private static final Integer PERSON_ID = 1; private static final Integer PERSON_ID = 1;
@Override
protected Class[] getAnnotatedClasses() {
return new Class[] {
Person.class,
PersonInfo.class
};
}
@Test @Test
public void testGet() { public void testGet(SessionFactoryScope scope) {
inTransaction( scope.inTransaction(
session -> { session -> {
Person p = new Person(); Person p = new Person();
@ -49,7 +50,7 @@ public class OneToOneWithDerivedIdentityTest extends SessionFactoryBasedFunction
} ); } );
inTransaction( scope.inTransaction(
session -> { session -> {
Person person = session.get( Person.class, PERSON_ID ); Person person = session.get( Person.class, PERSON_ID );
assertEquals( "Alfio", person.getName() ); assertEquals( "Alfio", person.getName() );

View File

@ -1,44 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.hibernate.testing.orm.junit.FailureExpectedExtension;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.extension.ExtendWith;
/**
* Composite annotation for functional tests that
* require a functioning SessionFactory.
*
* @apiNote Logically this should also include
* `@TestInstance( TestInstance.Lifecycle.PER_CLASS )`
* but that annotation is not conveyed (is that the
* right word? its not applied to the thing using this annotation).
* Test classes should apply that themselves.
*
* @see SessionFactoryScopeExtension
* @see DialectFilterExtension
* @see FailureExpectedExtension
*
* @author Steve Ebersole
*/
@Retention( RetentionPolicy.RUNTIME )
@Target(ElementType.TYPE)
@Inherited
@TestInstance( TestInstance.Lifecycle.PER_CLASS )
@ExtendWith( SessionFactoryScopeExtension.class )
@ExtendWith( DialectFilterExtension.class )
@ExtendWith( FailureExpectedExtension.class )
@SuppressWarnings("WeakerAccess")
public @interface FunctionalSessionFactoryTesting {
}

View File

@ -1,219 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import javax.persistence.SharedCacheMode;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataBuilder;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.SessionFactoryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.mapping.RootClass;
import org.hibernate.tool.schema.Action;
import org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator;
import org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.ActionGrouping;
import org.junit.jupiter.api.AfterEach;
import org.jboss.logging.Logger;
/**
* @author Steve Ebersole
*/
@FunctionalSessionFactoryTesting
public abstract class SessionFactoryBasedFunctionalTest
extends BaseUnitTest
implements SessionFactoryProducer, SessionFactoryScopeContainer {
protected static final Class[] NO_CLASSES = new Class[0];
protected static final String[] NO_MAPPINGS = new String[0];
protected static final Logger log = Logger.getLogger( SessionFactoryBasedFunctionalTest.class );
private SessionFactoryScope sessionFactoryScope;
private Metadata metadata;
protected SessionFactoryScope sessionFactoryScope() {
return sessionFactoryScope;
}
protected SessionFactoryImplementor sessionFactory() {
return sessionFactoryScope.getSessionFactory();
}
@Override
public SessionFactoryImplementor produceSessionFactory() {
log.trace( "Producing SessionFactory" );
final StandardServiceRegistryBuilder ssrBuilder = new StandardServiceRegistryBuilder()
.applySetting( AvailableSettings.HBM2DDL_AUTO, exportSchema() ? "create-drop" : "none" );
applySettings( ssrBuilder );
applyCacheSettings( ssrBuilder );
final StandardServiceRegistry ssr = ssrBuilder.build();
try {
metadata = buildMetadata( ssr );
final SessionFactoryBuilder sfBuilder = metadata.getSessionFactoryBuilder();
configure( sfBuilder );
final SessionFactoryImplementor factory = (SessionFactoryImplementor) metadata.buildSessionFactory();
sessionFactoryBuilt( factory );
return factory;
}
catch (Exception e) {
StandardServiceRegistryBuilder.destroy( ssr );
if ( exportSchema() && metadata != null ) {
final Set<ActionGrouping> groupings = ActionGrouping.interpret( metadata, ssrBuilder.getSettings() );
if ( ! groupings.isEmpty() ) {
dropDatabase();
}
}
throw e;
}
}
private MetadataImplementor buildMetadata(StandardServiceRegistry ssr) {
MetadataSources metadataSources = new MetadataSources( ssr );
applyMetadataSources( metadataSources );
final MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder();
configureMetadataBuilder( metadataBuilder );
return (MetadataImplementor) metadataBuilder.build();
}
private void dropDatabase() {
// final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().build();
// try {
// final DatabaseModel databaseModel = Helper.buildDatabaseModel( ssr, buildMetadata( ssr ) );
// new SchemaExport( databaseModel, ssr ).drop( EnumSet.of( TargetType.DATABASE ) );
// }
// finally {
// StandardServiceRegistryBuilder.destroy( ssr );
// }
}
protected void configureMetadataBuilder(MetadataBuilder metadataBuilder) {
}
protected void applySettings(StandardServiceRegistryBuilder builer) {
}
protected void configure(SessionFactoryBuilder builder) {
}
protected void sessionFactoryBuilt(SessionFactoryImplementor factory) {
}
protected boolean strictJpaCompliance() {
return false;
}
protected boolean exportSchema() {
return true;
}
protected void applyMetadataSources(MetadataSources metadataSources) {
for ( Class annotatedClass : getAnnotatedClasses() ) {
metadataSources.addAnnotatedClass( annotatedClass );
}
for ( String mapping : getHbmMappingFiles() ) {
metadataSources.addResource(
getBaseForMappings() + mapping
);
}
}
protected Class[] getAnnotatedClasses() {
return NO_CLASSES;
}
protected String[] getHbmMappingFiles() {
return NO_MAPPINGS;
}
protected String getBaseForMappings() {
return "org/hibernate/orm/test/";
}
@Override
public void injectSessionFactoryScope(SessionFactoryScope scope) {
sessionFactoryScope = scope;
}
@Override
public SessionFactoryProducer getSessionFactoryProducer() {
return this;
}
protected Metadata getMetadata(){
return metadata;
}
protected String getCacheConcurrencyStrategy() {
return null;
}
protected void applyCacheSettings(StandardServiceRegistryBuilder builer) {
if ( getCacheConcurrencyStrategy() != null ) {
builer.applySetting( AvailableSettings.DEFAULT_CACHE_CONCURRENCY_STRATEGY, getCacheConcurrencyStrategy() );
builer.applySetting( AvailableSettings.JPA_SHARED_CACHE_MODE, SharedCacheMode.ALL.name() );
}
}
@AfterEach
public final void afterTest() {
if ( isCleanupTestDataRequired() ) {
cleanupTestData();
}
}
protected boolean isCleanupTestDataRequired() {
return false;
}
protected void cleanupTestData() {
inTransaction(
session -> {
getMetadata().getEntityBindings().forEach(
persistentClass -> {
if ( persistentClass instanceof RootClass ) {
final String entityName = persistentClass.getEntityName();
session.createQuery( "delete from " + entityName ).executeUpdate();
}
}
);
}
);
}
protected void inTransaction(Consumer<SessionImplementor> action) {
sessionFactoryScope().inTransaction( action );
}
protected <R> R inTransaction(Function<SessionImplementor, R> action) {
return sessionFactoryScope().inTransaction( action );
}
protected <R> R inSession(Function<SessionImplementor, R> action) {
return sessionFactoryScope.inSession( action );
}
protected void inSession(Consumer<SessionImplementor> action) {
sessionFactoryScope().inSession( action );
}
protected Dialect getDialect(){
return sessionFactoryScope.getDialect();
}
}

View File

@ -1,30 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5;
import org.hibernate.engine.spi.SessionFactoryImplementor;
/**
* Contract for something that can build a SessionFactory.
*
* Used by SessionFactoryScopeExtension to create the
* SessionFactoryScope.
*
* Generally speaking, a test class would implement SessionFactoryScopeContainer
* and return the SessionFactoryProducer to be used for those tests.
* The SessionFactoryProducer is then used to build the SessionFactoryScope
* which is injected back into the SessionFactoryScopeContainer
*
* @see SessionFactoryScopeExtension
* @see SessionFactoryScope
* @see SessionFactoryScopeContainer
*
* @author Steve Ebersole
*/
public interface SessionFactoryProducer {
SessionFactoryImplementor produceSessionFactory();
}

View File

@ -1,217 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5;
import java.util.function.Consumer;
import java.util.function.Function;
import org.hibernate.Transaction;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SessionImplementor;
import org.jboss.logging.Logger;
/**
* A scope or holder fot the SessionFactory instance associated with a
* given test class. Used to:
*
* * provide lifecycle management related to the SessionFactory
* * access to functional programming using a Session generated
* from that SessionFactory
*
* @author Steve Ebersole
*/
public class SessionFactoryScope implements SessionFactoryAccess {
private static final Logger log = Logger.getLogger( SessionFactoryScope.class );
private final SessionFactoryProducer producer;
private SessionFactoryImplementor sessionFactory;
public SessionFactoryScope(SessionFactoryProducer producer) {
log.trace( "SessionFactoryScope#<init>" );
this.producer = producer;
}
public void rebuild() {
log.trace( "SessionFactoryScope#rebuild" );
releaseSessionFactory();
sessionFactory = producer.produceSessionFactory();
}
public void releaseSessionFactory() {
log.trace( "SessionFactoryScope#releaseSessionFactory" );
if ( sessionFactory != null ) {
sessionFactory.close();
}
}
@Override
public SessionFactoryImplementor getSessionFactory() {
log.trace( "SessionFactoryScope#getSessionFactory" );
if ( sessionFactory == null || sessionFactory.isClosed() ) {
sessionFactory = producer.produceSessionFactory();
}
return sessionFactory;
}
public void inSession(Consumer<SessionImplementor> action) {
log.trace( "#inSession(action)" );
inSession( getSessionFactory(), action );
}
public void inTransaction(Consumer<SessionImplementor> action) {
log.trace( "#inTransaction(action)" );
inTransaction( getSessionFactory(), action );
}
protected <R> R inSession(Function<SessionImplementor, R> action) {
return inSession( getSessionFactory(), action );
}
private <R> R inSession(SessionFactoryImplementor sfi, Function<SessionImplementor, R> action) {
log.trace( "##inSession(SF,action)" );
try (SessionImplementor session = (SessionImplementor) sfi.openSession()) {
log.trace( "Session opened, calling action" );
R result = action.apply( session );
log.trace( "called action" );
return result;
}
finally {
log.trace( "Session close - auto-close lock" );
}
}
private void inSession(SessionFactoryImplementor sfi, Consumer<SessionImplementor> action) {
log.trace( "##inSession(SF,action)" );
try (SessionImplementor session = (SessionImplementor) sfi.openSession()) {
log.trace( "Session opened, calling action" );
try {
action.accept( session );
}
catch (Exception e) {
Transaction transaction = session.getTransaction();
if ( transaction != null && transaction.isActive() ) {
transaction.rollback();
}
throw e;
}
log.trace( "called action" );
}
finally {
log.trace( "Session close - auto-close lock" );
}
}
private void inTransaction(SessionFactoryImplementor factory, Consumer<SessionImplementor> action) {
log.trace( "#inTransaction(factory, action)");
try (SessionImplementor session = (SessionImplementor) factory.openSession()) {
log.trace( "Session opened, calling action" );
inTransaction( session, action );
log.trace( "called action" );
}
finally {
log.trace( "Session close - auto-close lock" );
}
}
private void inTransaction(SessionImplementor session, Consumer<SessionImplementor> action) {
log.trace( "inTransaction(session,action)" );
final Transaction txn = session.beginTransaction();
log.trace( "Started transaction" );
try {
log.trace( "Calling action in txn" );
action.accept( session );
log.trace( "Called action - in txn" );
log.trace( "Committing transaction" );
txn.commit();
log.trace( "Committed transaction" );
}
catch (Exception e) {
log.tracef(
"Error calling action: %s (%s) - rolling back",
e.getClass().getName(),
e.getMessage()
);
try {
txn.rollback();
}
catch (Exception ignore) {
log.trace( "Was unable to roll back transaction" );
// really nothing else we can do here - the attempt to
// rollback already failed and there is nothing else
// to clean up.
}
throw e;
}
}
public <R> R inTransaction(Function<SessionImplementor, R> action) {
return inTransaction( getSessionFactory(), action );
}
private <R> R inTransaction(SessionFactoryImplementor factory, Function<SessionImplementor, R> action) {
log.trace( "#inTransaction(factory, action)" );
R result;
try (SessionImplementor session = (SessionImplementor) factory.openSession()) {
log.trace( "Session opened, calling action" );
result = inTransaction( session, action );
log.trace( "called action" );
}
finally {
log.trace( "Session close - auto-close lock" );
}
return result;
}
private <R> R inTransaction(SessionImplementor session, Function<SessionImplementor, R> action) {
log.trace( "inTransaction(session,action)" );
final Transaction txn = session.beginTransaction();
log.trace( "Started transaction" );
R result;
try {
log.trace( "Calling action in txn" );
result = action.apply( session );
log.trace( "Called action - in txn" );
log.trace( "Committing transaction" );
txn.commit();
log.trace( "Committed transaction" );
}
catch (Exception e) {
log.tracef(
"Error calling action: %s (%s) - rolling back",
e.getClass().getName(),
e.getMessage()
);
try {
txn.rollback();
}
catch (Exception ignore) {
log.trace( "Was unable to roll back transaction" );
// really nothing else we can do here - the attempt to
// rollback already failed and there is nothing else
// to clean up.
}
throw e;
}
return result;
}
}

View File

@ -1,28 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5;
/**
* The keystone in SessionFactoryScopeExtension support.
*
* This is how the extensions know how to build a SessionFactory (scope)
* and how to inject that SessionFactory (scope) back into the test
*
* @author Steve Ebersole
*/
public interface SessionFactoryScopeContainer {
/**
* Callback to inject the SessionFactoryScope into the container
*/
void injectSessionFactoryScope(SessionFactoryScope scope);
/**
* Obtain the {@link SessionFactoryProducer}. Quite often this
* is als implemented by the container itself.
*/
SessionFactoryProducer getSessionFactoryProducer();
}

View File

@ -1,133 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5;
import java.util.Optional;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestExecutionExceptionHandler;
import org.junit.jupiter.api.extension.TestInstancePostProcessor;
import org.jboss.logging.Logger;
import static org.junit.jupiter.api.extension.ExtensionContext.Namespace.create;
/**
* @asciidoc
*
* The thing that actually manages lifecycle of the SessionFactory related to a
* test class. Work in conjunction with SessionFactoryScope and SessionFactoryScopeContainer
*
* todo (6.0) ?? - allow annotation-driven definition of the test mappings and settings
*
* [code]
* .Annotation-driven example
* ```
*
* @FunctionalSessionFactoryTesting (
* model = @ModelToTest (
* true, // export
* standardModels = {
* @DomainModel ( AvailableDomainModel.CONTACTS )
* },
* annotatedClasses = {
* SomeAdditionalClass.class
* },
* mappings = {
* "some-orm-mappings.xml"
* },
* ...
* ),
* config = @PersistenceUnit(
* sessionFactoryName = "a-special-name",
* ...
* )
* )
* public class MyTest {
*
* }
*
* ```
*
*
* @see SessionFactoryScope
* @see SessionFactoryScopeContainer
* @see SessionFactoryProducer
*
* @author Steve Ebersole
*/
public class SessionFactoryScopeExtension
implements TestInstancePostProcessor, AfterAllCallback, TestExecutionExceptionHandler {
private static final Logger log = Logger.getLogger( SessionFactoryScopeExtension.class );
public static final Object SESSION_FACTORY_KEY = "SESSION_FACTORY";
public static ExtensionContext.Namespace namespace(Object testInstance) {
return create( SessionFactoryScopeExtension.class.getName(), testInstance );
}
public static Optional<SessionFactoryScope> findSessionFactoryScope(ExtensionContext context) {
final ExtensionContext.Namespace namespace = namespace( context.getRequiredTestInstance() );
final SessionFactoryScope storedScope = (SessionFactoryScope) context.getStore( namespace ).get( SESSION_FACTORY_KEY );
return Optional.ofNullable( storedScope );
}
public SessionFactoryScopeExtension() {
log.trace( "SessionFactoryScopeExtension#<init>" );
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// TestInstancePostProcessor
@Override
public void postProcessTestInstance(Object testInstance, ExtensionContext context) {
log.trace( "SessionFactoryScopeExtension#postProcessTestInstance" );
if ( SessionFactoryScopeContainer.class.isInstance( testInstance ) ) {
final SessionFactoryScopeContainer scopeContainer = SessionFactoryScopeContainer.class.cast(
testInstance );
final SessionFactoryScope scope = new SessionFactoryScope( scopeContainer.getSessionFactoryProducer() );
context.getStore( namespace( testInstance ) ).put( SESSION_FACTORY_KEY, scope );
scopeContainer.injectSessionFactoryScope( scope );
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// AfterAllCallback
@Override
public void afterAll(ExtensionContext context) {
final SessionFactoryScope scope = (SessionFactoryScope) context.getStore( namespace( context.getRequiredTestInstance() ) )
.remove( SESSION_FACTORY_KEY );
if ( scope != null ) {
scope.releaseSessionFactory();
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// TestExecutionExceptionHandler
@Override
public void handleTestExecutionException(ExtensionContext context, Throwable throwable) throws Throwable {
final Optional<SessionFactoryScope> scopeOptional = findSessionFactoryScope( context );
if ( ! scopeOptional.isPresent() ) {
log.debug( "Could not locate SessionFactoryScope on exception" );
}
else {
scopeOptional.get().releaseSessionFactory();
}
throw throwable;
}
}

View File

@ -1,24 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5;
/**
* @author Steve Ebersole
*/
@SuppressWarnings("unused")
public final class StandardTags {
public static final String NOT_IMPLEMENTED_YET = "not-implemented-yet";
public static final String FAILURE_EXPECTED = "failure-expected";
public static final String PERF = "perf";
public static final String QUERY = "query";
public static final String SQM = "sqm";
public static final String UNIT = "unit";
public static final String ENVERS = "envers";
private StandardTags() {
}
}

View File

@ -10,5 +10,8 @@
* `@FailureExcepted`, `@RequiresDialect`, etc. Used in writing tests * `@FailureExcepted`, `@RequiresDialect`, etc. Used in writing tests
* *
* todo (6.0) : add the proposed Docker support - DomainModel, multi-threading etc * todo (6.0) : add the proposed Docker support - DomainModel, multi-threading etc
*
* @deprecated Use {@link org.hibernate.testing.orm.junit} instead
*/ */
@Deprecated
package org.hibernate.testing.junit5; package org.hibernate.testing.junit5;

View File

@ -16,8 +16,6 @@ import java.lang.annotation.Target;
import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
import static org.hibernate.testing.junit5.StandardTags.FAILURE_EXPECTED;
/** /**
* Marks a test method or class as being expected to fail. * Marks a test method or class as being expected to fail.
* *
@ -30,8 +28,6 @@ import static org.hibernate.testing.junit5.StandardTags.FAILURE_EXPECTED;
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Repeatable( FailureExpectedGroup.class ) @Repeatable( FailureExpectedGroup.class )
@Tag( FAILURE_EXPECTED )
@ExtendWith( FailureExpectedExtension.class ) @ExtendWith( FailureExpectedExtension.class )
public @interface FailureExpected { public @interface FailureExpected {
/** /**

View File

@ -15,8 +15,6 @@ import java.lang.annotation.Target;
import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
import static org.hibernate.testing.junit5.StandardTags.FAILURE_EXPECTED;
/** /**
* @author Steve Ebersole * @author Steve Ebersole
*/ */
@ -24,8 +22,6 @@ import static org.hibernate.testing.junit5.StandardTags.FAILURE_EXPECTED;
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) @Target({ElementType.TYPE, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Tag( FAILURE_EXPECTED )
@ExtendWith( FailureExpectedExtension.class ) @ExtendWith( FailureExpectedExtension.class )
public @interface FailureExpectedGroup { public @interface FailureExpectedGroup {
FailureExpected[] value(); FailureExpected[] value();

View File

@ -15,11 +15,8 @@ import java.lang.annotation.Target;
import org.hibernate.NotImplementedYetException; import org.hibernate.NotImplementedYetException;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
import static org.hibernate.testing.junit5.StandardTags.NOT_IMPLEMENTED_YET;
/** /**
* Marks a test method or class's tested functionality as not being implemented yet. * Marks a test method or class's tested functionality as not being implemented yet.
* *
@ -30,9 +27,6 @@ import static org.hibernate.testing.junit5.StandardTags.NOT_IMPLEMENTED_YET;
@Inherited @Inherited
@Target(value = { ElementType.TYPE, ElementType.METHOD }) @Target(value = { ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Tag(NOT_IMPLEMENTED_YET)
@ExtendWith( NotImplementedYetExtension.class ) @ExtendWith( NotImplementedYetExtension.class )
public @interface NotImplementedYet { public @interface NotImplementedYet {