Re-enable additional tests

This commit is contained in:
Andrea Boriero 2021-11-12 15:35:40 +01:00 committed by Andrea Boriero
parent 1b879a65f0
commit 7dab08448f
94 changed files with 2140 additions and 1958 deletions

View File

@ -30,18 +30,18 @@
*/ */
package org.hibernate.orm.test.cdi.converters.legacy; package org.hibernate.orm.test.cdi.converters.legacy;
import static org.junit.Assert.*;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.List; import java.util.List;
import org.hibernate.query.Query; import org.hibernate.query.Query;
import org.hibernate.Session;
import org.hibernate.test.jpa.AbstractJPATest;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.junit.After; import org.hibernate.orm.test.jpa.model.AbstractJPATest;
import org.junit.Before; import org.junit.jupiter.api.AfterEach;
import org.junit.Test; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/** /**
* Tests using converters with the between construction. * Tests using converters with the between construction.
@ -51,7 +51,7 @@ import org.junit.Test;
public class ConvertBetweenTest extends AbstractJPATest { public class ConvertBetweenTest extends AbstractJPATest {
@Override @Override
public String[] getMappings() { public String[] getOrmXmlFiles() {
return new String[0]; return new String[0];
} }
@ -60,71 +60,62 @@ public class ConvertBetweenTest extends AbstractJPATest {
return new Class[] { Item.class }; return new Class[] { Item.class };
} }
@Before @BeforeEach
public void fillData() { public void fillData() {
final Session s = openSession(); inTransaction(
s.getTransaction().begin(); session -> {
final Item i0 = new Item(); final Item i0 = new Item();
i0.setPrice( new BigDecimal( "12.05" ) ); i0.setPrice( new BigDecimal( "12.05" ) );
i0.setQuantity( 10 ); i0.setQuantity( 10 );
s.persist( i0 ); session.persist( i0 );
final Item i1 = new Item(); final Item i1 = new Item();
i1.setPrice( new BigDecimal( "5.35" ) ); i1.setPrice( new BigDecimal( "5.35" ) );
i1.setQuantity( 5 ); i1.setQuantity( 5 );
s.persist( i1 ); session.persist( i1 );
final Item i2 = new Item(); final Item i2 = new Item();
i2.setPrice( new BigDecimal( "99.99" ) ); i2.setPrice( new BigDecimal( "99.99" ) );
i2.setQuantity( 15 ); i2.setQuantity( 15 );
s.persist( i2 ); session.persist( i2 );
}
s.getTransaction().commit(); );
s.close();
} }
@After @AfterEach
public void cleanUpData() { public void cleanUpData() {
final Session s = openSession(); inTransaction(
s.getTransaction().begin(); session ->
session.createQuery( "delete from Item" ).executeUpdate()
s.createQuery( "delete from Item" ).executeUpdate(); );
s.getTransaction().commit();
s.close();
} }
@Test @Test
@TestForIssue( jiraKey = "HHH-9356" ) @TestForIssue(jiraKey = "HHH-9356")
public void testBetweenLiteral() { public void testBetweenLiteral() {
final Session s = openSession(); inTransaction(
s.getTransaction().begin(); session -> {
@SuppressWarnings("unchecked") final List<Item> result = session.createQuery(
@SuppressWarnings("unchecked") "select i from Item i where quantity between 9 and 11" ).list();
final List<Item> result = s.createQuery( "select i from Item i where quantity between 9 and 11" ).list();
assertEquals( 1, result.size() ); assertEquals( 1, result.size() );
assertEquals( 10, result.get( 0 ).getQuantity().intValue() ); assertEquals( 10, result.get( 0 ).getQuantity().intValue() );
}
s.getTransaction().commit(); );
s.close();
} }
@Test @Test
public void testBetweenParameters() { public void testBetweenParameters() {
final Session s = openSession(); inTransaction(
s.getTransaction().begin(); session -> {
final Query query = session.createQuery(
final Query query = s.createQuery( "select i from Item i where quantity between :low and :high" ); "select i from Item i where quantity between :low and :high" );
query.setParameter( "low", 9 ); query.setParameter( "low", 9 );
query.setParameter( "high", 11 ); query.setParameter( "high", 11 );
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked") final List<Item> result = query.list();
final List<Item> result = query.list();
assertEquals( 1, result.size() ); assertEquals( 1, result.size() );
assertEquals( 10, result.get( 0 ).getQuantity().intValue() ); assertEquals( 10, result.get( 0 ).getQuantity().intValue() );
}
s.getTransaction().commit(); );
s.close();
} }
} }

View File

@ -4,77 +4,85 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.hql; package org.hibernate.orm.test.hql;
import static org.assertj.core.api.Assertions.assertThat;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.query.Query; import org.hibernate.query.Query;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import org.hibernate.testing.orm.junit.DomainModel;
import org.junit.Before; import org.hibernate.testing.orm.junit.SessionFactory;
import org.junit.Test; import org.hibernate.testing.orm.junit.SessionFactoryScope;
public class DeleteWhereFunctionCallTest extends BaseCoreFunctionalTestCase { import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@Override import jakarta.persistence.Entity;
protected Class[] getAnnotatedClasses() { import jakarta.persistence.GeneratedValue;
return new Class[] { import jakarta.persistence.Id;
SuperType.class,
SubType.class import static org.assertj.core.api.Assertions.assertThat;
};
@DomainModel(
annotatedClasses = {
DeleteWhereFunctionCallTest.SuperType.class,
DeleteWhereFunctionCallTest.SubType.class
} }
)
@SessionFactory
public class DeleteWhereFunctionCallTest {
@Override @BeforeEach
protected boolean isCleanupTestDataRequired() { public void initData(SessionFactoryScope scope) {
return true; scope.inTransaction( s -> {
}
@Before
public void initData() {
inTransaction( s -> {
s.persist( new SuperType( -1 ) ); s.persist( new SuperType( -1 ) );
s.persist( new SubType( -2 ) ); s.persist( new SubType( -2 ) );
} ); } );
} }
@AfterEach
public void tearDown(SessionFactoryScope scope){
scope.inTransaction(
session -> {
session.createQuery( "delete from supert" ).executeUpdate();
session.createQuery( "delete from subt" ).executeUpdate();
}
);
}
@Test @Test
@TestForIssue(jiraKey = "HHH-14814") @TestForIssue(jiraKey = "HHH-14814")
public void testDeleteWhereTypeFunctionCall() { public void testDeleteWhereTypeFunctionCall(SessionFactoryScope scope) {
inTransaction( s -> { scope.inTransaction( s -> {
assertThat( count( s, SuperType.class ) ).isEqualTo( 2 ); assertThat( count( s, SuperType.class ) ).isEqualTo( 2 );
assertThat( count( s, SubType.class ) ).isEqualTo( 1 ); assertThat( count( s, SubType.class ) ).isEqualTo( 1 );
} ); } );
inTransaction( s -> { scope.inTransaction( s -> {
Query<?> query = s.createQuery( "delete from " + SuperType.class.getName() + " e" Query<?> query = s.createQuery( "delete from " + SuperType.class.getName() + " e"
+ " where type( e ) = :type" ); + " where type( e ) = :type" );
query.setParameter( "type", SuperType.class ); query.setParameter( "type", SuperType.class );
query.executeUpdate(); query.executeUpdate();
} ); } );
inTransaction( s -> { scope.inTransaction( s -> {
assertThat( count( s, SuperType.class ) ).isEqualTo( 1 ); assertThat( count( s, SuperType.class ) ).isEqualTo( 1 );
assertThat( count( s, SubType.class ) ).isEqualTo( 1 ); assertThat( count( s, SubType.class ) ).isEqualTo( 1 );
} ); } );
} }
@Test @Test
public void testDeleteWhereAbsFunctionCall() { public void testDeleteWhereAbsFunctionCall(SessionFactoryScope scope) {
inTransaction( s -> { scope.inTransaction( s -> {
assertThat( count( s, SuperType.class ) ).isEqualTo( 2 ); assertThat( count( s, SuperType.class ) ).isEqualTo( 2 );
assertThat( count( s, SubType.class ) ).isEqualTo( 1 ); assertThat( count( s, SubType.class ) ).isEqualTo( 1 );
} ); } );
inTransaction( s -> { scope.inTransaction( s -> {
Query<?> query = s.createQuery( "delete from " + SuperType.class.getName() + " e" Query<?> query = s.createQuery( "delete from " + SuperType.class.getName() + " e"
+ " where abs( e.someNumber ) = :number" ); + " where abs( e.someNumber ) = :number" );
query.setParameter( "number", 2 ); query.setParameter( "number", 2 );
query.executeUpdate(); query.executeUpdate();
} ); } );
inTransaction( s -> { scope.inTransaction( s -> {
assertThat( count( s, SuperType.class ) ).isEqualTo( 1 ); assertThat( count( s, SuperType.class ) ).isEqualTo( 1 );
assertThat( count( s, SubType.class ) ).isEqualTo( 0 ); assertThat( count( s, SubType.class ) ).isEqualTo( 0 );
} ); } );

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.joinfetch.enhanced; package org.hibernate.orm.test.joinfetch.enhanced;
import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; import static org.hibernate.testing.transaction.TransactionUtil.doInJPA;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;

View File

@ -0,0 +1,73 @@
/*
* 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.orm.test.jpa;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.engine.spi.PersistenceContext;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.metamodel.MappingMetamodel;
import org.hibernate.metamodel.spi.MetamodelImplementor;
import org.hibernate.query.spi.QueryEngine;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.spi.SessionFactoryServiceRegistry;
import org.hibernate.testing.orm.junit.EntityManagerFactoryBasedFunctionalTest;
import org.junit.jupiter.api.Test;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.metamodel.Metamodel;
/**
* @author Chris Cranford
*/
public class EntityManagerUnwrapTest extends EntityManagerFactoryBasedFunctionalTest {
@Test
public void testUnwrapSession() {
final EntityManagerFactory entityManagerFactory = entityManagerFactoryScope().getEntityManagerFactory();
final EntityManager entityManager = entityManagerFactory.createEntityManager();
try {
entityManager.unwrap( Session.class );
entityManager.unwrap( SessionImplementor.class );
entityManager.unwrap( SharedSessionContractImplementor.class );
entityManager.unwrap( PersistenceContext.class );
}
finally {
entityManager.close();
}
}
@Test
public void testUnwrapSessionFactory() {
final EntityManagerFactory entityManagerFactory = entityManagerFactory();
entityManagerFactory.unwrap( SessionFactory.class );
entityManagerFactory.unwrap( SessionFactoryImplementor.class );
entityManagerFactory.unwrap( SessionFactoryServiceRegistry.class );
entityManagerFactory.unwrap( ServiceRegistry.class );
entityManagerFactory.unwrap( JdbcServices.class );
entityManagerFactory.unwrap( jakarta.persistence.Cache.class );
entityManagerFactory.unwrap( org.hibernate.Cache.class );
entityManagerFactory.unwrap( jakarta.persistence.metamodel.Metamodel.class );
entityManagerFactory.unwrap( Metamodel.class );
entityManagerFactory.unwrap( MetamodelImplementor.class );
entityManagerFactory.unwrap( MappingMetamodel.class );
entityManagerFactory.unwrap( QueryEngine.class );
}
}

View File

@ -4,17 +4,16 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.jpa.cascade; package org.hibernate.orm.test.jpa.cascade2;
import org.jboss.logging.Logger;
import org.junit.Test;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.TransientObjectException; import org.hibernate.TransientObjectException;
import org.hibernate.test.jpa.AbstractJPATest;
import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; import org.hibernate.orm.test.jpa.model.AbstractJPATest;
import static org.junit.Assert.fail; import org.junit.jupiter.api.Test;
import static org.hibernate.testing.orm.junit.ExtraAssertions.assertTyping;
import static org.junit.jupiter.api.Assertions.fail;
/** /**
* According to the JPA spec, persist()ing an entity should throw an exception * According to the JPA spec, persist()ing an entity should throw an exception
@ -31,8 +30,9 @@ import static org.junit.Assert.fail;
*/ */
public class CascadeTest extends AbstractJPATest { public class CascadeTest extends AbstractJPATest {
public String[] getMappings() { @Override
return new String[] { "jpa/cascade/ParentChild.hbm.xml" }; protected String[] getOrmXmlFiles() {
return new String[] { "org/hibernate/orm/test/jpa/cascade2/ParentChild.hbm.xml" };
} }
@Test @Test
@ -40,24 +40,24 @@ public class CascadeTest extends AbstractJPATest {
// NOTES: Child defines a many-to-one back to its Parent. This // NOTES: Child defines a many-to-one back to its Parent. This
// association does not define persist cascading (which is natural; // association does not define persist cascading (which is natural;
// a child should not be able to create its parent). // a child should not be able to create its parent).
try { try (Session s = sessionFactory().openSession()) {
Session s = openSession();
s.beginTransaction(); s.beginTransaction();
try {
Parent p = new Parent( "parent" ); Parent p = new Parent( "parent" );
Child c = new Child( "child" ); Child c = new Child( "child" );
c.setParent( p ); c.setParent( p );
s.save( c ); s.save( c );
try {
s.getTransaction().commit(); s.getTransaction().commit();
fail( "expecting TransientObjectException on flush" ); fail( "expecting TransientObjectException on flush" );
} }
catch (IllegalStateException e) { catch (IllegalStateException e) {
assertTyping( TransientObjectException.class, e.getCause() ); assertTyping( TransientObjectException.class, e.getCause() );
log.trace( "handled expected exception", e );
s.getTransaction().rollback(); s.getTransaction().rollback();
} }
finally { finally {
s.close(); if ( s.getTransaction().isActive() ) {
s.getTransaction().rollback();
}
} }
} }
finally { finally {
@ -69,24 +69,25 @@ public class CascadeTest extends AbstractJPATest {
// NOTES: Child defines a many-to-one back to its Parent. This // NOTES: Child defines a many-to-one back to its Parent. This
// association does not define persist cascading (which is natural; // association does not define persist cascading (which is natural;
// a child should not be able to create its parent). // a child should not be able to create its parent).
try (Session s = sessionFactory().openSession()) {
try { try {
Session s = openSession();
s.beginTransaction(); s.beginTransaction();
Parent p = new Parent( "parent" ); Parent p = new Parent( "parent" );
Child c = new Child( "child" ); Child c = new Child( "child" );
c.setParent( p ); c.setParent( p );
s.persist( c ); s.persist( c );
try {
s.getTransaction().commit(); s.getTransaction().commit();
fail( "expecting TransientObjectException on flush" ); fail( "expecting TransientObjectException on flush" );
} }
catch( TransientObjectException e ) { catch (TransientObjectException e) {
// expected result // expected result
log.trace( "handled expected exception", e );
s.getTransaction().rollback(); s.getTransaction().rollback();
} }
finally { finally {
s.close(); if ( s.getTransaction().isActive() ) {
s.getTransaction().rollback();
}
} }
} }
finally { finally {
@ -98,24 +99,25 @@ public class CascadeTest extends AbstractJPATest {
// NOTES: Child defines a many-to-one back to its Parent. This // NOTES: Child defines a many-to-one back to its Parent. This
// association does not define persist cascading (which is natural; // association does not define persist cascading (which is natural;
// a child should not be able to create its parent). // a child should not be able to create its parent).
try { try (Session s = sessionFactory().openSession()) {
Session s = openSession();
s.beginTransaction(); s.beginTransaction();
ParentAssigned p = new ParentAssigned( new Long( 1 ), "parent" ); try {
ChildAssigned c = new ChildAssigned( new Long( 2 ), "child" ); ParentAssigned p = new ParentAssigned( 1L, "parent" );
ChildAssigned c = new ChildAssigned( 2L, "child" );
c.setParent( p ); c.setParent( p );
s.persist( c ); s.persist( c );
try {
s.getTransaction().commit(); s.getTransaction().commit();
fail( "expecting TransientObjectException on flush" ); fail( "expecting TransientObjectException on flush" );
} }
catch( TransientObjectException e ) { catch (TransientObjectException e) {
// expected result // expected result
log.trace( "handled expected exception", e );
s.getTransaction().rollback(); s.getTransaction().rollback();
} }
finally { finally {
s.close(); if ( s.getTransaction().isActive() ) {
s.getTransaction().rollback();
}
} }
} }
finally { finally {
@ -124,25 +126,26 @@ public class CascadeTest extends AbstractJPATest {
} }
public void testOneToOneGeneratedIds() { public void testOneToOneGeneratedIds() {
try (Session s = sessionFactory().openSession()) {
try { try {
Session s = openSession();
s.beginTransaction(); s.beginTransaction();
Parent p = new Parent( "parent" ); Parent p = new Parent( "parent" );
ParentInfo info = new ParentInfo( "xyz" ); ParentInfo info = new ParentInfo( "xyz" );
p.setInfo( info ); p.setInfo( info );
info.setOwner( p ); info.setOwner( p );
s.persist( p ); s.persist( p );
try {
s.getTransaction().commit(); s.getTransaction().commit();
fail( "expecting TransientObjectException on flush" ); fail( "expecting TransientObjectException on flush" );
} }
catch( TransientObjectException e ) { catch (TransientObjectException e) {
// expected result // expected result
log.trace( "handled expected exception", e );
s.getTransaction().rollback(); s.getTransaction().rollback();
} }
finally { finally {
s.close(); if ( s.getTransaction().isActive() ) {
s.getTransaction().rollback();
}
} }
} }
finally { finally {
@ -151,25 +154,26 @@ public class CascadeTest extends AbstractJPATest {
} }
public void testOneToOneAssignedIds() { public void testOneToOneAssignedIds() {
try (Session s = sessionFactory().openSession()) {
try { try {
Session s = openSession();
s.beginTransaction(); s.beginTransaction();
ParentAssigned p = new ParentAssigned( new Long( 1 ), "parent" ); ParentAssigned p = new ParentAssigned( 1L, "parent" );
ParentInfoAssigned info = new ParentInfoAssigned( "something secret" ); ParentInfoAssigned info = new ParentInfoAssigned( "something secret" );
p.setInfo( info ); p.setInfo( info );
info.setOwner( p ); info.setOwner( p );
s.persist( p ); s.persist( p );
try {
s.getTransaction().commit(); s.getTransaction().commit();
fail( "expecting TransientObjectException on flush" ); fail( "expecting TransientObjectException on flush" );
} }
catch( TransientObjectException e ) { catch (TransientObjectException e) {
// expected result // expected result
log.trace( "handled expected exception", e );
s.getTransaction().rollback(); s.getTransaction().rollback();
} }
finally { finally {
s.close(); if ( s.getTransaction().isActive() ) {
s.getTransaction().rollback();
}
} }
} }
finally { finally {
@ -178,8 +182,7 @@ public class CascadeTest extends AbstractJPATest {
} }
public void testManyToOnePropertyRefGeneratedIds() { public void testManyToOnePropertyRefGeneratedIds() {
try { try (Session s = sessionFactory().openSession()) {
Session s = openSession();
s.beginTransaction(); s.beginTransaction();
Parent p = new Parent( "parent" ); Parent p = new Parent( "parent" );
Other other = new Other(); Other other = new Other();
@ -189,13 +192,14 @@ public class CascadeTest extends AbstractJPATest {
s.getTransaction().commit(); s.getTransaction().commit();
fail( "expecting TransientObjectException on flush" ); fail( "expecting TransientObjectException on flush" );
} }
catch( TransientObjectException e ) { catch (TransientObjectException e) {
// expected result // expected result
log.trace( "handled expected exception", e );
s.getTransaction().rollback(); s.getTransaction().rollback();
} }
finally { finally {
s.close(); if ( s.getTransaction().isActive() ) {
s.getTransaction().rollback();
}
} }
} }
finally { finally {
@ -204,24 +208,24 @@ public class CascadeTest extends AbstractJPATest {
} }
public void testManyToOnePropertyRefAssignedIds() { public void testManyToOnePropertyRefAssignedIds() {
try { try (Session s = sessionFactory().openSession()) {
Session s = openSession();
s.beginTransaction(); s.beginTransaction();
ParentAssigned p = new ParentAssigned( new Long( 1 ), "parent" ); ParentAssigned p = new ParentAssigned( 1L, "parent" );
OtherAssigned other = new OtherAssigned( new Long( 2 ) ); OtherAssigned other = new OtherAssigned( 2L );
other.setOwner( p ); other.setOwner( p );
s.persist( other ); s.persist( other );
try { try {
s.getTransaction().commit(); s.getTransaction().commit();
fail( "expecting TransientObjectException on flush" ); fail( "expecting TransientObjectException on flush" );
} }
catch( TransientObjectException e ) { catch (TransientObjectException e) {
// expected result // expected result
log.trace( "handled expected exception", e );
s.getTransaction().rollback(); s.getTransaction().rollback();
} }
finally { finally {
s.close(); if ( s.getTransaction().isActive() ) {
s.getTransaction().rollback();
}
} }
} }
finally { finally {
@ -230,8 +234,7 @@ public class CascadeTest extends AbstractJPATest {
} }
public void testOneToOnePropertyRefGeneratedIds() { public void testOneToOnePropertyRefGeneratedIds() {
try { try (Session s = sessionFactory().openSession()) {
Session s = openSession();
s.beginTransaction(); s.beginTransaction();
Child c2 = new Child( "c2" ); Child c2 = new Child( "c2" );
ChildInfo info = new ChildInfo( "blah blah blah" ); ChildInfo info = new ChildInfo( "blah blah blah" );
@ -242,13 +245,14 @@ public class CascadeTest extends AbstractJPATest {
s.getTransaction().commit(); s.getTransaction().commit();
fail( "expecting TransientObjectException on flush" ); fail( "expecting TransientObjectException on flush" );
} }
catch( TransientObjectException e ) { catch (TransientObjectException e) {
// expected result // expected result
log.trace( "handled expected exception : " + e );
s.getTransaction().rollback(); s.getTransaction().rollback();
} }
finally { finally {
s.close(); if ( s.getTransaction().isActive() ) {
s.getTransaction().rollback();
}
} }
} }
finally { finally {
@ -257,11 +261,10 @@ public class CascadeTest extends AbstractJPATest {
} }
public void testOneToOnePropertyRefAssignedIds() { public void testOneToOnePropertyRefAssignedIds() {
try { try (Session s = sessionFactory().openSession()) {
Session s = openSession();
s.beginTransaction(); s.beginTransaction();
ChildAssigned c2 = new ChildAssigned( new Long( 3 ), "c3" ); ChildAssigned c2 = new ChildAssigned( 3L, "c3" );
ChildInfoAssigned info = new ChildInfoAssigned( new Long( 4 ), "blah blah blah" ); ChildInfoAssigned info = new ChildInfoAssigned( 4L, "blah blah blah" );
c2.setInfo( info ); c2.setInfo( info );
info.setOwner( c2 ); info.setOwner( c2 );
s.persist( c2 ); s.persist( c2 );
@ -269,13 +272,14 @@ public class CascadeTest extends AbstractJPATest {
s.getTransaction().commit(); s.getTransaction().commit();
fail( "expecting TransientObjectException on flush" ); fail( "expecting TransientObjectException on flush" );
} }
catch( TransientObjectException e ) { catch (TransientObjectException e) {
// expected result // expected result
log.trace( "handled expected exception : " + e );
s.getTransaction().rollback(); s.getTransaction().rollback();
} }
finally { finally {
s.close(); if ( s.getTransaction().isActive() ) {
s.getTransaction().rollback();
}
} }
} }
finally { finally {
@ -285,29 +289,16 @@ public class CascadeTest extends AbstractJPATest {
private void cleanupData() { private void cleanupData() {
Session s = null; inTransaction(
try { s -> {
s = openSession();
s.beginTransaction();
s.createQuery( "delete ChildInfoAssigned" ).executeUpdate(); s.createQuery( "delete ChildInfoAssigned" ).executeUpdate();
s.createQuery( "delete ChildAssigned" ).executeUpdate(); s.createQuery( "delete ChildAssigned" ).executeUpdate();
s.createQuery( "delete ParentAssigned" ).executeUpdate(); s.createQuery( "delete ParentAssigned" ).executeUpdate();
s.createQuery( "delete ChildInfoAssigned" ).executeUpdate(); s.createQuery( "delete ChildInfoAssigned" ).executeUpdate();
s.createQuery( "delete ChildAssigned" ).executeUpdate(); s.createQuery( "delete ChildAssigned" ).executeUpdate();
s.createQuery( "delete ParentAssigned" ).executeUpdate(); s.createQuery( "delete ParentAssigned" ).executeUpdate();
s.getTransaction().commit();
}
catch( Throwable t ) {
log.warn( "unable to cleanup test data : " + t );
}
finally {
if ( s != null ) {
try {
s.close();
}
catch( Throwable ignore ) {
}
}
} }
);
} }
} }

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.jpa.cascade; package org.hibernate.orm.test.jpa.cascade2;
/** /**

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.jpa.cascade; package org.hibernate.orm.test.jpa.cascade2;
/** /**

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.jpa.cascade; package org.hibernate.orm.test.jpa.cascade2;
/** /**

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.jpa.cascade; package org.hibernate.orm.test.jpa.cascade2;
/** /**

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.jpa.cascade; package org.hibernate.orm.test.jpa.cascade2;
/** /**

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.jpa.cascade; package org.hibernate.orm.test.jpa.cascade2;
/** /**

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.jpa.cascade; package org.hibernate.orm.test.jpa.cascade2;
/** /**

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.jpa.cascade; package org.hibernate.orm.test.jpa.cascade2;
/** /**

View File

@ -8,7 +8,7 @@
"-//Hibernate/Hibernate Mapping DTD 3.0//EN" "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.hibernate.test.jpa.cascade" default-access="field"> <hibernate-mapping package="org.hibernate.orm.test.jpa.cascade2" default-access="field">
<!-- +++++++++++++ Generated ids ++++++++++++++++++++++ --> <!-- +++++++++++++ Generated ids ++++++++++++++++++++++ -->

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.jpa.cascade; package org.hibernate.orm.test.jpa.cascade2;
/** /**

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.jpa.cascade; package org.hibernate.orm.test.jpa.cascade2;
/** /**

View File

@ -7,36 +7,39 @@
package org.hibernate.orm.test.jpa.compliance.tck2_2; package org.hibernate.orm.test.jpa.compliance.tck2_2;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query; import org.hibernate.query.Query;
import org.hibernate.test.jpa.AbstractJPATest; import org.hibernate.orm.test.jpa.model.AbstractJPATest;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.hamcrest.CoreMatchers; import org.hamcrest.CoreMatchers;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.fail;
/** /**
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public class ClosedManagerTests extends AbstractJPATest { public class ClosedManagerTests extends AbstractJPATest {
@Override @Override
public void configure(Configuration cfg) { protected void applySettings(StandardServiceRegistryBuilder builder) {
super.configure( cfg ); super.applySettings( builder );
cfg.setProperty( AvailableSettings.JPA_CLOSED_COMPLIANCE, "true" ); builder.applySetting( AvailableSettings.JPA_CLOSED_COMPLIANCE, "true" );
} }
@Test @Test
public void testQuerySetMaxResults() { public void testQuerySetMaxResults() {
final Session session = sessionFactory().openSession(); final Session session = sessionFactory().openSession();
final Query qry;
final Query qry = session.createQuery( "select i from Item i" ); try {
qry = session.createQuery( "select i from Item i" );
}
finally {
session.close(); session.close();
assertThat( session.isOpen(), CoreMatchers.is ( false ) ); }
assertThat( session.isOpen(), CoreMatchers.is( false ) );
try { try {
qry.setMaxResults( 1 ); qry.setMaxResults( 1 );
@ -45,14 +48,18 @@ public class ClosedManagerTests extends AbstractJPATest {
catch (IllegalStateException expected) { catch (IllegalStateException expected) {
} }
} }
@Test @Test
public void testQuerySetFirstResult() { public void testQuerySetFirstResult() {
final Session session = sessionFactory().openSession(); final Session session = sessionFactory().openSession();
final Query qry;
final Query qry = session.createQuery( "select i from Item i" ); try {
qry = session.createQuery( "select i from Item i" );
}
finally {
session.close(); session.close();
assertThat( session.isOpen(), CoreMatchers.is ( false ) ); }
assertThat( session.isOpen(), CoreMatchers.is( false ) );
try { try {
qry.setFirstResult( 1 ); qry.setFirstResult( 1 );
@ -65,11 +72,15 @@ public class ClosedManagerTests extends AbstractJPATest {
@Test @Test
public void testQuerySetPositionalParameter() { public void testQuerySetPositionalParameter() {
final Session session = sessionFactory().openSession(); final Session session = sessionFactory().openSession();
final Query qry;
final Query qry = session.createQuery( "select i from Item i where i.id = ?1" ); try {
qry = session.createQuery( "select i from Item i where i.id = ?1" );
}
finally {
session.close(); session.close();
assertThat( session.isOpen(), CoreMatchers.is ( false ) );
}
assertThat( session.isOpen(), CoreMatchers.is( false ) );
try { try {
qry.setParameter( 1, 1 ); qry.setParameter( 1, 1 );
@ -83,10 +94,14 @@ public class ClosedManagerTests extends AbstractJPATest {
public void testQuerySetNamedParameter() { public void testQuerySetNamedParameter() {
final Session session = sessionFactory().openSession(); final Session session = sessionFactory().openSession();
final Query qry = session.createQuery( "select i from Item i where i.id = :id" ); final Query qry;
try {
qry = session.createQuery( "select i from Item i where i.id = :id" );
}
finally {
session.close(); session.close();
assertThat( session.isOpen(), CoreMatchers.is ( false ) ); }
assertThat( session.isOpen(), CoreMatchers.is( false ) );
try { try {
qry.setParameter( "id", 1 ); qry.setParameter( "id", 1 );
@ -100,11 +115,15 @@ public class ClosedManagerTests extends AbstractJPATest {
public void testQueryGetPositionalParameter() { public void testQueryGetPositionalParameter() {
final Session session = sessionFactory().openSession(); final Session session = sessionFactory().openSession();
final Query qry = session.createQuery( "select i from Item i where i.id = ?1" ); final Query qry;
try {
qry = session.createQuery( "select i from Item i where i.id = ?1" );
qry.setParameter( 1, 1 ); qry.setParameter( 1, 1 );
}
finally {
session.close(); session.close();
assertThat( session.isOpen(), CoreMatchers.is ( false ) ); }
assertThat( session.isOpen(), CoreMatchers.is( false ) );
try { try {
qry.getParameter( 1 ); qry.getParameter( 1 );
@ -125,11 +144,15 @@ public class ClosedManagerTests extends AbstractJPATest {
public void testQueryGetNamedParameter() { public void testQueryGetNamedParameter() {
final Session session = sessionFactory().openSession(); final Session session = sessionFactory().openSession();
final Query qry = session.createQuery( "select i from Item i where i.id = :id" ); final Query qry;
try {
qry = session.createQuery( "select i from Item i where i.id = :id" );
qry.setParameter( "id", 1 ); qry.setParameter( "id", 1 );
}
finally {
session.close(); session.close();
assertThat( session.isOpen(), CoreMatchers.is ( false ) ); }
assertThat( session.isOpen(), CoreMatchers.is( false ) );
try { try {
qry.getParameter( "id" ); qry.getParameter( "id" );

View File

@ -6,13 +6,12 @@
*/ */
package org.hibernate.orm.test.jpa.compliance.tck2_2; package org.hibernate.orm.test.jpa.compliance.tck2_2;
import jakarta.persistence.Parameter;
import org.hibernate.query.Query; import org.hibernate.query.Query;
import org.hibernate.testing.transaction.TransactionUtil2; import org.hibernate.orm.test.jpa.model.AbstractJPATest;
import org.hibernate.test.jpa.AbstractJPATest; import org.junit.jupiter.api.Test;
import org.junit.Test;
import jakarta.persistence.Parameter;
import static org.hamcrest.CoreMatchers.either; import static org.hamcrest.CoreMatchers.either;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
@ -23,15 +22,15 @@ import static org.hamcrest.MatcherAssert.assertThat;
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public class JpaPositionalParameterTest extends AbstractJPATest { public class JpaPositionalParameterTest extends AbstractJPATest {
@Test @Test
public void testPositionalParameters() { public void testPositionalParameters() {
TransactionUtil2.inTransaction( inTransaction(
sessionFactory(),
session -> { session -> {
Query query = session.createQuery( "select i from Item i where name = ?1 or name = ?2" ); Query query = session.createQuery( "select i from Item i where name = ?1 or name = ?2" );
for ( Parameter<?> parameter : query.getParameters() ) { for ( Parameter<?> parameter : query.getParameters() ) {
assertThat( parameter.getPosition(), notNullValue() ); assertThat( parameter.getPosition(), notNullValue() );
assertThat( parameter.getPosition(), either( is(1) ).or( is(2) ) ); assertThat( parameter.getPosition(), either( is( 1 ) ).or( is( 2 ) ) );
} }
} }
); );

View File

@ -6,27 +6,34 @@
*/ */
package org.hibernate.orm.test.jpa.compliance.tck2_2; package org.hibernate.orm.test.jpa.compliance.tck2_2;
import jakarta.persistence.LockModeType; import org.hibernate.orm.test.jpa.model.AbstractJPATest;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.hibernate.test.jpa.AbstractJPATest; import jakarta.persistence.LockModeType;
import org.junit.Test;
/** /**
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public class NonSelectQueryLockMode extends AbstractJPATest { public class NonSelectQueryLockMode extends AbstractJPATest {
@Test( expected = IllegalStateException.class ) @Test
public void testNonSelectQueryGetLockMode() { public void testNonSelectQueryGetLockMode() {
inTransaction( Assertions.assertThrows(
IllegalStateException.class,
() -> inTransaction(
session -> session.createQuery( "delete Item" ).getLockMode() session -> session.createQuery( "delete Item" ).getLockMode()
)
); );
} }
@Test( expected = IllegalStateException.class ) @Test
public void testNonSelectQuerySetLockMode() { public void testNonSelectQuerySetLockMode() {
inTransaction( Assertions.assertThrows(
IllegalStateException.class,
() -> inTransaction(
session -> session.createQuery( "delete Item" ).setLockMode( LockModeType.PESSIMISTIC_WRITE ) session -> session.createQuery( "delete Item" ).setLockMode( LockModeType.PESSIMISTIC_WRITE )
)
); );
} }
} }

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.jpa.convert; package org.hibernate.orm.test.jpa.convert;
import java.sql.Date; import java.sql.Date;
import java.sql.Time; import java.sql.Time;
@ -13,6 +13,11 @@ import java.time.LocalDate;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.LocalTime; import java.time.LocalTime;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.orm.junit.EntityManagerFactoryScope;
import org.hibernate.testing.orm.junit.Jpa;
import org.junit.jupiter.api.Test;
import jakarta.persistence.AttributeConverter; import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.persistence.Convert; import jakarta.persistence.Convert;
@ -20,32 +25,25 @@ import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue; import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id; import jakarta.persistence.Id;
import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
import org.hibernate.testing.TestForIssue;
import static org.hibernate.testing.transaction.TransactionUtil.doInJPA;
import static org.junit.Assert.assertEquals;
/** /**
* @author Chris Cranford * @author Chris Cranford
*/ */
public class JdbcTypeConverterTest extends BaseEntityManagerFunctionalTestCase { @Jpa(
@Override annotatedClasses = JdbcTypeConverterTest.JavaTimeBean.class
protected Class<?>[] getAnnotatedClasses() { )
return new Class<?>[] { JavaTimeBean.class }; public class JdbcTypeConverterTest {
}
@Test @Test
@TestForIssue(jiraKey = "HHH-12586") @TestForIssue(jiraKey = "HHH-12586")
public void testJava8TimeObjectsUsingJdbcSqlTypeDescriptors() { public void testJava8TimeObjectsUsingJdbcSqlTypeDescriptors(EntityManagerFactoryScope scope) {
// Because some databases do not support millisecond values in timestamps, we clear it here. // Because some databases do not support millisecond values in timestamps, we clear it here.
// This will serve sufficient for our test to verify that the retrieved values match persisted. // This will serve sufficient for our test to verify that the retrieved values match persisted.
LocalDateTime now = LocalDateTime.now().withNano( 0 ); LocalDateTime now = LocalDateTime.now().withNano( 0 );
// persist the record. // persist the record.
Integer rowId = doInJPA( this::entityManagerFactory, entityManager -> { Integer rowId = scope.fromTransaction( entityManager -> {
JavaTimeBean javaTime = new JavaTimeBean(); JavaTimeBean javaTime = new JavaTimeBean();
javaTime.setLocalDate( now.toLocalDate() ); javaTime.setLocalDate( now.toLocalDate() );
javaTime.setLocalTime( now.toLocalTime() ); javaTime.setLocalTime( now.toLocalTime() );
@ -55,7 +53,7 @@ public class JdbcTypeConverterTest extends BaseEntityManagerFunctionalTestCase {
} ); } );
// retrieve the record and verify values. // retrieve the record and verify values.
doInJPA( this::entityManagerFactory, entityManager -> { scope.inTransaction( entityManager -> {
final JavaTimeBean javaTime = entityManager.find( JavaTimeBean.class, rowId ); final JavaTimeBean javaTime = entityManager.find( JavaTimeBean.class, rowId );
assertEquals( now.toLocalDate(), javaTime.getLocalDate() ); assertEquals( now.toLocalDate(), javaTime.getLocalDate() );
assertEquals( now.toLocalTime(), javaTime.getLocalTime() ); assertEquals( now.toLocalTime(), javaTime.getLocalTime() );
@ -74,7 +72,7 @@ public class JdbcTypeConverterTest extends BaseEntityManagerFunctionalTestCase {
private LocalDate localDate; private LocalDate localDate;
@Convert(converter = LocalTimeToTimeConverter.class) @Convert(converter = LocalTimeToTimeConverter.class)
@Column(name = "LTIME" ) @Column(name = "LTIME")
private LocalTime localTime; private LocalTime localTime;
@Convert(converter = LocalDateTimeToTimestampConverter.class) @Convert(converter = LocalDateTimeToTimestampConverter.class)

View File

@ -24,4 +24,4 @@
/** /**
* Package for testing JPA converters and the {@link jakarta.persistence.Convert @Convert} annotation. * Package for testing JPA converters and the {@link jakarta.persistence.Convert @Convert} annotation.
*/ */
package org.hibernate.test.jpa.convert; package org.hibernate.orm.test.jpa.convert;

View File

@ -0,0 +1,86 @@
/*
* 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.orm.test.jpa.fetch;
import java.util.Date;
import org.hibernate.Hibernate;
import org.hibernate.orm.test.jpa.model.AbstractJPATest;
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.assertTrue;
/**
* @author Emmanuel Bernard
*/
public class FetchingTest extends AbstractJPATest {
@Override
public String[] getOrmXmlFiles() {
return new String[] { "org/hibernate/orm/test/jpa/fetch/Person.hbm.xml" };
}
@Test
public void testLazy() {
inTransaction(
session -> {
Person p = new Person( "Gavin", "King", "JBoss Inc" );
Stay stay = new Stay( p, new Date(), new Date(), "A380", "Blah", "Blah" );
p.addStay( stay );
session.persist( p );
session.getTransaction().commit();
session.clear();
session.beginTransaction();
p = (Person) session.createQuery( "select p from Person p where p.firstName = :name" )
.setParameter( "name", "Gavin" ).uniqueResult();
assertFalse( Hibernate.isInitialized( p.getStays() ) );
session.delete( p );
}
);
}
@Test
public void testHibernateFetchingLazy() {
inTransaction(
session -> {
Person p = new Person( "Gavin", "King", "JBoss Inc" );
Stay stay = new Stay( null, new Date(), new Date(), "A380", "Blah", "Blah" );
Stay stay2 = new Stay( null, new Date(), new Date(), "A320", "Blah", "Blah" );
Stay stay3 = new Stay( null, new Date(), new Date(), "A340", "Blah", "Blah" );
stay.setOldPerson( p );
stay2.setVeryOldPerson( p );
stay3.setVeryOldPerson( p );
p.addOldStay( stay );
p.addVeryOldStay( stay2 );
p.addVeryOldStay( stay3 );
session.persist( p );
session.getTransaction().commit();
session.clear();
session.beginTransaction();
p = (Person) session.createQuery( "select p from Person p where p.firstName = :name" )
.setParameter( "name", "Gavin" ).uniqueResult();
assertFalse( Hibernate.isInitialized( p.getOldStays() ) );
assertEquals( 1, p.getOldStays().size() );
assertFalse( Hibernate.isInitialized( p.getOldStays() ), "lazy extra is failing" );
session.clear();
stay = session.get( Stay.class, stay.getId() );
assertTrue( !Hibernate.isInitialized( stay.getOldPerson() ) );
session.clear();
stay3 = session.get( Stay.class, stay3.getId() );
assertTrue(
Hibernate.isInitialized( stay3.getVeryOldPerson() ),
"FetchMode.JOIN should overrides lazy options"
);
session.delete( stay3.getVeryOldPerson() );
}
);
}
}

View File

@ -8,7 +8,7 @@
"-//Hibernate/Hibernate Mapping DTD 3.0//EN" "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.hibernate.test.jpa.fetch"> <hibernate-mapping package="org.hibernate.orm.test.jpa.fetch">
<class name="Person" table="PERSON"> <class name="Person" table="PERSON">
<id name="id" column="ID" type="long"> <id name="id" column="ID" type="long">

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.jpa.fetch; package org.hibernate.orm.test.jpa.fetch;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.jpa.fetch; package org.hibernate.orm.test.jpa.fetch;
import java.io.Serializable; import java.io.Serializable;
import java.util.Date; import java.util.Date;

View File

@ -9,22 +9,23 @@ package org.hibernate.orm.test.jpa.lock;
import org.hibernate.LockMode; import org.hibernate.LockMode;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.Transaction; import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.SQLServerDialect; import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.orm.test.jpa.model.AbstractJPATest;
import org.hibernate.orm.test.jpa.model.Item;
import org.hibernate.orm.test.jpa.model.MyEntity;
import org.hibernate.testing.DialectChecks;
import org.hibernate.testing.RequiresDialectFeature;
import org.hibernate.test.jpa.AbstractJPATest;
import org.hibernate.test.jpa.Item;
import org.hibernate.test.jpa.MyEntity;
import org.hibernate.testing.jdbc.SQLServerSnapshotIsolationConnectionProvider; import org.hibernate.testing.jdbc.SQLServerSnapshotIsolationConnectionProvider;
import org.junit.Test; import org.hibernate.testing.orm.junit.DialectFeatureChecks;
import org.hibernate.testing.orm.junit.RequiresDialectFeature;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.fail;
/** /**
* Tests specifically relating to section 3.3.5.3 [Lock Modes] of the * Tests specifically relating to section 3.3.5.3 [Lock Modes] of the
@ -32,23 +33,23 @@ import static org.junit.Assert.fail;
* *
* @author Steve Ebersole * @author Steve Ebersole
*/ */
@RequiresDialectFeature( DialectChecks.DoesReadCommittedNotCauseWritersToBlockReadersCheck.class ) @RequiresDialectFeature(feature = DialectFeatureChecks.DoesReadCommittedNotCauseWritersToBlockReadersCheck.class)
public class JPALockTest extends AbstractJPATest { public class JPALockTest extends AbstractJPATest {
private SQLServerSnapshotIsolationConnectionProvider connectionProvider = new SQLServerSnapshotIsolationConnectionProvider(); private SQLServerSnapshotIsolationConnectionProvider connectionProvider = new SQLServerSnapshotIsolationConnectionProvider();
@Override @Override
public void configure(Configuration cfg) { protected void applySettings(StandardServiceRegistryBuilder builder) {
super.configure( cfg ); super.applySettings( builder );
if( SQLServerDialect.class.isAssignableFrom( DIALECT.getClass() )) { if ( SQLServerDialect.class.isAssignableFrom( DIALECT.getClass() ) ) {
connectionProvider.setConnectionProvider( (ConnectionProvider) cfg.getProperties().get( AvailableSettings.CONNECTION_PROVIDER ) ); connectionProvider.setConnectionProvider( (ConnectionProvider) builder.getSettings()
cfg.getProperties().put( AvailableSettings.CONNECTION_PROVIDER, connectionProvider ); .get( AvailableSettings.CONNECTION_PROVIDER ) );
builder.applySetting( AvailableSettings.CONNECTION_PROVIDER, connectionProvider );
} }
} }
@Override @AfterAll
protected void releaseSessionFactory() { protected void tearDown() {
super.releaseSessionFactory();
connectionProvider.stop(); connectionProvider.stop();
} }
@ -87,43 +88,73 @@ public class JPALockTest extends AbstractJPATest {
} }
final String initialName = "lock test"; final String initialName = "lock test";
// set up some test data // set up some test data
Session s1 = sessionFactory().openSession(); Item it = new Item();
Transaction t1 = s1.beginTransaction(); Long itemId = fromTransaction(
Item item = new Item(); session -> {
item.setName( initialName ); it.setName( initialName );
s1.save( item ); session.save( it );
t1.commit(); return it.getId();
s1.close(); }
);
Long itemId = item.getId();
Session s1 = null;
Session s2 = null;
Item item;
try {
// do the isolated update // do the isolated update
s1 = sessionFactory().openSession(); s1 = sessionFactory().openSession();
t1 = s1.beginTransaction(); s1.beginTransaction();
item = (Item) s1.get( Item.class, itemId ); item = s1.get( Item.class, itemId );
s1.lock( item, LockMode.UPGRADE ); s1.lock( item, LockMode.UPGRADE );
item.setName( "updated" ); item.setName( "updated" );
s1.flush(); s1.flush();
Session s2 = sessionFactory().openSession(); s2 = sessionFactory().openSession();
Transaction t2 = s2.beginTransaction(); Transaction t2 = s2.beginTransaction();
Item item2 = (Item) s2.get( Item.class, itemId ); Item item2 = s2.get( Item.class, itemId );
assertEquals( "isolation not maintained", initialName, item2.getName() ); assertEquals( initialName, item2.getName(), "isolation not maintained" );
t1.commit(); s1.getTransaction().commit();
s1.close(); s1.close();
item2 = (Item) s2.get( Item.class, itemId ); item2 = s2.get( Item.class, itemId );
assertEquals( "repeatable read not maintained", initialName, item2.getName() ); assertEquals( initialName, item2.getName(), "repeatable read not maintained" );
t2.commit(); t2.commit();
s2.close(); s2.close();
}
s1 = sessionFactory().openSession(); finally {
t1 = s1.beginTransaction(); if ( s1 != null ) {
s1.delete( item ); try {
t1.commit(); if ( s1.getTransaction().isActive() ) {
s1.getTransaction().rollback();
}
}
finally {
if ( s1.isOpen() ) {
s1.close(); s1.close();
} }
}
}
if ( s2 != null ) {
try {
if ( s2.getTransaction().isActive() ) {
s2.getTransaction().rollback();
}
}
finally {
if ( s2.isOpen() ) {
s2.close();
}
}
}
}
inTransaction(
session ->
session.delete( item )
);
}
/** /**
* Test the equivalent of EJB3 LockModeType.WRITE * Test the equivalent of EJB3 LockModeType.WRITE
@ -154,55 +185,59 @@ public class JPALockTest extends AbstractJPATest {
} }
final String initialName = "lock test"; final String initialName = "lock test";
// set up some test data // set up some test data
Session s1 = sessionFactory().openSession(); Item it = new Item();
Transaction t1 = s1.beginTransaction(); MyEntity entity = new MyEntity();
Item item = new Item(); inTransaction(
item.setName( initialName ); session -> {
s1.save( item ); it.setName( initialName );
MyEntity myEntity = new MyEntity(); session.save( it );
myEntity.setName( "Test" ); entity.setName( "Test" );
s1.save( myEntity ); session.save( entity );
t1.commit(); }
s1.close(); );
Long itemId = item.getId();
long initialVersion = item.getVersion();
Long itemId = it.getId();
long initialVersion = it.getVersion();
Session s1 = null;
Session s2 = null;
MyEntity myEntity;
Item item;
try {
s1 = sessionFactory().openSession(); s1 = sessionFactory().openSession();
t1 = s1.beginTransaction(); s1.beginTransaction();
item = (Item) s1.get( Item.class, itemId ); item = s1.get( Item.class, itemId );
s1.lock( item, LockMode.FORCE ); s1.lock( item, LockMode.FORCE );
assertEquals( "no forced version increment", initialVersion + 1, item.getVersion() ); assertEquals( initialVersion + 1, item.getVersion(), "no forced version increment" );
myEntity = (MyEntity) s1.get( MyEntity.class, myEntity.getId() ); myEntity = s1.get( MyEntity.class, entity.getId() );
s1.lock( myEntity, LockMode.FORCE ); s1.lock( myEntity, LockMode.FORCE );
assertTrue( "LockMode.FORCE on a un-versioned entity should degrade nicely to UPGRADE", true ); assertTrue( true, "LockMode.FORCE on a un-versioned entity should degrade nicely to UPGRADE" );
s1.lock( item, LockMode.FORCE ); s1.lock( item, LockMode.FORCE );
assertEquals( "subsequent LockMode.FORCE did not no-op", initialVersion + 1, item.getVersion() ); assertEquals( initialVersion + 1, item.getVersion(), "subsequent LockMode.FORCE did not no-op" );
Session s2 = sessionFactory().openSession(); s2 = sessionFactory().openSession();
Transaction t2 = s2.beginTransaction(); s2.beginTransaction();
Item item2 = (Item) s2.get( Item.class, itemId ); Item item2 = s2.get( Item.class, itemId );
assertEquals( "isolation not maintained", initialName, item2.getName() ); assertEquals( initialName, item2.getName(), "isolation not maintained" );
item.setName( "updated-1" ); item.setName( "updated-1" );
s1.flush(); s1.flush();
// currently an unfortunate side effect... // currently an unfortunate side effect...
assertEquals( initialVersion + 2, item.getVersion() ); assertEquals( initialVersion + 2, item.getVersion() );
t1.commit(); s1.getTransaction().commit();
s1.close(); s1.close();
item2.setName( "updated" ); item2.setName( "updated" );
try { try {
t2.commit(); s2.getTransaction().commit();
fail( "optimistic lock should have failed" ); fail( "optimistic lock should have failed" );
} }
catch (Throwable t) { catch (Throwable t) {
// expected behavior // expected behavior
try { try {
t2.rollback(); s2.getTransaction().rollback();
} }
catch (Throwable ignore) { catch (Throwable ignore) {
// ignore // ignore
@ -211,20 +246,40 @@ public class JPALockTest extends AbstractJPATest {
throw (AssertionError) t; throw (AssertionError) t;
} }
} }
finally {
try {
s2.close();
} }
catch (Throwable ignore) { finally {
// ignore if ( s1 != null ) {
try {
if ( s1.getTransaction().isActive() ) {
s1.getTransaction().rollback();
}
}
finally {
if ( s1.isOpen() ) {
s1.close();
}
} }
} }
s1 = sessionFactory().openSession(); if ( s2 != null ) {
t1 = s1.beginTransaction(); try {
s1.delete( item ); if ( s2.getTransaction().isActive() ) {
s1.delete( myEntity ); s2.getTransaction().rollback();
t1.commit(); }
s1.close(); }
finally {
if ( s2.isOpen() ) {
s2.close();
}
}
}
}
inTransaction(
session -> {
session.delete( item );
session.delete( myEntity );
}
);
} }
} }

View File

@ -7,47 +7,49 @@
package org.hibernate.orm.test.jpa.lock; package org.hibernate.orm.test.jpa.lock;
import java.util.Collections; import java.util.Collections;
import org.hibernate.LockOptions;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.orm.test.jpa.model.AbstractJPATest;
import org.hibernate.orm.test.jpa.model.Item;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.jdbc.SQLServerSnapshotIsolationConnectionProvider;
import org.hibernate.testing.orm.junit.DialectFeatureChecks;
import org.hibernate.testing.orm.junit.RequiresDialectFeature;
import org.hibernate.testing.transaction.TransactionUtil2;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import jakarta.persistence.LockModeType; import jakarta.persistence.LockModeType;
import jakarta.persistence.LockTimeoutException; import jakarta.persistence.LockTimeoutException;
import jakarta.persistence.PessimisticLockException; import jakarta.persistence.PessimisticLockException;
import org.hibernate.LockOptions; import static org.junit.jupiter.api.Assertions.fail;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
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.TestForIssue;
import org.hibernate.testing.jdbc.SQLServerSnapshotIsolationConnectionProvider;
import org.hibernate.testing.transaction.TransactionUtil2;
import org.hibernate.test.jpa.AbstractJPATest;
import org.hibernate.test.jpa.Item;
import org.junit.Test;
import static org.junit.Assert.fail;
/** /**
* @author Steve Ebersole * @author Steve Ebersole
*/ */
@RequiresDialectFeature(DialectChecks.SupportNoWait.class) @RequiresDialectFeature(feature = DialectFeatureChecks.SupportNoWait.class)
public class LockExceptionTests extends AbstractJPATest { public class LockExceptionTests extends AbstractJPATest {
private SQLServerSnapshotIsolationConnectionProvider connectionProvider = new SQLServerSnapshotIsolationConnectionProvider(); private SQLServerSnapshotIsolationConnectionProvider connectionProvider = new SQLServerSnapshotIsolationConnectionProvider();
@Override @Override
public void configure(Configuration cfg) { protected void applySettings(StandardServiceRegistryBuilder builder) {
super.configure( cfg ); super.applySettings( builder );
if( SQLServerDialect.class.isAssignableFrom( DIALECT.getClass() )) { if ( SQLServerDialect.class.isAssignableFrom( DIALECT.getClass() ) ) {
connectionProvider.setConnectionProvider( (ConnectionProvider) cfg.getProperties().get( AvailableSettings.CONNECTION_PROVIDER ) ); connectionProvider.setConnectionProvider( (ConnectionProvider) builder.getSettings()
cfg.getProperties().put( AvailableSettings.CONNECTION_PROVIDER, connectionProvider ); .get( AvailableSettings.CONNECTION_PROVIDER ) );
builder.applySetting( AvailableSettings.CONNECTION_PROVIDER, connectionProvider );
} }
} }
@Override @AfterAll
protected void releaseSessionFactory() { protected void tearDown() {
super.releaseSessionFactory();
connectionProvider.stop(); connectionProvider.stop();
} }
@ -85,9 +87,6 @@ public class LockExceptionTests extends AbstractJPATest {
} }
); );
} }
catch (Exception e) {
log.error( "Exception thrown", e );
}
finally { finally {
inTransaction( inTransaction(
session -> session.createQuery( "delete Item" ).executeUpdate() session -> session.createQuery( "delete Item" ).executeUpdate()

View File

@ -8,27 +8,27 @@ package org.hibernate.orm.test.jpa.lock;
import java.math.BigDecimal; import java.math.BigDecimal;
import org.junit.Test;
import org.hibernate.LockMode; import org.hibernate.LockMode;
import org.hibernate.Session;
import org.hibernate.StaleObjectStateException; import org.hibernate.StaleObjectStateException;
import org.hibernate.Transaction; import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.SQLServerDialect; import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.exception.SQLGrammarException; import org.hibernate.exception.SQLGrammarException;
import org.hibernate.test.jpa.AbstractJPATest; import org.hibernate.orm.test.jpa.model.AbstractJPATest;
import org.hibernate.test.jpa.Item; import org.hibernate.orm.test.jpa.model.Item;
import org.hibernate.test.jpa.Part; import org.hibernate.orm.test.jpa.model.Part;
import org.hibernate.testing.jdbc.SQLServerSnapshotIsolationConnectionProvider;
import org.hibernate.testing.DialectChecks; import org.hibernate.testing.jdbc.SQLServerSnapshotIsolationConnectionProvider;
import org.hibernate.testing.RequiresDialectFeature; import org.hibernate.testing.orm.junit.DialectFeatureChecks;
import org.hibernate.testing.orm.junit.RequiresDialectFeature;
import org.junit.jupiter.api.AfterAll;
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.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/** /**
* Test that the Hibernate Session complies with REPEATABLE_READ isolation * Test that the Hibernate Session complies with REPEATABLE_READ isolation
@ -36,247 +36,252 @@ import static org.junit.Assert.fail;
* *
* @author Steve Ebersole * @author Steve Ebersole
*/ */
@RequiresDialectFeature( DialectChecks.DoesReadCommittedNotCauseWritersToBlockReadersCheck.class ) @RequiresDialectFeature(feature = DialectFeatureChecks.DoesReadCommittedNotCauseWritersToBlockReadersCheck.class)
public class RepeatableReadTest extends AbstractJPATest { public class RepeatableReadTest extends AbstractJPATest {
private SQLServerSnapshotIsolationConnectionProvider connectionProvider = new SQLServerSnapshotIsolationConnectionProvider(); private SQLServerSnapshotIsolationConnectionProvider connectionProvider = new SQLServerSnapshotIsolationConnectionProvider();
@Override @Override
public void configure(Configuration cfg) { protected void applySettings(StandardServiceRegistryBuilder builder) {
super.configure( cfg ); super.applySettings( builder );
if( SQLServerDialect.class.isAssignableFrom( DIALECT.getClass() )) { if ( SQLServerDialect.class.isAssignableFrom( DIALECT.getClass() ) ) {
connectionProvider.setConnectionProvider( (ConnectionProvider) cfg.getProperties().get( AvailableSettings.CONNECTION_PROVIDER ) ); connectionProvider.setConnectionProvider( (ConnectionProvider) builder.getSettings()
cfg.getProperties().put( AvailableSettings.CONNECTION_PROVIDER, connectionProvider ); .get( AvailableSettings.CONNECTION_PROVIDER ) );
builder.applySetting( AvailableSettings.CONNECTION_PROVIDER, connectionProvider );
} }
} }
@Override @AfterAll
protected void releaseSessionFactory() { protected void tearDown() {
super.releaseSessionFactory();
connectionProvider.stop(); connectionProvider.stop();
} }
@Test @Test
public void testStaleVersionedInstanceFoundInQueryResult() { public void testStaleVersionedInstanceFoundInQueryResult() {
String check = "EJB3 Specification"; String check = "EJB3 Specification";
Session s1 = sessionFactory().openSession(); Item it = new Item( check );
Transaction t1 = s1.beginTransaction(); inTransaction(
Item item = new Item( check ); session -> {
s1.save( item ); session.save( it );
t1.commit(); }
s1.close(); );
Long itemId = item.getId(); Long itemId = it.getId();
long initialVersion = item.getVersion(); long initialVersion = it.getVersion();
// Now, open a new Session and re-load the item... // Now, open a new Session and re-load the item...
s1 = sessionFactory().openSession(); inTransaction(
t1 = s1.beginTransaction(); s1 -> {
item = ( Item ) s1.get( Item.class, itemId ); Item item = s1.get( Item.class, itemId );
// now that the item is associated with the persistence-context of that session, // now that the item is associated with the persistence-context of that session,
// open a new session and modify it "behind the back" of the first session // open a new session and modify it "behind the back" of the first session
Session s2 = sessionFactory().openSession(); inTransaction(
Transaction t2 = s2.beginTransaction(); s2 -> {
Item item2 = ( Item ) s2.get( Item.class, itemId ); Item item2 = s2.get( Item.class, itemId );
item2.setName( "EJB3 Persistence Spec" ); item2.setName( "EJB3 Persistence Spec" );
t2.commit(); }
s2.close(); );
// at this point, s1 now contains stale data, so try an hql query which // at this point, s1 now contains stale data, so try an hql query which
// returns said item and make sure we get the previously associated state // returns said item and make sure we get the previously associated state
// (i.e., the old name and the old version) // (i.e., the old name and the old version)
item2 = ( Item ) s1.createQuery( "select i from Item i" ).list().get( 0 ); Item item2 = (Item) s1.createQuery( "select i from Item i" ).list().get( 0 );
assertTrue( item == item2 ); assertTrue( item == item2 );
assertEquals( "encountered non-repeatable read", check, item2.getName() ); assertEquals( check, item2.getName(), "encountered non-repeatable read" );
assertEquals( "encountered non-repeatable read", initialVersion, item2.getVersion() ); assertEquals( initialVersion, item2.getVersion(), "encountered non-repeatable read" );
t1.commit(); }
s1.close(); );
// clean up // clean up
s1 = sessionFactory().openSession(); inTransaction(
t1 = s1.beginTransaction(); session ->
s1.createQuery( "delete Item" ).executeUpdate(); session.createQuery( "delete Item" ).executeUpdate()
t1.commit(); );
s1.close();
} }
@Test @Test
public void testStaleVersionedInstanceFoundOnLock() { public void testStaleVersionedInstanceFoundOnLock() {
if ( ! readCommittedIsolationMaintained( "repeatable read tests" ) ) { if ( !readCommittedIsolationMaintained( "repeatable read tests" ) ) {
return; return;
} }
String check = "EJB3 Specification"; String check = "EJB3 Specification";
Session s1 = sessionFactory().openSession(); Item it = new Item( check );
Transaction t1 = s1.beginTransaction(); inTransaction(
Item item = new Item( check ); session -> {
s1.save( item ); session.save( it );
t1.commit(); }
s1.close(); );
Long itemId = item.getId(); Long itemId = it.getId();
long initialVersion = item.getVersion(); long initialVersion = it.getVersion();
// Now, open a new Session and re-load the item... // Now, open a new Session and re-load the item...
s1 = sessionFactory().openSession(); inSession(
t1 = s1.beginTransaction(); s1 -> {
item = ( Item ) s1.get( Item.class, itemId ); s1.beginTransaction();
try {
Item item = s1.get( Item.class, itemId );
// now that the item is associated with the persistence-context of that session, // now that the item is associated with the persistence-context of that session,
// open a new session and modify it "behind the back" of the first session // open a new session and modify it "behind the back" of the first session
Session s2 = sessionFactory().openSession(); inTransaction(
Transaction t2 = s2.beginTransaction(); s2 -> {
Item item2 = ( Item ) s2.get( Item.class, itemId ); Item item2 = s2.get( Item.class, itemId );
item2.setName( "EJB3 Persistence Spec" ); item2.setName( "EJB3 Persistence Spec" );
t2.commit(); }
s2.close(); );
// at this point, s1 now contains stale data, so acquire a READ lock // at this point, s1 now contains stale data, so acquire a READ lock
// and make sure we get the already associated state (i.e., the old // and make sure we get the already associated state (i.e., the old
// name and the old version) // name and the old version)
s1.lock( item, LockMode.READ ); s1.lock( item, LockMode.READ );
item2 = ( Item ) s1.get( Item.class, itemId ); Item item2 = (Item) s1.get( Item.class, itemId );
assertTrue( item == item2 ); assertTrue( item == item2 );
assertEquals( "encountered non-repeatable read", check, item2.getName() ); assertEquals( check, item2.getName(), "encountered non-repeatable read" );
assertEquals( "encountered non-repeatable read", initialVersion, item2.getVersion() ); assertEquals( initialVersion, item2.getVersion(), "encountered non-repeatable read" );
// attempt to acquire an UPGRADE lock; this should fail // attempt to acquire an UPGRADE lock; this should fail
try {
s1.lock( item, LockMode.UPGRADE ); s1.lock( item, LockMode.UPGRADE );
fail( "expected UPGRADE lock failure" ); fail( "expected UPGRADE lock failure" );
} }
catch( StaleObjectStateException expected ) { catch (StaleObjectStateException expected) {
// this is the expected behavior // this is the expected behavior
} }
catch( SQLGrammarException t ) { catch (SQLGrammarException t) {
if ( getDialect() instanceof SQLServerDialect ) { if ( getDialect() instanceof SQLServerDialect ) {
// sql-server (using snapshot isolation) reports this as a grammar exception /:) // sql-server (using snapshot isolation) reports this as a grammar exception /:)
// //
// not to mention that it seems to "lose track" of the transaction in this scenario... // not to mention that it seems to "lose track" of the transaction in this scenario...
t1.rollback(); s1.getTransaction().rollback();
t1 = s1.beginTransaction();
} }
else { else {
throw t; throw t;
} }
} }
finally {
s1.getTransaction().rollback();
}
t1.commit(); }
s1.close(); );
// clean up // clean up
s1 = sessionFactory().openSession(); inTransaction(
t1 = s1.beginTransaction(); session ->
s1.createQuery( "delete Item" ).executeUpdate(); session.createQuery( "delete Item" ).executeUpdate()
t1.commit(); );
s1.close();
} }
@Test @Test
public void testStaleNonVersionedInstanceFoundInQueryResult() { public void testStaleNonVersionedInstanceFoundInQueryResult() {
String check = "Lock Modes"; String check = "Lock Modes";
Session s1 = sessionFactory().openSession(); Part p = new Part( new Item( "EJB3 Specification" ), check, "3.3.5.3", new BigDecimal( 0.0 ) );
Transaction t1 = s1.beginTransaction(); inTransaction(
Part part = new Part( new Item( "EJB3 Specification" ), check, "3.3.5.3", new BigDecimal( 0.0 ) ); session -> {
s1.save( part ); session.save( p );
t1.commit(); }
s1.close(); );
Long partId = part.getId(); Long partId = p.getId();
// Now, open a new Session and re-load the part... // Now, open a new Session and re-load the part...
s1 = sessionFactory().openSession();
t1 = s1.beginTransaction(); inTransaction(
part = ( Part ) s1.get( Part.class, partId ); s1 -> {
Part part = s1.get( Part.class, partId );
// now that the item is associated with the persistence-context of that session, // now that the item is associated with the persistence-context of that session,
// open a new session and modify it "behind the back" of the first session // open a new session and modify it "behind the back" of the first session
Session s2 = sessionFactory().openSession(); inTransaction(
Transaction t2 = s2.beginTransaction(); s2 -> {
Part part2 = ( Part ) s2.get( Part.class, partId ); Part part2 = s2.get( Part.class, partId );
part2.setName( "Lock Mode Types" ); part2.setName( "Lock Mode Types" );
t2.commit(); }
s2.close(); );
// at this point, s1 now contains stale data, so try an hql query which // at this point, s1 now contains stale data, so try an hql query which
// returns said part and make sure we get the previously associated state // returns said part and make sure we get the previously associated state
// (i.e., the old name) // (i.e., the old name)
part2 = ( Part ) s1.createQuery( "select p from Part p" ).list().get( 0 ); Part part2 = (Part) s1.createQuery( "select p from Part p" ).list().get( 0 );
assertTrue( part == part2 ); assertTrue( part == part2 );
assertEquals( "encountered non-repeatable read", check, part2.getName() ); assertEquals( check, part2.getName(), "encountered non-repeatable read" );
}
t1.commit(); );
s1.close();
// clean up // clean up
s1 = sessionFactory().openSession(); inTransaction(
t1 = s1.beginTransaction(); session -> {
s1.delete( part2 ); Part part = (Part) session.createQuery( "select p from Part p" ).list().get( 0 );
s1.delete( part2.getItem() );
t1.commit(); session.delete( part );
s1.close(); session.delete( part.getItem() );
}
);
} }
@Test @Test
public void testStaleNonVersionedInstanceFoundOnLock() { public void testStaleNonVersionedInstanceFoundOnLock() {
if ( ! readCommittedIsolationMaintained( "repeatable read tests" ) ) { if ( !readCommittedIsolationMaintained( "repeatable read tests" ) ) {
return; return;
} }
String check = "Lock Modes"; String check = "Lock Modes";
Session s1 = sessionFactory().openSession(); Part p = new Part( new Item( "EJB3 Specification" ), check, "3.3.5.3", new BigDecimal( 0.0 ) );
Transaction t1 = s1.beginTransaction(); inTransaction(
Part part = new Part( new Item( "EJB3 Specification" ), check, "3.3.5.3", new BigDecimal( 0.0 ) ); session -> {
s1.save( part ); session.save( p );
t1.commit(); }
s1.close(); );
Long partId = part.getId(); Long partId = p.getId();
// Now, open a new Session and re-load the part... // Now, open a new Session and re-load the part...
s1 = sessionFactory().openSession(); inTransaction(
t1 = s1.beginTransaction(); s1 -> {
part = ( Part ) s1.get( Part.class, partId ); Part part = s1.get( Part.class, partId );
// now that the item is associated with the persistence-context of that session, // now that the item is associated with the persistence-context of that session,
// open a new session and modify it "behind the back" of the first session // open a new session and modify it "behind the back" of the first session
Session s2 = sessionFactory().openSession(); inTransaction(
Transaction t2 = s2.beginTransaction(); s2 -> {
Part part2 = ( Part ) s2.get( Part.class, partId ); Part part2 = s2.get( Part.class, partId );
part2.setName( "Lock Mode Types" ); part2.setName( "Lock Mode Types" );
t2.commit(); }
s2.close(); );
// at this point, s1 now contains stale data, so acquire a READ lock // at this point, s1 now contains stale data, so acquire a READ lock
// and make sure we get the already associated state (i.e., the old // and make sure we get the already associated state (i.e., the old
// name and the old version) // name and the old version)
s1.lock( part, LockMode.READ ); s1.lock( part, LockMode.READ );
part2 = ( Part ) s1.get( Part.class, partId ); Part part2 = s1.get( Part.class, partId );
assertTrue( part == part2 ); assertTrue( part == part2 );
assertEquals( "encountered non-repeatable read", check, part2.getName() ); assertEquals( check, part2.getName(), "encountered non-repeatable read" );
// then acquire an UPGRADE lock; this should fail // then acquire an UPGRADE lock; this should fail
try { try {
s1.lock( part, LockMode.UPGRADE ); s1.lock( part, LockMode.UPGRADE );
} }
catch( Throwable t ) { catch (Throwable t) {
// SQLServer, for example, immediately throws an exception here... // SQLServer, for example, immediately throws an exception here...
t1.rollback(); s1.getTransaction().rollback();
t1 = s1.beginTransaction(); s1.beginTransaction();
} }
part2 = ( Part ) s1.get( Part.class, partId ); part2 = s1.get( Part.class, partId );
assertTrue( part == part2 ); assertTrue( part == part2 );
assertEquals( "encountered non-repeatable read", check, part2.getName() ); assertEquals( check, part2.getName(), "encountered non-repeatable read" );
}
t1.commit(); );
s1.close();
// clean up // clean up
s1 = sessionFactory().openSession(); inTransaction(
t1 = s1.beginTransaction(); session -> {
s1.delete( part ); Part part = session.get( Part.class, partId );
s1.delete( part.getItem() ); session.delete( part );
t1.commit(); session.delete( part.getItem() );
s1.close(); }
);
} }
} }

View File

@ -4,14 +4,16 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.jpa; package org.hibernate.orm.test.jpa.model;
import java.sql.Connection;
import java.util.IdentityHashMap; import java.util.IdentityHashMap;
import jakarta.persistence.EntityNotFoundException;
import org.hibernate.Session;
import org.hibernate.boot.Metadata; import org.hibernate.boot.Metadata;
import org.hibernate.boot.SessionFactoryBuilder;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.cfg.Configuration; import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Environment; import org.hibernate.cfg.Environment;
import org.hibernate.engine.spi.CascadingAction; import org.hibernate.engine.spi.CascadingAction;
import org.hibernate.engine.spi.CascadingActions; import org.hibernate.engine.spi.CascadingActions;
@ -30,29 +32,40 @@ import org.hibernate.integrator.spi.Integrator;
import org.hibernate.proxy.EntityNotFoundDelegate; import org.hibernate.proxy.EntityNotFoundDelegate;
import org.hibernate.service.spi.SessionFactoryServiceRegistry; import org.hibernate.service.spi.SessionFactoryServiceRegistry;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import org.hibernate.testing.SkipLog;
import org.hibernate.testing.orm.junit.BaseSessionFactoryFunctionalTest;
import jakarta.persistence.EntityNotFoundException;
/** /**
* An abstract test for all JPA spec related tests. * An abstract test for all JPA spec related tests.
* *
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public abstract class AbstractJPATest extends BaseCoreFunctionalTestCase { public abstract class AbstractJPATest extends BaseSessionFactoryFunctionalTest {
@Override @Override
public String[] getMappings() { protected String[] getOrmXmlFiles() {
return new String[] { "jpa/Part.hbm.xml", "jpa/Item.hbm.xml", "jpa/MyEntity.hbm.xml" }; return new String[] {
"org/hibernate/orm/test/jpa/model/Part.hbm.xml",
"org/hibernate/orm/test/jpa/model/Item.hbm.xml",
"org/hibernate/orm/test/jpa/model/MyEntity.hbm.xml"
};
} }
@Override @Override
public void configure(Configuration cfg) { protected void applySettings(StandardServiceRegistryBuilder builder) {
super.configure( cfg ); builder.applySetting( Environment.JPAQL_STRICT_COMPLIANCE, "true" );
cfg.setProperty( Environment.JPAQL_STRICT_COMPLIANCE, "true" ); builder.applySetting( Environment.USE_SECOND_LEVEL_CACHE, "false" );
cfg.setProperty( Environment.USE_SECOND_LEVEL_CACHE, "false" );
cfg.setEntityNotFoundDelegate( new JPAEntityNotFoundDelegate() );
} }
@Override @Override
protected void prepareBootstrapRegistryBuilder(BootstrapServiceRegistryBuilder builder) { protected void configure(SessionFactoryBuilder builder) {
super.configure( builder );
builder.applyEntityNotFoundDelegate( new JPAEntityNotFoundDelegate() );
}
@Override
public void prepareBootstrapRegistryBuilder(BootstrapServiceRegistryBuilder builder) {
builder.applyIntegrator( builder.applyIntegrator(
new Integrator() { new Integrator() {
@ -87,7 +100,7 @@ public abstract class AbstractJPATest extends BaseCoreFunctionalTestCase {
private static class JPAEntityNotFoundDelegate implements EntityNotFoundDelegate { private static class JPAEntityNotFoundDelegate implements EntityNotFoundDelegate {
public void handleEntityNotFound(String entityName, Object id) { public void handleEntityNotFound(String entityName, Object id) {
throw new EntityNotFoundException("Unable to find " + entityName + " with id " + id); throw new EntityNotFoundException( "Unable to find " + entityName + " with id " + id );
} }
} }
@ -157,4 +170,21 @@ public abstract class AbstractJPATest extends BaseCoreFunctionalTestCase {
public static class JPAFlushEntityEventListener extends DefaultFlushEntityEventListener { public static class JPAFlushEntityEventListener extends DefaultFlushEntityEventListener {
// in JPA, used mainly for preUpdate callbacks... // in JPA, used mainly for preUpdate callbacks...
} }
protected boolean readCommittedIsolationMaintained(String scenario) {
final int isolation;
try (Session testSession = sessionFactory().openSession()) {
isolation = testSession.doReturningWork(
connection ->
connection.getTransactionIsolation()
);
}
if ( isolation < Connection.TRANSACTION_READ_COMMITTED ) {
SkipLog.reportSkip( "environment does not support at least read committed isolation", scenario );
return false;
}
else {
return true;
}
}
} }

View File

@ -10,7 +10,7 @@
"-//Hibernate/Hibernate Mapping DTD 3.0//EN" "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.hibernate.test.jpa"> <hibernate-mapping package="org.hibernate.orm.test.jpa.model">
<class name="Item" table="EJB3_ITEM"> <class name="Item" table="EJB3_ITEM">
<id name="id" column="ITEM_ID" type="long"> <id name="id" column="ITEM_ID" type="long">

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.jpa; package org.hibernate.orm.test.jpa.model;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;

View File

@ -1,4 +1,4 @@
package org.hibernate.test.jpa; package org.hibernate.orm.test.jpa.model;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.Id; import jakarta.persistence.Id;

View File

@ -1,4 +1,4 @@
package org.hibernate.test.jpa; package org.hibernate.orm.test.jpa.model;
import java.util.Map; import java.util.Map;

View File

@ -8,7 +8,7 @@
--> -->
<!DOCTYPE hibernate-mapping SYSTEM "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd" > <!DOCTYPE hibernate-mapping SYSTEM "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="org.hibernate.test.jpa"> <hibernate-mapping package="org.hibernate.orm.test.jpa.model">
<class name="MyEntity" table="JPA_MYENTITY" discriminator-value="E"> <class name="MyEntity" table="JPA_MYENTITY" discriminator-value="E">
<id name="id" column="ID" type="long"> <id name="id" column="ID" type="long">

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.jpa; package org.hibernate.orm.test.jpa.model;
/** /**

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.jpa; package org.hibernate.orm.test.jpa.model;
/** /**

View File

@ -10,7 +10,7 @@
"-//Hibernate/Hibernate Mapping DTD 3.0//EN" "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.hibernate.test.jpa"> <hibernate-mapping package="org.hibernate.orm.test.jpa.model">
<class name="Part" table="EJB3_PART"> <class name="Part" table="EJB3_PART">
<id name="id" column="PART_ID" type="long"> <id name="id" column="PART_ID" type="long">

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.jpa; package org.hibernate.orm.test.jpa.model;
import java.math.BigDecimal; import java.math.BigDecimal;
/** /**

View File

@ -1,4 +1,4 @@
package org.hibernate.test.jpa; package org.hibernate.orm.test.jpa.model;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.Id; import jakarta.persistence.Id;

View File

@ -0,0 +1,78 @@
/*
* 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.orm.test.jpa.naturalid;
import org.hibernate.dialect.AbstractHANADialect;
import org.hibernate.dialect.OracleDialect;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.orm.junit.SkipForDialect;
import org.hibernate.orm.test.jpa.model.AbstractJPATest;
import org.hibernate.test.jpa.naturalid.ClassWithIdentityColumn;
import org.hibernate.test.jpa.naturalid.Group;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Steve Ebersole
*/
@SkipForDialect(dialectClass = OracleDialect.class, version = 800, matchSubTypes = true,
reason = "Oracle do not support identity key generation")
@SkipForDialect(dialectClass = AbstractHANADialect.class, matchSubTypes = true,
reason = "Hana do not support identity key generation")
public class MutableNaturalIdTest extends AbstractJPATest {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] { Group.class, ClassWithIdentityColumn.class };
}
@Test
public void testSimpleNaturalIdLoadAccessCacheWithUpdate() {
inTransaction(
session -> {
Group g = new Group( 1, "admin" );
session.persist( g );
}
);
inTransaction(
session -> {
Group g = session.bySimpleNaturalId( Group.class ).load( "admin" );
assertNotNull( g );
Group g2 = (Group) session.bySimpleNaturalId( Group.class ).getReference( "admin" );
assertTrue( g == g2 );
g.setName( "admins" );
session.flush();
g2 = session.bySimpleNaturalId( Group.class ).getReference( "admins" );
assertTrue( g == g2 );
}
);
inTransaction(
session ->
session.createQuery( "delete Group" ).executeUpdate()
);
}
@Test
@TestForIssue(jiraKey = "HHH-7304")
public void testInLineSynchWithIdentityColumn() {
inTransaction(
session -> {
ClassWithIdentityColumn e = new ClassWithIdentityColumn();
e.setName( "Dampf" );
session.save( e );
e.setName( "Klein" );
assertNotNull( session.bySimpleNaturalId( ClassWithIdentityColumn.class ).load( "Klein" ) );
}
);
}
}

View File

@ -4,36 +4,39 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.jpa.orphan.one2one; package org.hibernate.orm.test.jpa.orphan.onetoone;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.orm.junit.EntityManagerFactoryScope;
import org.hibernate.testing.orm.junit.Jpa;
import org.junit.jupiter.api.Test;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.Id; import jakarta.persistence.Id;
import jakarta.persistence.OneToOne; import jakarta.persistence.OneToOne;
import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.Test; import static org.junit.jupiter.api.Assertions.assertNull;
import org.hibernate.testing.TestForIssue;
import static org.hibernate.testing.transaction.TransactionUtil.doInJPA;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
/** /**
* @author Chris Cranford * @author Chris Cranford
*/ */
@TestForIssue( jiraKey = "HHH-9663" ) @TestForIssue(jiraKey = "HHH-9663")
public class OneToOneEagerNonOptionalOrphanRemovalTest extends BaseEntityManagerFunctionalTestCase { @Jpa(
@Override annotatedClasses = {
protected Class<?>[] getAnnotatedClasses() { OneToOneEagerNonOptionalOrphanRemovalTest.Car.class,
return new Class<?>[] { Car.class, PaintColor.class, Engine.class }; OneToOneEagerNonOptionalOrphanRemovalTest.PaintColor.class,
OneToOneEagerNonOptionalOrphanRemovalTest.Engine.class
} }
)
public class OneToOneEagerNonOptionalOrphanRemovalTest {
@Test @Test
public void testOneToOneLazyNonOptionalOrphanRemoval() { public void testOneToOneLazyNonOptionalOrphanRemoval(EntityManagerFactoryScope scope) {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Initialize the data // Initialize the data
doInJPA( this::entityManagerFactory, entityManager -> { scope.inTransaction( entityManager -> {
final PaintColor color = new PaintColor( 1, "Red" ); final PaintColor color = new PaintColor( 1, "Red" );
final Engine engine1 = new Engine( 1, 275 ); final Engine engine1 = new Engine( 1, 275 );
final Engine engine2 = new Engine( 2, 295 ); final Engine engine2 = new Engine( 2, 295 );
@ -47,14 +50,14 @@ public class OneToOneEagerNonOptionalOrphanRemovalTest extends BaseEntityManager
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Test orphan removal for unidirectional relationship // Test orphan removal for unidirectional relationship
doInJPA( this::entityManagerFactory, entityManager -> { scope.inTransaction( entityManager -> {
final Car car = entityManager.find( Car.class, 1 ); final Car car = entityManager.find( Car.class, 1 );
final Engine engine = entityManager.find( Engine.class, 2 ); final Engine engine = entityManager.find( Engine.class, 2 );
car.setEngine( engine ); car.setEngine( engine );
entityManager.merge( car ); entityManager.merge( car );
} ); } );
doInJPA( this::entityManagerFactory, entityManager -> { scope.inTransaction( entityManager -> {
final Car car = entityManager.find( Car.class, 1 ); final Car car = entityManager.find( Car.class, 1 );
assertNotNull( car.getEngine() ); assertNotNull( car.getEngine() );
@ -64,7 +67,7 @@ public class OneToOneEagerNonOptionalOrphanRemovalTest extends BaseEntityManager
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Test orphan removal for bidirectional relationship // Test orphan removal for bidirectional relationship
doInJPA( this::entityManagerFactory, entityManager -> { scope.inTransaction( entityManager -> {
final PaintColor color = new PaintColor( 2, "Blue" ); final PaintColor color = new PaintColor( 2, "Blue" );
final Car car = entityManager.find( Car.class, 1 ); final Car car = entityManager.find( Car.class, 1 );
car.setPaintColor( color ); car.setPaintColor( color );
@ -72,7 +75,7 @@ public class OneToOneEagerNonOptionalOrphanRemovalTest extends BaseEntityManager
entityManager.merge( car ); entityManager.merge( car );
} ); } );
doInJPA( this::entityManagerFactory, entityManager -> { scope.inTransaction( entityManager -> {
final Car car = entityManager.find( Car.class, 1 ); final Car car = entityManager.find( Car.class, 1 );
assertNotNull( car.getPaintColor() ); assertNotNull( car.getPaintColor() );

View File

@ -4,36 +4,39 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.jpa.orphan.one2one; package org.hibernate.orm.test.jpa.orphan.onetoone;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.orm.junit.EntityManagerFactoryScope;
import org.hibernate.testing.orm.junit.Jpa;
import org.junit.jupiter.api.Test;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.FetchType; import jakarta.persistence.FetchType;
import jakarta.persistence.Id; import jakarta.persistence.Id;
import jakarta.persistence.OneToOne; import jakarta.persistence.OneToOne;
import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.Test;
import org.hibernate.testing.TestForIssue;
import static org.hibernate.testing.transaction.TransactionUtil.doInJPA;
import static org.junit.Assert.assertNull;
/** /**
* @author Chris Cranford * @author Chris Cranford
*/ */
@TestForIssue( jiraKey = "HHH-9663" ) @TestForIssue(jiraKey = "HHH-9663")
public class OneToOneEagerOrphanRemovalTest extends BaseEntityManagerFunctionalTestCase { @Jpa(
@Override annotatedClasses = {
protected Class<?>[] getAnnotatedClasses() { OneToOneEagerOrphanRemovalTest.Car.class,
return new Class<?>[] { Car.class, PaintColor.class, Engine.class }; OneToOneEagerOrphanRemovalTest.PaintColor.class,
OneToOneEagerOrphanRemovalTest.Engine.class
} }
)
public class OneToOneEagerOrphanRemovalTest {
@Test @Test
public void testOneToOneEagerOrphanRemoval() { public void testOneToOneEagerOrphanRemoval(EntityManagerFactoryScope scope) {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Initialize the data // Initialize the data
doInJPA( this::entityManagerFactory, entityManager -> { scope.inTransaction( entityManager -> {
final PaintColor color = new PaintColor( 1, "Red" ); final PaintColor color = new PaintColor( 1, "Red" );
final Engine engine = new Engine( 1, 275 ); final Engine engine = new Engine( 1, 275 );
final Car car = new Car( 1, engine, color ); final Car car = new Car( 1, engine, color );
@ -45,13 +48,13 @@ public class OneToOneEagerOrphanRemovalTest extends BaseEntityManagerFunctionalT
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Test orphan removal for unidirectional relationship // Test orphan removal for unidirectional relationship
doInJPA( this::entityManagerFactory, entityManager -> { scope.inTransaction( entityManager -> {
final Car car = entityManager.find( Car.class, 1 ); final Car car = entityManager.find( Car.class, 1 );
car.setEngine( null ); car.setEngine( null );
entityManager.merge( car ); entityManager.merge( car );
} ); } );
doInJPA( this::entityManagerFactory, entityManager -> { scope.inTransaction( entityManager -> {
final Car car = entityManager.find( Car.class, 1 ); final Car car = entityManager.find( Car.class, 1 );
assertNull( car.getEngine() ); assertNull( car.getEngine() );
@ -61,13 +64,13 @@ public class OneToOneEagerOrphanRemovalTest extends BaseEntityManagerFunctionalT
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Test orphan removal for bidirectional relationship // Test orphan removal for bidirectional relationship
doInJPA( this::entityManagerFactory, entityManager -> { scope.inTransaction( entityManager -> {
final Car car = entityManager.find( Car.class, 1 ); final Car car = entityManager.find( Car.class, 1 );
car.setPaintColor( null ); car.setPaintColor( null );
entityManager.merge( car ); entityManager.merge( car );
} ); } );
doInJPA( this::entityManagerFactory, entityManager -> { scope.inTransaction( entityManager -> {
final Car car = entityManager.find( Car.class, 1 ); final Car car = entityManager.find( Car.class, 1 );
assertNull( car.getPaintColor() ); assertNull( car.getPaintColor() );

View File

@ -4,37 +4,39 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.jpa.orphan.one2one; package org.hibernate.orm.test.jpa.orphan.onetoone;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.orm.junit.EntityManagerFactoryScope;
import org.hibernate.testing.orm.junit.Jpa;
import org.junit.jupiter.api.Test;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.FetchType; import jakarta.persistence.FetchType;
import jakarta.persistence.Id; import jakarta.persistence.Id;
import jakarta.persistence.OneToOne; import jakarta.persistence.OneToOne;
import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.Test; import static org.junit.jupiter.api.Assertions.assertNull;
import org.hibernate.testing.TestForIssue;
import static org.hibernate.testing.transaction.TransactionUtil.doInJPA;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
/** /**
* @author Chris Cranford * @author Chris Cranford
*/ */
@TestForIssue( jiraKey = "HHH-9663" ) @TestForIssue(jiraKey = "HHH-9663")
public class OneToOneLazyNonOptionalOrphanRemovalTest extends BaseEntityManagerFunctionalTestCase { @Jpa(
@Override annotatedClasses = {
protected Class<?>[] getAnnotatedClasses() { OneToOneLazyNonOptionalOrphanRemovalTest.Car.class,
return new Class<?>[] { Car.class, PaintColor.class, Engine.class }; OneToOneLazyNonOptionalOrphanRemovalTest.PaintColor.class,
OneToOneLazyNonOptionalOrphanRemovalTest.Engine.class
} }
)
public class OneToOneLazyNonOptionalOrphanRemovalTest {
@Test @Test
public void testOneToOneLazyNonOptionalOrphanRemoval() { public void testOneToOneLazyNonOptionalOrphanRemoval(EntityManagerFactoryScope scope) {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Initialize the data // Initialize the data
doInJPA( this::entityManagerFactory, entityManager -> { scope.inTransaction( entityManager -> {
final PaintColor color = new PaintColor( 1, "Red" ); final PaintColor color = new PaintColor( 1, "Red" );
final Engine engine1 = new Engine( 1, 275 ); final Engine engine1 = new Engine( 1, 275 );
final Engine engine2 = new Engine( 2, 295 ); final Engine engine2 = new Engine( 2, 295 );
@ -48,14 +50,14 @@ public class OneToOneLazyNonOptionalOrphanRemovalTest extends BaseEntityManagerF
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Test orphan removal for unidirectional relationship // Test orphan removal for unidirectional relationship
doInJPA( this::entityManagerFactory, entityManager -> { scope.inTransaction( entityManager -> {
final Car car = entityManager.find( Car.class, 1 ); final Car car = entityManager.find( Car.class, 1 );
final Engine engine = entityManager.find( Engine.class, 2 ); final Engine engine = entityManager.find( Engine.class, 2 );
car.setEngine( engine ); car.setEngine( engine );
entityManager.merge( car ); entityManager.merge( car );
} ); } );
doInJPA( this::entityManagerFactory, entityManager -> { scope.inTransaction( entityManager -> {
final Car car = entityManager.find( Car.class, 1 ); final Car car = entityManager.find( Car.class, 1 );
assertNotNull( car.getEngine() ); assertNotNull( car.getEngine() );
@ -65,7 +67,7 @@ public class OneToOneLazyNonOptionalOrphanRemovalTest extends BaseEntityManagerF
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Test orphan removal for bidirectional relationship // Test orphan removal for bidirectional relationship
doInJPA( this::entityManagerFactory, entityManager -> { scope.inTransaction( entityManager -> {
final PaintColor color = new PaintColor( 2, "Blue" ); final PaintColor color = new PaintColor( 2, "Blue" );
final Car car = entityManager.find( Car.class, 1 ); final Car car = entityManager.find( Car.class, 1 );
car.setPaintColor( color ); car.setPaintColor( color );
@ -73,7 +75,7 @@ public class OneToOneLazyNonOptionalOrphanRemovalTest extends BaseEntityManagerF
entityManager.merge( car ); entityManager.merge( car );
} ); } );
doInJPA( this::entityManagerFactory, entityManager -> { scope.inTransaction( entityManager -> {
final Car car = entityManager.find( Car.class, 1 ); final Car car = entityManager.find( Car.class, 1 );
assertNotNull( car.getPaintColor() ); assertNotNull( car.getPaintColor() );

View File

@ -4,36 +4,39 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.jpa.orphan.one2one; package org.hibernate.orm.test.jpa.orphan.onetoone;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.orm.junit.EntityManagerFactoryScope;
import org.hibernate.testing.orm.junit.Jpa;
import org.junit.jupiter.api.Test;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.FetchType; import jakarta.persistence.FetchType;
import jakarta.persistence.Id; import jakarta.persistence.Id;
import jakarta.persistence.OneToOne; import jakarta.persistence.OneToOne;
import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.Test;
import org.hibernate.testing.TestForIssue;
import static org.hibernate.testing.transaction.TransactionUtil.doInJPA;
import static org.junit.Assert.assertNull;
/** /**
* @author Chris Cranford * @author Chris Cranford
*/ */
@TestForIssue( jiraKey = "HHH-9663" ) @TestForIssue(jiraKey = "HHH-9663")
public class OneToOneLazyOrphanRemovalTest extends BaseEntityManagerFunctionalTestCase { @Jpa(
@Override annotatedClasses = {
protected Class<?>[] getAnnotatedClasses() { OneToOneLazyOrphanRemovalTest.Car.class,
return new Class<?>[] { Car.class, PaintColor.class, Engine.class }; OneToOneLazyOrphanRemovalTest.PaintColor.class,
OneToOneLazyOrphanRemovalTest.Engine.class
} }
)
public class OneToOneLazyOrphanRemovalTest {
@Test @Test
public void testOneToOneLazyOrphanRemoval() { public void testOneToOneLazyOrphanRemoval(EntityManagerFactoryScope scope) {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Initialize the data // Initialize the data
doInJPA( this::entityManagerFactory, entityManager -> { scope.inTransaction( entityManager -> {
final PaintColor color = new PaintColor( 1, "Red" ); final PaintColor color = new PaintColor( 1, "Red" );
final Engine engine = new Engine( 1, 275 ); final Engine engine = new Engine( 1, 275 );
final Car car = new Car( 1, engine, color ); final Car car = new Car( 1, engine, color );
@ -45,13 +48,13 @@ public class OneToOneLazyOrphanRemovalTest extends BaseEntityManagerFunctionalTe
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Test orphan removal for unidirectional relationship // Test orphan removal for unidirectional relationship
doInJPA( this::entityManagerFactory, entityManager -> { scope.inTransaction( entityManager -> {
final Car car = entityManager.find( Car.class, 1 ); final Car car = entityManager.find( Car.class, 1 );
car.setEngine( null ); car.setEngine( null );
entityManager.merge( car ); entityManager.merge( car );
} ); } );
doInJPA( this::entityManagerFactory, entityManager -> { scope.inTransaction( entityManager -> {
final Car car = entityManager.find( Car.class, 1 ); final Car car = entityManager.find( Car.class, 1 );
assertNull( car.getEngine() ); assertNull( car.getEngine() );
@ -61,13 +64,13 @@ public class OneToOneLazyOrphanRemovalTest extends BaseEntityManagerFunctionalTe
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Test orphan removal for bidirectional relationship // Test orphan removal for bidirectional relationship
doInJPA( this::entityManagerFactory, entityManager -> { scope.inTransaction( entityManager -> {
final Car car = entityManager.find( Car.class, 1 ); final Car car = entityManager.find( Car.class, 1 );
car.setPaintColor( null ); car.setPaintColor( null );
entityManager.merge( car ); entityManager.merge( car );
} ); } );
doInJPA( this::entityManagerFactory, entityManager -> { scope.inTransaction( entityManager -> {
final Car car = entityManager.find( Car.class, 1 ); final Car car = entityManager.find( Car.class, 1 );
assertNull( car.getPaintColor() ); assertNull( car.getPaintColor() );

View File

@ -4,16 +4,23 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.jpa.orphan.one2one.embedded; package org.hibernate.orm.test.jpa.orphan.onetoone.embedded;
import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; import org.hibernate.testing.orm.junit.EntityManagerFactoryScope;
import org.junit.Assert; import org.hibernate.testing.orm.junit.Jpa;
import org.junit.Test; import org.junit.jupiter.api.Test;
import jakarta.persistence.*; import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
import jakarta.persistence.Embedded;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToOne;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.hibernate.testing.transaction.TransactionUtil.doInJPA;
import static org.junit.Assert.assertNull;
/** /**
* Similar test as ../OneToOneLazyOrphanRemovalTest, * Similar test as ../OneToOneLazyOrphanRemovalTest,
@ -22,48 +29,51 @@ import static org.junit.Assert.assertNull;
* *
* @TestForIssue( jiraKey = "HHH-9663" ) * @TestForIssue( jiraKey = "HHH-9663" )
*/ */
public class OneToOneLazyOrphanRemovalInEmbeddedEntityTest extends BaseEntityManagerFunctionalTestCase { @Jpa(
@Override annotatedClasses = {
protected Class<?>[] getAnnotatedClasses() { OneToOneLazyOrphanRemovalInEmbeddedEntityTest.RaceDriver.class,
return new Class<?>[] { RaceDriver.class, Car.class, Engine.class}; OneToOneLazyOrphanRemovalInEmbeddedEntityTest.Car.class,
OneToOneLazyOrphanRemovalInEmbeddedEntityTest.Engine.class
} }
)
public class OneToOneLazyOrphanRemovalInEmbeddedEntityTest {
@Test @Test
public void testOneToOneLazyOrphanRemoval() { public void testOneToOneLazyOrphanRemoval(EntityManagerFactoryScope scope) {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Initialize the data // Initialize the data
doInJPA( this::entityManagerFactory, entityManager -> { scope.inTransaction( entityManager -> {
final Engine engine = new Engine( 1, 275 ); final Engine engine = new Engine( 1, 275 );
final Car car = new Car(1, engine, "red"); final Car car = new Car( 1, engine, "red" );
final RaceDriver raceDriver = new RaceDriver(1, car); final RaceDriver raceDriver = new RaceDriver( 1, car );
entityManager.persist( engine ); entityManager.persist( engine );
entityManager.persist( raceDriver ); entityManager.persist( raceDriver );
} ); } );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//set car engine to null, orphanRemoval = true should trigger deletion for engine entity //set car engine to null, orphanRemoval = true should trigger deletion for engine entity
doInJPA( this::entityManagerFactory, entityManager -> { scope.inTransaction( entityManager -> {
final RaceDriver raceDriver = entityManager.find( RaceDriver.class, 1 ); final RaceDriver raceDriver = entityManager.find( RaceDriver.class, 1 );
final Car car = raceDriver.getCar(); final Car car = raceDriver.getCar();
//check, that at the moment the engine is orphan //check, that at the moment the engine is orphan
Assert.assertNotNull(car.getEngine()); assertNotNull( car.getEngine() );
car.setEngine( null ); car.setEngine( null );
entityManager.merge( raceDriver ); entityManager.merge( raceDriver );
final RaceDriver raceDriver2 = entityManager.find( RaceDriver.class, 1 ); final RaceDriver raceDriver2 = entityManager.find( RaceDriver.class, 1 );
Assert.assertNotNull(raceDriver2.car); assertNotNull( raceDriver2.car );
} ); } );
//check, that the engine is deleted: //check, that the engine is deleted:
doInJPA( this::entityManagerFactory, entityManager -> { scope.inTransaction( entityManager -> {
final RaceDriver raceDriver = entityManager.find( RaceDriver.class, 1 ); final RaceDriver raceDriver = entityManager.find( RaceDriver.class, 1 );
final Car car = raceDriver.getCar(); final Car car = raceDriver.getCar();
Assert.assertNull(car.getEngine()); assertNull( car.getEngine() );
final Engine engine = entityManager.find( Engine.class, 1 ); final Engine engine = entityManager.find( Engine.class, 1 );
assertNull( engine); assertNull( engine );
} ); } );
} }

View File

@ -0,0 +1,102 @@
/*
* 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.orm.test.jpa.proxy;
import org.hibernate.Hibernate;
import org.hibernate.orm.test.jpa.model.AbstractJPATest;
import org.hibernate.orm.test.jpa.model.Item;
import org.junit.jupiter.api.Test;
import junit.framework.AssertionFailedError;
import jakarta.persistence.EntityNotFoundException;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Test relation between proxies and get()/load() processing
* and make sure the interactions match the ejb3 expectations
*
* @author Steve Ebersole
*/
public class JPAProxyTest extends AbstractJPATest {
@Test
public void testEjb3ProxyUsage() {
inTransaction(
s -> {
Item item = s.load( Item.class, new Long( -1 ) );
assertFalse( Hibernate.isInitialized( item ) );
try {
Hibernate.initialize( item );
fail( "proxy access did not fail on non-existent proxy" );
}
catch (EntityNotFoundException e) {
// expected behavior
}
catch (Throwable t) {
fail( "unexpected exception type on non-existent proxy access : " + t );
}
s.clear();
Item item2 = s.load( Item.class, new Long( -1 ) );
assertFalse( Hibernate.isInitialized( item2 ) );
assertFalse( item == item2 );
try {
item2.getName();
fail( "proxy access did not fail on non-existent proxy" );
}
catch (EntityNotFoundException e) {
// expected behavior
}
catch (Throwable t) {
fail( "unexpected exception type on non-existent proxy access : " + t );
}
}
);
}
/**
* The ejb3 find() method maps to the Hibernate get() method
*/
@Test
public void testGetSemantics() {
Long nonExistentId = new Long( -1 );
inTransaction(
session -> {
Item item = session.get( Item.class, nonExistentId );
assertNull( item , "get() of non-existent entity did not return null");
}
);
inTransaction(
s -> {
// first load() it to generate a proxy...
Item item = s.load( Item.class, nonExistentId );
assertFalse( Hibernate.isInitialized( item ) );
// then try to get() it to make sure we get an exception
try {
s.get( Item.class, nonExistentId );
fail( "force load did not fail on non-existent entity" );
}
catch (EntityNotFoundException e) {
// expected behavior
}
catch (AssertionFailedError e) {
throw e;
}
catch (Throwable t) {
fail( "unexpected exception type on non-existent entity force load : " + t );
}
}
);
}
}

View File

@ -6,6 +6,9 @@
*/ */
package org.hibernate.orm.test.jpa.ql; package org.hibernate.orm.test.jpa.ql;
import org.hibernate.orm.test.jpa.model.AbstractJPATest;
import org.junit.jupiter.api.Test;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.persistence.DiscriminatorColumn; import jakarta.persistence.DiscriminatorColumn;
import jakarta.persistence.DiscriminatorType; import jakarta.persistence.DiscriminatorType;
@ -16,11 +19,6 @@ import jakarta.persistence.Inheritance;
import jakarta.persistence.InheritanceType; import jakarta.persistence.InheritanceType;
import jakarta.persistence.Table; import jakarta.persistence.Table;
import org.hibernate.Session;
import org.hibernate.test.jpa.AbstractJPATest;
import org.junit.Test;
/** /**
* Mainly a test for testing compliance with the fact that "identification variables" (aliases) need to * Mainly a test for testing compliance with the fact that "identification variables" (aliases) need to
* be treated as case-insensitive according to JPA. * be treated as case-insensitive according to JPA.
@ -31,44 +29,52 @@ public class IdentificationVariablesTest extends AbstractJPATest {
@Test @Test
public void testUsageInSelect() { public void testUsageInSelect() {
Session s = openSession(); inSession(
s.createQuery( "select I from Item i" ).list(); session ->
s.close(); session.createQuery( "select I from Item i" ).list()
);
} }
@Test @Test
public void testUsageInPath() { public void testUsageInPath() {
Session s = openSession(); inSession(
s.createQuery( "select I from Item i where I.name = 'widget'" ).list(); session ->
s.close(); session.createQuery( "select I from Item i where I.name = 'widget'" ).list()
);
} }
@Test @Test
public void testMixedTckUsage() { public void testMixedTckUsage() {
Session s = openSession(); inSession(
s.createQuery( "Select DISTINCT OBJECT(P) from Product p where P.quantity < 10" ).list(); session ->
s.close(); session.createQuery( "Select DISTINCT OBJECT(P) from Product p where P.quantity < 10" ).list()
);
} }
@Test @Test
public void testUsageInJpaInCollectionSyntax() { public void testUsageInJpaInCollectionSyntax() {
Session s = openSession(); inSession(
s.createQuery( "SELECT DISTINCT object(i) FROM Item I, IN(i.parts) ip where ip.stockNumber = '123'" ).list(); session ->
s.close(); session.createQuery(
"SELECT DISTINCT object(i) FROM Item I, IN(i.parts) ip where ip.stockNumber = '123'" )
.list()
);
} }
@Test @Test
public void testUsageInDistinct() { public void testUsageInDistinct() {
Session s = openSession(); inSession(
s.createQuery( "select distinct(I) from Item i" ).list(); session ->
s.close(); session.createQuery( "select distinct(I) from Item i" ).list()
);
} }
@Test @Test
public void testUsageInSelectObject() { public void testUsageInSelectObject() {
Session s = openSession(); inSession(
s.createQuery( "select OBJECT(I) from Item i" ).list(); session ->
s.close(); session.createQuery( "select OBJECT(I) from Item i" ).list()
);
} }
@Override @Override
@ -76,11 +82,11 @@ public class IdentificationVariablesTest extends AbstractJPATest {
return new Class[] { Product.class }; return new Class[] { Product.class };
} }
@Entity( name = "Product") @Entity(name = "Product")
@Table( name = "PROD" ) @Table(name = "PROD")
@Inheritance( strategy = InheritanceType.SINGLE_TABLE ) @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn( name = "PRODUCT_TYPE", discriminatorType = DiscriminatorType.STRING ) @DiscriminatorColumn(name = "PRODUCT_TYPE", discriminatorType = DiscriminatorType.STRING)
@DiscriminatorValue( "Product" ) @DiscriminatorValue("Product")
public static class Product { public static class Product {
private String id; private String id;
private String name; private String name;

View File

@ -9,20 +9,18 @@ package org.hibernate.orm.test.jpa.ql;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.hibernate.Session;
import org.hibernate.query.Query; import org.hibernate.query.Query;
import org.hibernate.query.SemanticException; import org.hibernate.query.SemanticException;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.transaction.TransactionUtil2; import org.hibernate.orm.test.jpa.model.AbstractJPATest;
import org.hibernate.test.jpa.AbstractJPATest; import org.hibernate.orm.test.jpa.model.Item;
import org.hibernate.test.jpa.Item; import org.junit.jupiter.api.Test;
import org.junit.Test;
import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; import static org.hibernate.testing.orm.junit.ExtraAssertions.assertTyping;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.fail;
/** /**
* Tests for various JPAQL compliance issues * Tests for various JPAQL compliance issues
@ -30,61 +28,72 @@ import static org.junit.Assert.fail;
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public class JPAQLComplianceTest extends AbstractJPATest { public class JPAQLComplianceTest extends AbstractJPATest {
@Test @Test
public void testAliasNameSameAsUnqualifiedEntityName() { public void testAliasNameSameAsUnqualifiedEntityName() {
Session s = openSession(); inTransaction(
s.beginTransaction(); session -> {
s.createQuery( "select item from Item item" ).list(); session.createQuery( "select item from Item item" ).list();
s.createQuery( "select item from Item item where item.name = 'a'" ).list(); session.createQuery( "select item from Item item where item.name = 'a'" ).list();
s.getTransaction().commit();
s.close(); }
);
} }
@Test @Test
public void testIdentifierCaseSensitive() { public void testIdentifierCaseSensitive() {
Session s = openSession( );
// a control test (a user reported that the JPA 'case insensitivity' support // a control test (a user reported that the JPA 'case insensitivity' support
// caused problems with the "discriminator resolution" code; unable to reproduce)... // caused problems with the "discriminator resolution" code; unable to reproduce)...
s.createQuery( "select E from MyEntity e where other.class = MySubclassEntity" ); inSession(
s.createQuery( "select e from MyEntity e where e.other.class = MySubclassEntity" ); session -> {
s.createQuery( "select e from MyEntity E where e.class = MySubclassEntity" ); session.createQuery( "select E from MyEntity e where other.class = MySubclassEntity" );
session.createQuery( "select e from MyEntity e where e.other.class = MySubclassEntity" );
session.createQuery( "select e from MyEntity E where e.class = MySubclassEntity" );
s.createQuery( "select object(I) from Item i").list(); session.createQuery( "select object(I) from Item i" ).list();
s.close(); }
);
} }
@Test @Test
public void testIdentifierCasesensitivityAndDuplicateFromElements() { public void testIdentifierCasesensitivityAndDuplicateFromElements() {
Session s = openSession(); inSession(
s.createQuery( "select e from MyEntity e where exists (select 1 from MyEntity e2 where e2.other.name = 'something' and e2.other.other = e)" ); session ->
s.close(); session.createQuery(
"select e from MyEntity e where exists (select 1 from MyEntity e2 where e2.other.name = 'something' and e2.other.other = e)" )
);
} }
@Test @Test
public void testGeneratedSubquery() { public void testGeneratedSubquery() {
Session s = openSession(); inSession(
s.createQuery( "select c FROM Item c WHERE c.parts IS EMPTY" ).list(); session ->
s.close(); session.createQuery( "select c FROM Item c WHERE c.parts IS EMPTY" ).list()
);
} }
@Test @Test
public void testOrderByAlias() { public void testOrderByAlias() {
Session s = openSession(); inSession(
s.createQuery( "select c.name as myname FROM Item c ORDER BY myname" ).list(); session -> {
s.createQuery( "select p.name as name, p.stockNumber as stockNo, p.unitPrice as uPrice FROM Part p ORDER BY name, abs( p.unitPrice ), stockNo" ).list(); session.createQuery( "select c.name as myname FROM Item c ORDER BY myname" ).list();
s.close(); session.createQuery(
"select p.name as name, p.stockNumber as stockNo, p.unitPrice as uPrice FROM Part p ORDER BY name, abs( p.unitPrice ), stockNo" )
.list();
} );
} }
@Test @Test
@TestForIssue(jiraKey = "HHH-12290") @TestForIssue(jiraKey = "HHH-12290")
public void testParametersMixturePositionalAndNamed() { public void testParametersMixturePositionalAndNamed() {
TransactionUtil2.inTransaction( inTransaction(
sessionFactory(),
s -> { s -> {
try { try {
s.createQuery( "select item from Item item where item.id = ?1 and item.name = :name" ).list(); s.createQuery( "select item from Item item where item.id = ?1 and item.name = :name" ).list();
fail( "Expecting QuerySyntaxException because of named and positional parameters mixture" ); fail( "Expecting QuerySyntaxException because of named and positional parameters mixture" );
} catch ( IllegalArgumentException e ) { }
catch (IllegalArgumentException e) {
assertNotNull( e.getCause() ); assertNotNull( e.getCause() );
assertTyping( SemanticException.class, e.getCause() ); assertTyping( SemanticException.class, e.getCause() );
} }
@ -95,8 +104,7 @@ public class JPAQLComplianceTest extends AbstractJPATest {
@Test @Test
@TestForIssue(jiraKey = "HHH-12290") @TestForIssue(jiraKey = "HHH-12290")
public void testParametersMixtureNamedAndPositional() { public void testParametersMixtureNamedAndPositional() {
TransactionUtil2.inTransaction( inTransaction(
sessionFactory(),
s -> { s -> {
try { try {
s.createQuery( "select item from Item item where item.id = :id and item.name = ?1" ).list(); s.createQuery( "select item from Item item where item.id = :id and item.name = ?1" ).list();
@ -113,10 +121,10 @@ public class JPAQLComplianceTest extends AbstractJPATest {
@Test @Test
@TestForIssue(jiraKey = "HHH-12290") @TestForIssue(jiraKey = "HHH-12290")
public void testReusedNamedCollectionParam() { public void testReusedNamedCollectionParam() {
TransactionUtil2.inTransaction( inTransaction(
sessionFactory(),
session -> { session -> {
Query q = session.createQuery( "select e from MyEntity e where e.surname in (:values) or e.name in (:values)" ); Query q = session.createQuery(
"select e from MyEntity e where e.surname in (:values) or e.name in (:values)" );
List<String> params = new ArrayList<>(); List<String> params = new ArrayList<>();
params.add( "name" ); params.add( "name" );
params.add( "other" ); params.add( "other" );
@ -129,8 +137,7 @@ public class JPAQLComplianceTest extends AbstractJPATest {
@Test @Test
@TestForIssue(jiraKey = "HHH-12290") @TestForIssue(jiraKey = "HHH-12290")
public void testReusedPositionalCollectionParam() { public void testReusedPositionalCollectionParam() {
TransactionUtil2.inTransaction( inTransaction(
sessionFactory(),
session -> { session -> {
Query q = session.createQuery( "select e from MyEntity e where e.name in (?1) or e.surname in (?1)" ); Query q = session.createQuery( "select e from MyEntity e where e.name in (?1) or e.surname in (?1)" );
List<String> params = new ArrayList<>(); List<String> params = new ArrayList<>();
@ -149,11 +156,11 @@ public class JPAQLComplianceTest extends AbstractJPATest {
@Test @Test
@TestForIssue(jiraKey = "HHH-12290") @TestForIssue(jiraKey = "HHH-12290")
public void testParametersMixtureNamedCollectionAndPositional() { public void testParametersMixtureNamedCollectionAndPositional() {
TransactionUtil2.inTransaction( inTransaction(
sessionFactory(),
s -> { s -> {
try { try {
Query q = s.createQuery( "select item from Item item where item.id in (?1) and item.name = :name" ); Query q = s.createQuery(
"select item from Item item where item.id in (?1) and item.name = :name" );
List<Long> params = new ArrayList<>(); List<Long> params = new ArrayList<>();
params.add( 0L ); params.add( 0L );
params.add( 1L ); params.add( 1L );
@ -178,16 +185,14 @@ public class JPAQLComplianceTest extends AbstractJPATest {
final Item item2 = new Item( "Computer" ); final Item item2 = new Item( "Computer" );
item2.setId( 2L ); item2.setId( 2L );
TransactionUtil2.inTransaction( inTransaction(
sessionFactory(),
s -> { s -> {
s.save( item ); s.save( item );
s.save( item2 ); s.save( item2 );
} }
); );
TransactionUtil2.inTransaction( inTransaction(
sessionFactory(),
s -> { s -> {
Query q = s.createQuery( Query q = s.createQuery(
"select item from Item item where item.id in(?1) and item.name in (?2) and item.id in(?1)" ); "select item from Item item where item.id in(?1) and item.name in (?2) and item.id in(?1)" );
@ -208,8 +213,7 @@ public class JPAQLComplianceTest extends AbstractJPATest {
} }
); );
TransactionUtil2.inTransaction( inTransaction(
sessionFactory(),
s -> s.createQuery( "select i from Item i" ).list().forEach( result -> s.delete( result ) ) s -> s.createQuery( "select i from Item i" ).list().forEach( result -> s.delete( result ) )
); );

View File

@ -8,9 +8,9 @@ package org.hibernate.orm.test.jpa.ql;
import org.hibernate.dialect.PostgreSQLDialect; import org.hibernate.dialect.PostgreSQLDialect;
import org.hibernate.test.jpa.MapContent; import org.hibernate.orm.test.jpa.model.MapContent;
import org.hibernate.test.jpa.MapOwner; import org.hibernate.orm.test.jpa.model.MapOwner;
import org.hibernate.test.jpa.Relationship; import org.hibernate.orm.test.jpa.model.Relationship;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.jdbc.SQLStatementInspector; import org.hibernate.testing.jdbc.SQLStatementInspector;
import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.DomainModel;

View File

@ -0,0 +1,179 @@
/*
* 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.orm.test.jpa.removed;
import java.math.BigDecimal;
import org.hibernate.orm.test.jpa.model.AbstractJPATest;
import org.hibernate.orm.test.jpa.model.Item;
import org.hibernate.orm.test.jpa.model.Part;
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.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Steve Ebersole
*/
public class RemovedEntityTest extends AbstractJPATest {
@Test
public void testRemoveThenContains() {
Item item = new Item();
inTransaction(
session -> {
item.setName( "dummy" );
session.persist( item );
}
);
boolean contains = fromTransaction(
session -> {
session.delete( item );
return session.contains( item );
}
);
assertFalse( contains, "expecting removed entity to not be contained" );
}
@Test
public void testRemoveThenGet() {
Item it = new Item();
inTransaction(
session -> {
it.setName( "dummy" );
session.persist( it );
}
);
Long id = it.getId();
Item item = fromTransaction(
session -> {
session.delete( it );
return session.get( Item.class, id );
}
);
assertNull( item, "expecting removed entity to be returned as null from get()" );
}
@Test
public void testRemoveThenSave() {
Item it = new Item();
inTransaction(
session -> {
it.setName( "dummy" );
session.persist( it );
}
);
Long id = it.getId();
inTransaction(
session -> {
Item item = session.get( Item.class, id );
String sessionAsString = session.toString();
session.delete( item );
Item item2 = session.get( Item.class, id );
assertNull( item2, "expecting removed entity to be returned as null from get()" );
session.persist( item );
assertEquals( sessionAsString, session.toString(), "expecting session to be as it was before" );
item.setName( "Rescued" );
item = session.get( Item.class, id );
assertNotNull( item, "expecting rescued entity to be returned from get()" );
}
);
Item item = fromTransaction(
session ->
session.get( Item.class, id )
);
assertNotNull( item, "expecting removed entity to be returned as null from get()" );
assertEquals( "Rescued", item.getName() );
// clean up
inTransaction(
session ->
session.delete( item )
);
}
@Test
public void testRemoveThenSaveWithCascades() {
Item item = new Item();
inTransaction(
session -> {
item.setName( "dummy" );
Part part = new Part( item, "child", "1234", BigDecimal.ONE );
// persist cascades to part
session.persist( item );
// delete cascades to part also
session.delete( item );
assertFalse( session.contains( item ), "the item is contained in the session after deletion" );
assertFalse( session.contains( part ), "the part is contained in the session after deletion" );
// now try to persist again as a "unschedule removal" operation
session.persist( item );
assertTrue( session.contains( item ), "the item is contained in the session after deletion" );
assertTrue( session.contains( part ), "the part is contained in the session after deletion" );
}
);
// clean up
inTransaction(
session ->
session.delete( item )
);
}
@Test
public void testRemoveChildThenFlushWithCascadePersist() {
Item item = new Item();
inTransaction(
session -> {
item.setName( "dummy" );
Part child = new Part( item, "child", "1234", BigDecimal.ONE );
// persist cascades to part
session.persist( item );
// delete the part
session.delete( child );
assertFalse(
session.contains( child ),
"the child is contained in the session, since it is deleted"
);
// now try to flush, which will attempt to cascade persist again to child.
session.flush();
assertTrue(
session.contains( child ),
"Now it is consistent again since if was cascade-persisted by the flush()"
);
}
);
// clean up
inTransaction(
session ->
session.delete( item )
);
}
}

View File

@ -6,32 +6,32 @@
*/ */
package org.hibernate.orm.test.jpa.txn; package org.hibernate.orm.test.jpa.txn;
import org.hibernate.Session; import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.engine.transaction.internal.jta.JtaStatusHelper; import org.hibernate.engine.transaction.internal.jta.JtaStatusHelper;
import org.hibernate.orm.test.jpa.model.AbstractJPATest;
import org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorBuilderImpl; import org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorBuilderImpl;
import org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorImpl; import org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorImpl;
import org.hibernate.testing.jta.TestingJtaBootstrap; import org.hibernate.testing.jta.TestingJtaBootstrap;
import org.hibernate.testing.jta.TestingJtaPlatformImpl; import org.hibernate.testing.jta.TestingJtaPlatformImpl;
import org.hibernate.testing.junit4.ExtraAssertions; import org.hibernate.testing.orm.junit.ExtraAssertions;
import org.hibernate.test.jpa.AbstractJPATest; import org.junit.jupiter.api.Test;
import org.junit.Test;
import static org.junit.Assert.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
/** /**
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public class JtaTransactionJoiningTest extends AbstractJPATest { public class JtaTransactionJoiningTest extends AbstractJPATest {
@Override @Override
public void configure(Configuration cfg) { protected void applySettings(StandardServiceRegistryBuilder builder) {
super.configure( cfg ); super.applySettings( builder );
TestingJtaBootstrap.prepare( cfg.getProperties() ); TestingJtaBootstrap.prepare( builder.getSettings() );
cfg.setProperty( builder.applySetting(
AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY, AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY,
JtaTransactionCoordinatorBuilderImpl.class.getName() JtaTransactionCoordinatorBuilderImpl.class.getName()
); );
@ -41,10 +41,9 @@ public class JtaTransactionJoiningTest extends AbstractJPATest {
public void testExplicitJoining() throws Exception { public void testExplicitJoining() throws Exception {
assertFalse( JtaStatusHelper.isActive( TestingJtaPlatformImpl.INSTANCE.getTransactionManager() ) ); assertFalse( JtaStatusHelper.isActive( TestingJtaPlatformImpl.INSTANCE.getTransactionManager() ) );
SessionImplementor session = (SessionImplementor) sessionFactory().withOptions() try (SessionImplementor session = (SessionImplementor) sessionFactory().withOptions()
.autoJoinTransactions( false ) .autoJoinTransactions( false )
.openSession(); .openSession()) {
ExtraAssertions.assertTyping( JtaTransactionCoordinatorImpl.class, session.getTransactionCoordinator() ); ExtraAssertions.assertTyping( JtaTransactionCoordinatorImpl.class, session.getTransactionCoordinator() );
JtaTransactionCoordinatorImpl transactionCoordinator = (JtaTransactionCoordinatorImpl) session.getTransactionCoordinator(); JtaTransactionCoordinatorImpl transactionCoordinator = (JtaTransactionCoordinatorImpl) session.getTransactionCoordinator();
@ -79,11 +78,11 @@ public class JtaTransactionJoiningTest extends AbstractJPATest {
assertTrue( transactionCoordinator.isJtaTransactionCurrentlyActive() ); assertTrue( transactionCoordinator.isJtaTransactionCurrentlyActive() );
assertTrue( transactionCoordinator.isSynchronizationRegistered() ); assertTrue( transactionCoordinator.isSynchronizationRegistered() );
assertTrue( transactionCoordinator.isJoined() ); assertTrue( transactionCoordinator.isJoined() );
}
((Session) session).close(); finally {
TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit(); TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();
} }
}
@Test @Test
public void testImplicitJoining() throws Exception { public void testImplicitJoining() throws Exception {
@ -92,12 +91,15 @@ public class JtaTransactionJoiningTest extends AbstractJPATest {
TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin(); TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
assertTrue( JtaStatusHelper.isActive( TestingJtaPlatformImpl.INSTANCE.getTransactionManager() ) ); assertTrue( JtaStatusHelper.isActive( TestingJtaPlatformImpl.INSTANCE.getTransactionManager() ) );
SessionImplementor session = (SessionImplementor) sessionFactory().withOptions() try (SessionImplementor session = (SessionImplementor) sessionFactory().withOptions()
.autoJoinTransactions( false ) .autoJoinTransactions( false )
.openSession(); .openSession()) {
session.getFlushMode(); session.getFlushMode();
} }
finally {
TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();
}
}
@Test @Test
public void control() throws Exception { public void control() throws Exception {
@ -106,17 +108,17 @@ public class JtaTransactionJoiningTest extends AbstractJPATest {
TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin(); TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
assertTrue( JtaStatusHelper.isActive( TestingJtaPlatformImpl.INSTANCE.getTransactionManager() ) ); assertTrue( JtaStatusHelper.isActive( TestingJtaPlatformImpl.INSTANCE.getTransactionManager() ) );
SessionImplementor session = (SessionImplementor) sessionFactory().openSession(); try (SessionImplementor session = (SessionImplementor) sessionFactory().openSession()) {
ExtraAssertions.assertTyping( JtaTransactionCoordinatorImpl.class, session.getTransactionCoordinator() ); ExtraAssertions.assertTyping( JtaTransactionCoordinatorImpl.class, session.getTransactionCoordinator() );
JtaTransactionCoordinatorImpl transactionCoordinator = (JtaTransactionCoordinatorImpl) session.getTransactionCoordinator(); JtaTransactionCoordinatorImpl transactionCoordinator = (JtaTransactionCoordinatorImpl) session.getTransactionCoordinator();
assertTrue( transactionCoordinator.isSynchronizationRegistered() ); assertTrue( transactionCoordinator.isSynchronizationRegistered() );
assertTrue( transactionCoordinator.isActive() ); assertTrue( transactionCoordinator.isActive() );
assertTrue( transactionCoordinator.isJoined() ); assertTrue( transactionCoordinator.isJoined() );
}
( (Session) session ).close(); finally {
TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit(); TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();
} }
}
} }

View File

@ -7,39 +7,38 @@
package org.hibernate.orm.test.jpa.txn; package org.hibernate.orm.test.jpa.txn;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorBuilderImpl; import org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorBuilderImpl;
import org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl; import org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl;
import org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorImpl;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.jta.TestingJtaBootstrap; import org.hibernate.testing.jta.TestingJtaBootstrap;
import org.hibernate.testing.junit4.ExtraAssertions; import org.hibernate.testing.orm.junit.ExtraAssertions;
import org.hibernate.test.jpa.AbstractJPATest; import org.hibernate.orm.test.jpa.model.AbstractJPATest;
import org.junit.jupiter.api.Test;
import org.junit.Test; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/** /**
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public class ResourceLocalTransactionJoiningTest extends AbstractJPATest { public class ResourceLocalTransactionJoiningTest extends AbstractJPATest {
@Override @Override
public void configure(Configuration cfg) { protected void applySettings(StandardServiceRegistryBuilder builder) {
super.configure( cfg ); super.applySettings( builder );
TestingJtaBootstrap.prepare( cfg.getProperties() ); TestingJtaBootstrap.prepare( builder.getSettings() );
cfg.setProperty( builder.applySetting(
AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY, AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY,
JdbcResourceLocalTransactionCoordinatorBuilderImpl.class.getName() JdbcResourceLocalTransactionCoordinatorBuilderImpl.class.getName()
); );
} }
@Test @Test
@TestForIssue( jiraKey = "HHH-9859" ) @TestForIssue(jiraKey = "HHH-9859")
public void testExpectations() { public void testExpectations() {
// JPA spec is very vague on what should happen here. It does vaguely // JPA spec is very vague on what should happen here. It does vaguely
// imply that jakarta.persistence.EntityManager.joinTransaction() should only be used // imply that jakarta.persistence.EntityManager.joinTransaction() should only be used
@ -47,7 +46,7 @@ public class ResourceLocalTransactionJoiningTest extends AbstractJPATest {
// And the TCK in fact does test calls to jakarta.persistence.EntityManager.isJoinedToTransaction() // And the TCK in fact does test calls to jakarta.persistence.EntityManager.isJoinedToTransaction()
// from resource-local EMs, so lets make sure those work.. // from resource-local EMs, so lets make sure those work..
Session session = sessionFactory().openSession(); try (Session session = sessionFactory().openSession()) {
JdbcResourceLocalTransactionCoordinatorImpl tc = ExtraAssertions.assertTyping( JdbcResourceLocalTransactionCoordinatorImpl tc = ExtraAssertions.assertTyping(
JdbcResourceLocalTransactionCoordinatorImpl.class, JdbcResourceLocalTransactionCoordinatorImpl.class,
( (SessionImplementor) session ).getTransactionCoordinator() ( (SessionImplementor) session ).getTransactionCoordinator()
@ -55,13 +54,16 @@ public class ResourceLocalTransactionJoiningTest extends AbstractJPATest {
assertFalse( tc.isJoined() ); assertFalse( tc.isJoined() );
session.beginTransaction(); session.beginTransaction();
try {
tc = ExtraAssertions.assertTyping( tc = ExtraAssertions.assertTyping(
JdbcResourceLocalTransactionCoordinatorImpl.class, JdbcResourceLocalTransactionCoordinatorImpl.class,
( (SessionImplementor) session ).getTransactionCoordinator() ( (SessionImplementor) session ).getTransactionCoordinator()
); );
assertTrue( tc.isJoined() ); assertTrue( tc.isJoined() );
}
finally {
session.getTransaction().rollback(); session.getTransaction().rollback();
session.close(); }
}
} }
} }

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.mapping; package org.hibernate.orm.test.mapping;
import java.util.Locale; import java.util.Locale;
@ -13,9 +13,9 @@ import org.hibernate.dialect.PostgreSQL94Dialect;
import org.hibernate.mapping.Column; import org.hibernate.mapping.Column;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
/** /**
* Aliases should always be lower-case. This tests that an alias for * Aliases should always be lower-case. This tests that an alias for

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.mapping; package org.hibernate.orm.test.mapping;
import java.io.Serializable; import java.io.Serializable;
import java.util.Objects; import java.util.Objects;
@ -14,20 +14,20 @@ import jakarta.persistence.IdClass;
import jakarta.persistence.MappedSuperclass; import jakarta.persistence.MappedSuperclass;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import org.hibernate.testing.orm.junit.DomainModel;
import org.junit.Test; import org.hibernate.testing.orm.junit.SessionFactory;
import org.junit.jupiter.api.Test;
@TestForIssue(jiraKey = "HHH-14499") @TestForIssue(jiraKey = "HHH-14499")
public class MappedSuperclassWithGenericsTest extends BaseCoreFunctionalTestCase { @DomainModel(
annotatedClasses = {
@Override MappedSuperclassWithGenericsTest.IntermediateAbstractMapped.class,
protected Class<?>[] getAnnotatedClasses() { MappedSuperclassWithGenericsTest.BaseEntity.class,
return new Class[] { MappedSuperclassWithGenericsTest.AbstractGenericMappedSuperType.class,
IntermediateAbstractMapped.class,
BaseEntity.class,
AbstractGenericMappedSuperType.class,
};
} }
)
@SessionFactory
public class MappedSuperclassWithGenericsTest {
@Test @Test
public void testIt() { public void testIt() {

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.mapping; package org.hibernate.orm.test.mapping;
import org.hibernate.MappingException; import org.hibernate.MappingException;
import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistry;
@ -13,25 +13,29 @@ import org.hibernate.boot.spi.MetadataBuildingContext;
import org.hibernate.mapping.Property; import org.hibernate.mapping.Property;
import org.hibernate.mapping.RootClass; import org.hibernate.mapping.RootClass;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.boot.MetadataBuildingContextTestingImpl; import org.hibernate.testing.boot.MetadataBuildingContextTestingImpl;
import org.junit.After; import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.junit.Assert; import org.junit.jupiter.api.AfterEach;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class PersistentClassTest extends BaseUnitTestCase { import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.fail;
@BaseUnitTest
public class PersistentClassTest {
private StandardServiceRegistry serviceRegistry; private StandardServiceRegistry serviceRegistry;
private MetadataBuildingContext metadataBuildingContext; private MetadataBuildingContext metadataBuildingContext;
@Before @BeforeEach
public void prepare() { public void prepare() {
serviceRegistry = new StandardServiceRegistryBuilder().build(); serviceRegistry = new StandardServiceRegistryBuilder().build();
metadataBuildingContext = new MetadataBuildingContextTestingImpl( serviceRegistry ); metadataBuildingContext = new MetadataBuildingContextTestingImpl( serviceRegistry );
} }
@After @AfterEach
public void release() { public void release() {
StandardServiceRegistryBuilder.destroy( serviceRegistry ); StandardServiceRegistryBuilder.destroy( serviceRegistry );
} }
@ -39,35 +43,36 @@ public class PersistentClassTest extends BaseUnitTestCase {
@Test @Test
public void testGetMappedClass() { public void testGetMappedClass() {
RootClass pc = new RootClass( metadataBuildingContext ); RootClass pc = new RootClass( metadataBuildingContext );
pc.setClassName(String.class.getName()); pc.setClassName( String.class.getName() );
Assert.assertEquals(String.class.getName(), pc.getClassName()); assertEquals( String.class.getName(), pc.getClassName() );
Assert.assertEquals(String.class, pc.getMappedClass()); assertEquals( String.class, pc.getMappedClass() );
pc.setClassName(Integer.class.getName()); pc.setClassName( Integer.class.getName() );
Assert.assertEquals(Integer.class, pc.getMappedClass()); assertEquals( Integer.class, pc.getMappedClass() );
} }
@Test @Test
public void testGetProxyInterface() { public void testGetProxyInterface() {
RootClass pc = new RootClass( metadataBuildingContext ); RootClass pc = new RootClass( metadataBuildingContext );
pc.setProxyInterfaceName(String.class.getName()); pc.setProxyInterfaceName( String.class.getName() );
Assert.assertEquals(String.class.getName(), pc.getProxyInterfaceName()); assertEquals( String.class.getName(), pc.getProxyInterfaceName() );
Assert.assertEquals(String.class, pc.getProxyInterface()); assertEquals( String.class, pc.getProxyInterface() );
pc.setProxyInterfaceName(Integer.class.getName()); pc.setProxyInterfaceName( Integer.class.getName() );
Assert.assertEquals(Integer.class, pc.getProxyInterface()); assertEquals( Integer.class, pc.getProxyInterface() );
} }
@Test @Test
public void testGetProperty() { public void testGetProperty() {
RootClass pc = new RootClass( metadataBuildingContext ); RootClass pc = new RootClass( metadataBuildingContext );
Property p = new Property(); Property p = new Property();
p.setName("name"); p.setName( "name" );
pc.addProperty(p); pc.addProperty( p );
Assert.assertEquals(p, pc.getProperty("name")); assertEquals( p, pc.getProperty( "name" ) );
Assert.assertEquals(p, pc.getProperty("name.test")); assertEquals( p, pc.getProperty( "name.test" ) );
try { try {
Assert.assertNull(pc.getProperty("test")); assertNull( pc.getProperty( "test" ) );
Assert.fail("MappingException expected"); fail( "MappingException expected" );
} catch (MappingException e) { }
catch (MappingException e) {
// expected // expected
} }
} }

View File

@ -4,11 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.mapping; package org.hibernate.orm.test.mapping;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
@ -19,26 +15,30 @@ import org.hibernate.mapping.RootClass;
import org.hibernate.mapping.SingleTableSubclass; import org.hibernate.mapping.SingleTableSubclass;
import org.hibernate.mapping.Subclass; import org.hibernate.mapping.Subclass;
import org.hibernate.mapping.UnionSubclass; import org.hibernate.mapping.UnionSubclass;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.boot.MetadataBuildingContextTestingImpl; import org.hibernate.testing.boot.MetadataBuildingContextTestingImpl;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/** /**
* Simple smoke style tests to make sure visitors keep working. * Simple smoke style tests to make sure visitors keep working.
* *
* @author max * @author max
*/ */
public class PersistentClassVisitorTest extends BaseUnitTestCase { @BaseUnitTest
public class PersistentClassVisitorTest {
private StandardServiceRegistry serviceRegistry; private StandardServiceRegistry serviceRegistry;
private MetadataBuildingContext metadataBuildingContext; private MetadataBuildingContext metadataBuildingContext;
@Before @BeforeEach
public void prepare() { public void prepare() {
serviceRegistry = new StandardServiceRegistryBuilder().build(); serviceRegistry = new StandardServiceRegistryBuilder().build();
metadataBuildingContext = new MetadataBuildingContextTestingImpl( serviceRegistry ); metadataBuildingContext = new MetadataBuildingContextTestingImpl( serviceRegistry );
} }
@After @AfterEach
public void release() { public void release() {
StandardServiceRegistryBuilder.destroy( serviceRegistry ); StandardServiceRegistryBuilder.destroy( serviceRegistry );
} }

View File

@ -4,10 +4,21 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.mapping.cascade; package org.hibernate.orm.test.mapping.cascade;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import org.hibernate.LazyInitializationException;
import org.hibernate.Session;
import org.hibernate.stat.SessionStatistics;
import org.hibernate.testing.TestForIssue;
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 jakarta.persistence.CascadeType; import jakarta.persistence.CascadeType;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
@ -19,105 +30,99 @@ import jakarta.persistence.OneToMany;
import jakarta.persistence.OneToOne; import jakarta.persistence.OneToOne;
import jakarta.persistence.Table; import jakarta.persistence.Table;
import org.hibernate.LazyInitializationException; import static org.junit.jupiter.api.Assertions.assertEquals;
import org.hibernate.Session; import static org.junit.jupiter.api.Assertions.fail;
import org.hibernate.stat.SessionStatistics;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.junit.Assert;
import org.junit.Test;
import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate;
import static org.junit.Assert.fail;
/** /**
* Testing relationships between components: example invoice -> invoice line * Testing relationships between components: example invoice -> invoice line
* *
* @author Jan-Oliver Lustig, Sebastian Viefhaus * @author Jan-Oliver Lustig, Sebastian Viefhaus
*/ */
public class PersistOnLazyCollectionTest extends BaseCoreFunctionalTestCase{ @DomainModel(
annotatedClasses = {
PersistOnLazyCollectionTest.Invoice.class,
PersistOnLazyCollectionTest.InvoiceLine.class,
PersistOnLazyCollectionTest.Receipt.class
}
)
@SessionFactory
public class PersistOnLazyCollectionTest {
static String RECEIPT_A = "Receipt A"; static String RECEIPT_A = "Receipt A";
static String INVOICE_A = "Invoice A"; static String INVOICE_A = "Invoice A";
static String INVOICELINE_A = "InvoiceLine A"; static String INVOICELINE_A = "InvoiceLine A";
static String INVOICELINE_B = "InvoiceLine B"; static String INVOICELINE_B = "InvoiceLine B";
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] {
Invoice.class,
InvoiceLine.class,
Receipt.class
};
}
public Invoice createInvoiceWithTwoInvoiceLines(Session session) { public Invoice createInvoiceWithTwoInvoiceLines(Session session) {
InvoiceLine lineA = new InvoiceLine(INVOICELINE_A); InvoiceLine lineA = new InvoiceLine( INVOICELINE_A );
InvoiceLine lineB = new InvoiceLine(INVOICELINE_B); InvoiceLine lineB = new InvoiceLine( INVOICELINE_B );
Invoice invoice = new Invoice(INVOICE_A); Invoice invoice = new Invoice( INVOICE_A );
invoice.addInvoiceLine(lineA); invoice.addInvoiceLine( lineA );
invoice.addInvoiceLine(lineB); invoice.addInvoiceLine( lineB );
session.persist(invoice); session.persist( invoice );
return invoice; return invoice;
} }
@Test @Test
@TestForIssue( jiraKey = "HHH-11916" ) @TestForIssue(jiraKey = "HHH-11916")
public void testPersistOnAlreadyPersistentEntityWithUninitializedLazyCollection() { public void testPersistOnAlreadyPersistentEntityWithUninitializedLazyCollection(SessionFactoryScope scope) {
final Invoice _invoice = doInHibernate( this::sessionFactory, this::createInvoiceWithTwoInvoiceLines ); final Invoice _invoice = scope.fromTransaction( session -> createInvoiceWithTwoInvoiceLines( session ) );
Invoice invoiceAfter = doInHibernate( this::sessionFactory, session -> { Invoice invoiceAfter = scope.fromTransaction( session -> {
SessionStatistics stats = session.getStatistics(); SessionStatistics stats = session.getStatistics();
// load invoice, invoiceLines should not be loaded // load invoice, invoiceLines should not be loaded
Invoice invoice = session.get(Invoice.class, _invoice.getId()); Invoice invoice = session.get( Invoice.class, _invoice.getId() );
Assert.assertEquals( assertEquals(
"Invoice lines should not be initialized while loading the invoice, " + 1,
"because of the lazy association.", 1, stats.getEntityCount()); stats.getEntityCount(),
"Invoice lines should not be initialized while loading the invoice, because of the lazy association."
);
invoice.setName(invoice.getName() + " !"); invoice.setName( invoice.getName() + " !" );
return invoice; return invoice;
} ); } );
try { try {
invoiceAfter.getInvoiceLines().size(); invoiceAfter.getInvoiceLines().size();
fail("Should throw LazyInitializationException"); fail( "Should throw LazyInitializationException" );
} }
catch (LazyInitializationException expected) { catch (LazyInitializationException expected) {
} }
} }
@Test @Test
@TestForIssue( jiraKey = "HHH-11916" ) @TestForIssue(jiraKey = "HHH-11916")
public void testPersistOnNewEntityRelatedToAlreadyPersistentEntityWithUninitializedLazyCollection() { public void testPersistOnNewEntityRelatedToAlreadyPersistentEntityWithUninitializedLazyCollection(
final Invoice _invoice = doInHibernate( this::sessionFactory, this::createInvoiceWithTwoInvoiceLines ); SessionFactoryScope scope) {
final Invoice _invoice = scope.fromTransaction( session -> createInvoiceWithTwoInvoiceLines( session ) );
Invoice invoiceAfter = doInHibernate( this::sessionFactory, session -> { Invoice invoiceAfter = scope.fromTransaction( session -> {
SessionStatistics stats = session.getStatistics(); SessionStatistics stats = session.getStatistics();
// load invoice, invoiceLines should not be loaded // load invoice, invoiceLines should not be loaded
Invoice invoice = session.get(Invoice.class, _invoice.getId()); Invoice invoice = session.get( Invoice.class, _invoice.getId() );
Assert.assertEquals( assertEquals( 1,
"Invoice lines should not be initialized while loading the invoice, " + stats.getEntityCount(),
"because of the lazy association.", 1, stats.getEntityCount()); "Invoice lines should not be initialized while loading the invoice, because of the lazy association."
);
Receipt receipt = new Receipt(RECEIPT_A); Receipt receipt = new Receipt( RECEIPT_A );
receipt.setInvoice(invoice); receipt.setInvoice( invoice );
session.persist(receipt); session.persist( receipt );
return invoice; return invoice;
} ); } );
try { try {
invoiceAfter.getInvoiceLines().size(); invoiceAfter.getInvoiceLines().size();
fail("Should throw LazyInitializationException"); fail( "Should throw LazyInitializationException" );
} }
catch (LazyInitializationException expected) { catch (LazyInitializationException expected) {
} }
@ -168,7 +173,7 @@ public class PersistOnLazyCollectionTest extends BaseCoreFunctionalTestCase{
} }
public void addInvoiceLine(InvoiceLine invoiceLine) { public void addInvoiceLine(InvoiceLine invoiceLine) {
invoiceLines.add(invoiceLine); invoiceLines.add( invoiceLine );
} }
} }
@ -206,7 +211,7 @@ public class PersistOnLazyCollectionTest extends BaseCoreFunctionalTestCase{
@Table(name = "OTM_Receipt") @Table(name = "OTM_Receipt")
public static class Receipt { public static class Receipt {
@OneToOne(cascade = { CascadeType.PERSIST}) @OneToOne(cascade = { CascadeType.PERSIST })
private Invoice invoice; private Invoice invoice;
@Id @Id

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.mapping.joinformula; package org.hibernate.orm.test.mapping.joinformula;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;

View File

@ -0,0 +1,44 @@
/*
* 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.orm.test.mapping.joinformula;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.ServiceRegistry;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.hibernate.testing.orm.junit.Setting;
import org.junit.jupiter.api.Test;
@DomainModel(
annotatedClasses = {
ParentEntity.class,
ChildEntity.class
}
)
@SessionFactory
@ServiceRegistry(
settings = {
@Setting(name = AvailableSettings.SHOW_SQL, value = "true"),
@Setting(name = AvailableSettings.FORMAT_SQL, value = "true")
}
)
public class JoinFormulaTest {
@Test
public void hhh13722Test(SessionFactoryScope scope) {
scope.inSession(
s -> {
//Nothing to do: the test just needs to verify that
//this can boot.
}
);
}
}

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.mapping.joinformula; package org.hibernate.orm.test.mapping.joinformula;
import org.hibernate.annotations.JoinColumnOrFormula; import org.hibernate.annotations.JoinColumnOrFormula;
import org.hibernate.annotations.JoinColumnsOrFormulas; import org.hibernate.annotations.JoinColumnsOrFormulas;

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.mapping.lazytoone; package org.hibernate.orm.test.mapping.lazytoone;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.Id; import jakarta.persistence.Id;

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.mapping.lazytoone; package org.hibernate.orm.test.mapping.lazytoone;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.mapping.lazytoone; package org.hibernate.orm.test.mapping.lazytoone;
import org.hibernate.Hibernate; import org.hibernate.Hibernate;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.mapping.lazytoone; package org.hibernate.orm.test.mapping.lazytoone;
import org.hibernate.Hibernate; import org.hibernate.Hibernate;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.mapping.lazytoone; package org.hibernate.orm.test.mapping.lazytoone;
import java.math.BigDecimal; import java.math.BigDecimal;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.mapping.lazytoone; package org.hibernate.orm.test.mapping.lazytoone;
import org.hibernate.Hibernate; import org.hibernate.Hibernate;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.mapping.lazytoone; package org.hibernate.orm.test.mapping.lazytoone;
import java.math.BigDecimal; import java.math.BigDecimal;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.mapping.lazytoone; package org.hibernate.orm.test.mapping.lazytoone;
import java.math.BigDecimal; import java.math.BigDecimal;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.mapping.lazytoone.mappedby; package org.hibernate.orm.test.mapping.lazytoone.mappedby;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.Id; import jakarta.persistence.Id;

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.mapping.lazytoone.onetoone; package org.hibernate.orm.test.mapping.lazytoone.onetoone;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.Id; import jakarta.persistence.Id;

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.mapping.lazytoone.onetoone; package org.hibernate.orm.test.mapping.lazytoone.onetoone;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.Id; import jakarta.persistence.Id;

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.mapping.lazytoone.onetoone; package org.hibernate.orm.test.mapping.lazytoone.onetoone;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.Id; import jakarta.persistence.Id;

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.mapping.lazytoone.polymorphic; package org.hibernate.orm.test.mapping.lazytoone.polymorphic;
import java.math.BigDecimal; import java.math.BigDecimal;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.mapping.lazytoone.polymorphic; package org.hibernate.orm.test.mapping.lazytoone.polymorphic;
import java.math.BigDecimal; import java.math.BigDecimal;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.mapping.lazytoone.polymorphic; package org.hibernate.orm.test.mapping.lazytoone.polymorphic;
import java.math.BigDecimal; import java.math.BigDecimal;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;

View File

@ -8,9 +8,8 @@ package org.hibernate.orm.test.query.hql;
import org.hibernate.Session; import org.hibernate.Session;
import org.junit.Test; import org.hibernate.orm.test.jpa.model.AbstractJPATest;
import org.junit.jupiter.api.Test;
import org.hibernate.test.jpa.AbstractJPATest;
/** /**
* Test use of the JPA 2.1 FUNCTION keyword. * Test use of the JPA 2.1 FUNCTION keyword.
@ -21,17 +20,17 @@ public class FunctionKeywordTest extends AbstractJPATest {
@Test @Test
public void basicFixture() { public void basicFixture() {
Session s = openSession(); try (Session session = sessionFactoryScope().getSessionFactory().openSession()) {
s.createQuery( "select i from Item i where substring( i.name, 1, 3 ) = 'abc'" ) session.createQuery( "select i from Item i where substring( i.name, 1, 3 ) = 'abc'" )
.list(); .list();
s.close(); }
} }
@Test @Test
public void basicTest() { public void basicTest() {
Session s = openSession(); try (Session session = sessionFactoryScope().getSessionFactory().openSession()) {
s.createQuery( "select i from Item i where function( 'substring', i.name, 1, 3 ) = 'abc'" ) session.createQuery( "select i from Item i where function( 'substring', i.name, 1, 3 ) = 'abc'" )
.list(); .list();
s.close(); }
} }
} }

View File

@ -10,9 +10,8 @@ import java.math.BigDecimal;
import org.hibernate.Session; import org.hibernate.Session;
import org.junit.Test; import org.hibernate.orm.test.jpa.model.AbstractJPATest;
import org.junit.jupiter.api.Test;
import org.hibernate.test.jpa.AbstractJPATest;
/** /**
* Tests of the JPA decision (ugh) to use ON as a keyword for what Hibernate/HQL termed WITH. * Tests of the JPA decision (ugh) to use ON as a keyword for what Hibernate/HQL termed WITH.
@ -22,10 +21,10 @@ import org.hibernate.test.jpa.AbstractJPATest;
public class OnKeywordTest extends AbstractJPATest { public class OnKeywordTest extends AbstractJPATest {
@Test @Test
public void basicTest() { public void basicTest() {
Session s = openSession(); try (Session s = sessionFactory().openSession()) {
s.createQuery( "select i from Item i join i.parts p on p.unitPrice > :filterPrice" ) s.createQuery( "select i from Item i join i.parts p on p.unitPrice > :filterPrice" )
.setParameter( "filterPrice", new BigDecimal( 100 ) ) .setParameter( "filterPrice", new BigDecimal( 100 ) )
.list(); .list();
s.close(); }
} }
} }

View File

@ -4,20 +4,16 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.type; package org.hibernate.orm.test.type;
import java.io.Serializable; import java.io.Serializable;
import java.util.Arrays; import java.util.Arrays;
import java.util.Map; import java.util.Map;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import org.hibernate.boot.model.TypeContributions; import org.hibernate.boot.model.TypeContributions;
import org.hibernate.boot.model.TypeContributor; import org.hibernate.boot.model.TypeContributor;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.jpa.boot.spi.TypeContributorList; import org.hibernate.jpa.boot.spi.TypeContributorList;
import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase;
import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.AbstractSingleColumnStandardBasicType; import org.hibernate.type.AbstractSingleColumnStandardBasicType;
import org.hibernate.type.descriptor.WrapperOptions; import org.hibernate.type.descriptor.WrapperOptions;
@ -25,12 +21,19 @@ import org.hibernate.type.descriptor.java.AbstractClassJavaTypeDescriptor;
import org.hibernate.type.descriptor.jdbc.LongVarcharJdbcType; import org.hibernate.type.descriptor.jdbc.LongVarcharJdbcType;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.junit.Test; import org.hibernate.testing.orm.junit.EntityManagerFactoryBasedFunctionalTest;
import org.junit.jupiter.api.Test;
import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; import jakarta.persistence.Column;
import static org.junit.Assert.assertEquals; import jakarta.persistence.Entity;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
public class LongListTypeContributorTest extends BaseEntityManagerFunctionalTestCase { import static org.junit.jupiter.api.Assertions.assertEquals;
public class LongListTypeContributorTest extends EntityManagerFactoryBasedFunctionalTest {
@Override @Override
public Class[] getAnnotatedClasses() { public Class[] getAnnotatedClasses() {
@ -40,8 +43,8 @@ public class LongListTypeContributorTest extends BaseEntityManagerFunctionalTest
} }
@Override @Override
protected void afterEntityManagerFactoryBuilt() { protected void entityManagerFactoryBuilt(EntityManagerFactory factory) {
entityManagerFactory().getMetamodel().getTypeConfiguration().getJavaTypeDescriptorRegistry() ( (SessionFactoryImplementor) factory ).getTypeConfiguration().getJavaTypeDescriptorRegistry()
.addDescriptor( StringifiedCollectionTypeContributor.StringifiedCollectionJavaTypeDescriptor.INSTANCE ); .addDescriptor( StringifiedCollectionTypeContributor.StringifiedCollectionJavaTypeDescriptor.INSTANCE );
} }
@ -57,27 +60,27 @@ public class LongListTypeContributorTest extends BaseEntityManagerFunctionalTest
@TestForIssue(jiraKey = "HHH-11409") @TestForIssue(jiraKey = "HHH-11409")
public void testParameterRegisterredCollection() { public void testParameterRegisterredCollection() {
LongList longList = new LongList(5L, 11L, 6123L, -61235L, 24L); LongList longList = new LongList( 5L, 11L, 6123L, -61235L, 24L );
doInJPA( this::entityManagerFactory, em -> { inTransaction( em -> {
SpecialItem item = new SpecialItem( "LongList", longList ); SpecialItem item = new SpecialItem( "LongList", longList );
em.persist( item ); em.persist( item );
} ); } );
doInJPA( this::entityManagerFactory, em -> { inTransaction( em -> {
SpecialItem item = (SpecialItem) em.createNativeQuery( SpecialItem item = (SpecialItem) em.createNativeQuery(
"SELECT * FROM special_table WHERE longList = ?", SpecialItem.class ) "SELECT * FROM special_table WHERE longList = ?", SpecialItem.class )
.setParameter(1, longList) .setParameter( 1, longList )
.getSingleResult(); .getSingleResult();
assertEquals( "LongList", item.getName() ); assertEquals( "LongList", item.getName() );
} ); } );
doInJPA( this::entityManagerFactory, em -> { inTransaction( em -> {
SpecialItem item = (SpecialItem) em.createNativeQuery( SpecialItem item = (SpecialItem) em.createNativeQuery(
"SELECT * FROM special_table WHERE longList = :longList", SpecialItem.class ) "SELECT * FROM special_table WHERE longList = :longList", SpecialItem.class )
.setParameter("longList", longList) .setParameter( "longList", longList )
.getSingleResult(); .getSingleResult();
assertEquals( "LongList", item.getName() ); assertEquals( "LongList", item.getName() );
@ -155,9 +158,11 @@ public class LongListTypeContributorTest extends BaseEntityManagerFunctionalTest
public static final StringifiedCollectionType INSTANCE = new StringifiedCollectionType(); public static final StringifiedCollectionType INSTANCE = new StringifiedCollectionType();
public StringifiedCollectionType() { public StringifiedCollectionType() {
super( LongVarcharJdbcType.INSTANCE, super(
StringifiedCollectionJavaTypeDescriptor.INSTANCE ); LongVarcharJdbcType.INSTANCE,
regKeys = new String[]{ LongList.class.getName() }; StringifiedCollectionJavaTypeDescriptor.INSTANCE
);
regKeys = new String[] { LongList.class.getName() };
name = "StringifiedCollection"; name = "StringifiedCollection";
} }

View File

@ -8,14 +8,10 @@ package org.hibernate.orm.test.unionsubclass;
import java.sql.Connection; import java.sql.Connection;
import java.util.List; import java.util.List;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.JoinType;
import jakarta.persistence.criteria.Root;
import org.hibernate.Hibernate; import org.hibernate.Hibernate;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.SQLServerDialect; import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
@ -24,50 +20,45 @@ import org.hibernate.resource.jdbc.spi.PhysicalConnectionHandlingMode;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.jdbc.SQLServerSnapshotIsolationConnectionProvider; import org.hibernate.testing.jdbc.SQLServerSnapshotIsolationConnectionProvider;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import org.hibernate.testing.orm.junit.BaseSessionFactoryFunctionalTest;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; import jakarta.persistence.criteria.CriteriaBuilder;
import static org.junit.Assert.assertEquals; import jakarta.persistence.criteria.CriteriaQuery;
import static org.junit.Assert.assertFalse; import jakarta.persistence.criteria.JoinType;
import static org.junit.Assert.assertNotNull; import jakarta.persistence.criteria.Root;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** /**
* @author Gavin King * @author Gavin King
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public class UnionSubclassTest extends BaseCoreFunctionalTestCase { public class UnionSubclassTest extends BaseSessionFactoryFunctionalTest {
private SQLServerSnapshotIsolationConnectionProvider connectionProvider = private SQLServerSnapshotIsolationConnectionProvider connectionProvider =
new SQLServerSnapshotIsolationConnectionProvider(); new SQLServerSnapshotIsolationConnectionProvider();
@Override @Override
public void configure(Configuration cfg) { protected String[] getOrmXmlFiles() {
super.configure( cfg ); return new String[] { "org/hibernate/orm/test/unionsubclass/Beings.hbm.xml" };
}
@Override
protected void applySettings(StandardServiceRegistryBuilder builder) {
super.applySettings( builder );
if ( SQLServerDialect.class.isAssignableFrom( DIALECT.getClass() ) ) { if ( SQLServerDialect.class.isAssignableFrom( DIALECT.getClass() ) ) {
connectionProvider.setConnectionProvider( (ConnectionProvider) cfg.getProperties().get( AvailableSettings.CONNECTION_PROVIDER ) ); connectionProvider.setConnectionProvider( (ConnectionProvider) builder.getSettings()
cfg.getProperties().put( AvailableSettings.CONNECTION_PROVIDER, connectionProvider ); .get( AvailableSettings.CONNECTION_PROVIDER ) );
builder.applySetting( AvailableSettings.CONNECTION_PROVIDER, connectionProvider );
} }
} }
@Override
protected void releaseSessionFactory() {
super.releaseSessionFactory();
connectionProvider.stop();
}
@Override
protected String getBaseForMappings() {
return "org/hibernate/orm/test/";
}
@Override
public String[] getMappings() {
return new String[] { "unionsubclass/Beings.hbm.xml" };
}
@Test @Test
public void testUnionSubclassCollection() { public void testUnionSubclassCollection() {
inTransaction( inTransaction(
@ -92,7 +83,7 @@ public class UnionSubclassTest extends BaseCoreFunctionalTestCase {
CriteriaQuery<Human> criteria = criteriaBuilder.createQuery( Human.class ); CriteriaQuery<Human> criteria = criteriaBuilder.createQuery( Human.class );
criteria.from( Human.class ); criteria.from( Human.class );
Human gavin = s.createQuery( criteria ).uniqueResult(); Human gavin = s.createQuery( criteria ).uniqueResult();
assertEquals( gavin.getInfo().size(), 2 ); assertEquals( 2, gavin.getInfo().size() );
s.delete( gavin ); s.delete( gavin );
s.delete( gavin.getLocation() ); s.delete( gavin.getLocation() );
} }
@ -183,34 +174,34 @@ public class UnionSubclassTest extends BaseCoreFunctionalTestCase {
hive = (Hive) s.createQuery( "from Hive h" ).uniqueResult(); hive = (Hive) s.createQuery( "from Hive h" ).uniqueResult();
assertFalse( Hibernate.isInitialized( hive.getMembers() ) ); assertFalse( Hibernate.isInitialized( hive.getMembers() ) );
assertEquals( hive.getMembers().size(), 2 ); assertEquals( 2, hive.getMembers().size() );
s.clear(); s.clear();
hive = (Hive) s.createQuery( "from Hive h left join fetch h.location left join fetch h.members" ) hive = (Hive) s.createQuery( "from Hive h left join fetch h.location left join fetch h.members" )
.uniqueResult(); .uniqueResult();
assertTrue( Hibernate.isInitialized( hive.getMembers() ) ); assertTrue( Hibernate.isInitialized( hive.getMembers() ) );
assertEquals( hive.getMembers().size(), 2 ); assertEquals( 2, hive.getMembers().size() );
s.clear(); s.clear();
x23y4 = (Alien) s.createQuery( "from Alien a left join fetch a.hivemates where a.identity like 'x%'" ) x23y4 = (Alien) s.createQuery( "from Alien a left join fetch a.hivemates where a.identity like 'x%'" )
.uniqueResult(); .uniqueResult();
assertTrue( Hibernate.isInitialized( x23y4.getHivemates() ) ); assertTrue( Hibernate.isInitialized( x23y4.getHivemates() ) );
assertEquals( x23y4.getHivemates().size(), 1 ); assertEquals( 1, x23y4.getHivemates().size() );
s.clear(); s.clear();
x23y4 = (Alien) s.createQuery( "from Alien a where a.identity like 'x%'" ).uniqueResult(); x23y4 = (Alien) s.createQuery( "from Alien a where a.identity like 'x%'" ).uniqueResult();
assertFalse( Hibernate.isInitialized( x23y4.getHivemates() ) ); assertFalse( Hibernate.isInitialized( x23y4.getHivemates() ) );
assertEquals( x23y4.getHivemates().size(), 1 ); assertEquals( 1, x23y4.getHivemates().size() );
s.clear(); s.clear();
CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder();
CriteriaQuery<Alien> criteria = criteriaBuilder.createQuery( Alien.class ); CriteriaQuery<Alien> criteria = criteriaBuilder.createQuery( Alien.class );
Root<Alien> root = criteria.from( Alien.class ); Root<Alien> root = criteria.from( Alien.class );
criteria.orderBy( criteriaBuilder.asc( root.get("identity") ) ); criteria.orderBy( criteriaBuilder.asc( root.get( "identity" ) ) );
x23y4 = s.createQuery( criteria ).list().get( 0 ); x23y4 = s.createQuery( criteria ).list().get( 0 );
// x23y4 = (Alien) s.createCriteria( Alien.class ).addOrder( Order.asc( "identity" ) ).list().get( 0 ); // x23y4 = (Alien) s.createCriteria( Alien.class ).addOrder( Order.asc( "identity" ) ).list().get( 0 );
s.delete( x23y4.getHive() ); s.delete( x23y4.getHive() );
@ -259,18 +250,19 @@ public class UnionSubclassTest extends BaseCoreFunctionalTestCase {
thing = (Thing) s.createQuery( "from Thing t left join fetch t.owner" ).uniqueResult(); thing = (Thing) s.createQuery( "from Thing t left join fetch t.owner" ).uniqueResult();
assertTrue( Hibernate.isInitialized( thing.getOwner() ) ); assertTrue( Hibernate.isInitialized( thing.getOwner() ) );
assertEquals( thing.getOwner().getIdentity(), "gavin" ); assertEquals( "gavin", thing.getOwner().getIdentity() );
s.clear(); s.clear();
thing = (Thing) s.createQuery( "select t from Thing t left join t.owner where t.owner.identity='gavin'" ) thing = (Thing) s.createQuery(
"select t from Thing t left join t.owner where t.owner.identity='gavin'" )
.uniqueResult(); .uniqueResult();
assertFalse( Hibernate.isInitialized( thing.getOwner() ) ); assertFalse( Hibernate.isInitialized( thing.getOwner() ) );
assertEquals( thing.getOwner().getIdentity(), "gavin" ); assertEquals( "gavin", thing.getOwner().getIdentity() );
s.clear(); s.clear();
gavin = (Human) s.createQuery( "from Human h left join fetch h.things" ).uniqueResult(); gavin = (Human) s.createQuery( "from Human h left join fetch h.things" ).uniqueResult();
assertTrue( Hibernate.isInitialized( gavin.getThings() ) ); assertTrue( Hibernate.isInitialized( gavin.getThings() ) );
assertEquals( ( (Thing) gavin.getThings().get( 0 ) ).getDescription(), "some thing" ); assertEquals( "some thing", ( (Thing) gavin.getThings().get( 0 ) ).getDescription() );
s.clear(); s.clear();
assertTrue( s.createQuery( "from Being b left join fetch b.things" ).list().size() == 2 ); assertTrue( s.createQuery( "from Being b left join fetch b.things" ).list().size() == 2 );
@ -278,24 +270,26 @@ public class UnionSubclassTest extends BaseCoreFunctionalTestCase {
gavin = (Human) s.createQuery( "from Being b join fetch b.things" ).uniqueResult(); gavin = (Human) s.createQuery( "from Being b join fetch b.things" ).uniqueResult();
assertTrue( Hibernate.isInitialized( gavin.getThings() ) ); assertTrue( Hibernate.isInitialized( gavin.getThings() ) );
assertEquals( ( (Thing) gavin.getThings().get( 0 ) ).getDescription(), "some thing" ); assertEquals( "some thing", ( (Thing) gavin.getThings().get( 0 ) ).getDescription() );
s.clear(); s.clear();
gavin = (Human) s.createQuery( "select h from Human h join h.things t where t.description='some thing'" ) gavin = (Human) s.createQuery(
"select h from Human h join h.things t where t.description='some thing'" )
.uniqueResult(); .uniqueResult();
assertFalse( Hibernate.isInitialized( gavin.getThings() ) ); assertFalse( Hibernate.isInitialized( gavin.getThings() ) );
assertEquals( ( (Thing) gavin.getThings().get( 0 ) ).getDescription(), "some thing" ); assertEquals( "some thing", ( (Thing) gavin.getThings().get( 0 ) ).getDescription() );
s.clear(); s.clear();
gavin = (Human) s.createQuery( "select b from Being b join b.things t where t.description='some thing'" ) gavin = (Human) s.createQuery(
"select b from Being b join b.things t where t.description='some thing'" )
.uniqueResult(); .uniqueResult();
assertFalse( Hibernate.isInitialized( gavin.getThings() ) ); assertFalse( Hibernate.isInitialized( gavin.getThings() ) );
assertEquals( ( (Thing) gavin.getThings().get( 0 ) ).getDescription(), "some thing" ); assertEquals( "some thing", ( (Thing) gavin.getThings().get( 0 ) ).getDescription() );
s.clear(); s.clear();
thing = s.get( Thing.class, thing.getId() ); thing = s.get( Thing.class, thing.getId() );
assertFalse( Hibernate.isInitialized( thing.getOwner() ) ); assertFalse( Hibernate.isInitialized( thing.getOwner() ) );
assertEquals( thing.getOwner().getIdentity(), "gavin" ); assertEquals( "gavin", thing.getOwner().getIdentity() );
thing.getOwner().getThings().remove( thing ); thing.getOwner().getThings().remove( thing );
thing.setOwner( x23y4 ); thing.setOwner( x23y4 );
@ -307,7 +301,8 @@ public class UnionSubclassTest extends BaseCoreFunctionalTestCase {
thing = s.get( Thing.class, thing.getId() ); thing = s.get( Thing.class, thing.getId() );
assertFalse( Hibernate.isInitialized( thing.getOwner() ) ); assertFalse( Hibernate.isInitialized( thing.getOwner() ) );
assertEquals( thing.getOwner().getIdentity(), "x23y4$$hu%3" ); assertEquals( "x23y4$$hu%3", thing.getOwner().getIdentity()
);
s.delete( thing ); s.delete( thing );
CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder();
@ -352,20 +347,20 @@ public class UnionSubclassTest extends BaseCoreFunctionalTestCase {
x23y4.setHive( hive ); x23y4.setHive( hive );
s.persist( hive ); s.persist( hive );
assertEquals( s.createQuery( "from Being" ).list().size(), 2 ); assertEquals( 2, s.createQuery( "from Being" ).list().size() );
assertEquals( s.createQuery( "from Being b where b.class = Alien" ).list().size(), 1 ); assertEquals( 1, s.createQuery( "from Being b where b.class = Alien" ).list().size() );
assertEquals( s.createQuery( "from Being b where type(b) = :what" ).setParameter( assertEquals( 1, s.createQuery( "from Being b where type(b) = :what" ).setParameter(
"what", "what",
Alien.class Alien.class
).list().size(), 1 ); ).list().size() );
assertEquals( s.createQuery( "from Being b where type(b) in :what" ).setParameterList( assertEquals( 2, s.createQuery( "from Being b where type(b) in :what" ).setParameterList(
"what", "what",
new Class[] { new Class[] {
Alien.class, Alien.class,
Human.class Human.class
} }
).list().size(), 2 ); ).list().size() );
assertEquals( s.createQuery( "from Alien" ).list().size(), 1 ); assertEquals( 1, s.createQuery( "from Alien" ).list().size() );
s.clear(); s.clear();
List beings = s.createQuery( "from Being b left join fetch b.location" ).list(); List beings = s.createQuery( "from Being b left join fetch b.location" ).list();
@ -376,7 +371,7 @@ public class UnionSubclassTest extends BaseCoreFunctionalTestCase {
assertNotNull( b.getIdentity() ); assertNotNull( b.getIdentity() );
assertNotNull( b.getSpecies() ); assertNotNull( b.getSpecies() );
} }
assertEquals( beings.size(), 2 ); assertEquals( 2, beings.size() );
s.clear(); s.clear();
beings = s.createQuery( "from Being" ).list(); beings = s.createQuery( "from Being" ).list();
@ -387,7 +382,7 @@ public class UnionSubclassTest extends BaseCoreFunctionalTestCase {
assertNotNull( b.getIdentity() ); assertNotNull( b.getIdentity() );
assertNotNull( b.getSpecies() ); assertNotNull( b.getSpecies() );
} }
assertEquals( beings.size(), 2 ); assertEquals( 2, beings.size() );
s.clear(); s.clear();
List locations = s.createQuery( "from Location" ).list(); List locations = s.createQuery( "from Location" ).list();
@ -397,11 +392,11 @@ public class UnionSubclassTest extends BaseCoreFunctionalTestCase {
assertNotNull( l.getName() ); assertNotNull( l.getName() );
for ( Object o : l.getBeings() ) { for ( Object o : l.getBeings() ) {
count++; count++;
assertSame( ( (Being) o ).getLocation(), l ); assertSame( l, ( (Being) o ).getLocation() );
} }
} }
assertEquals( count, 2 ); assertEquals( 2, count );
assertEquals( locations.size(), 3 ); assertEquals( 3, locations.size() );
s.clear(); s.clear();
locations = s.createQuery( "from Location loc left join fetch loc.beings" ).list(); locations = s.createQuery( "from Location loc left join fetch loc.beings" ).list();
@ -414,15 +409,15 @@ public class UnionSubclassTest extends BaseCoreFunctionalTestCase {
assertSame( ( (Being) o ).getLocation(), l ); assertSame( ( (Being) o ).getLocation(), l );
} }
} }
assertEquals( count, 2 ); assertEquals( 2, count );
assertEquals( locations.size(), 3 ); assertEquals( 3, locations.size() );
s.clear(); s.clear();
gavin = s.get( Human.class, gavin.getId() ); gavin = s.get( Human.class, gavin.getId() );
atl = s.get( Location.class, atl.getId() ); atl = s.get( Location.class, atl.getId() );
atl.addBeing( gavin ); atl.addBeing( gavin );
assertEquals( s.createQuery( "from Human h where h.location.name like '%GA'" ).list().size(), 1 ); assertEquals( 1, s.createQuery( "from Human h where h.location.name like '%GA'" ).list().size() );
s.delete( gavin ); s.delete( gavin );
CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder();
@ -474,8 +469,8 @@ public class UnionSubclassTest extends BaseCoreFunctionalTestCase {
@Test @Test
@TestForIssue(jiraKey = "HHH-11740") @TestForIssue(jiraKey = "HHH-11740")
public void testBulkOperationsWithDifferentConnections() throws Exception { public void testBulkOperationsWithDifferentConnections() throws Exception {
doInHibernate( inTransaction(
this::sessionFactory, s -> { s -> {
Location mars = new Location( "Mars" ); Location mars = new Location( "Mars" );
s.persist( mars ); s.persist( mars );
@ -507,7 +502,7 @@ public class UnionSubclassTest extends BaseCoreFunctionalTestCase {
// The following tests that bulk operations can be executed using 2 different // The following tests that bulk operations can be executed using 2 different
// connections. // connections.
doInHibernate( this::sessionFactory, s1 -> { inTransaction( s1 -> {
// Transaction used by s1 is already started. // Transaction used by s1 is already started.
// Assert that the Connection is already physically connected. // Assert that the Connection is already physically connected.
SharedSessionContractImplementor s1Implementor = (SharedSessionContractImplementor) s1; SharedSessionContractImplementor s1Implementor = (SharedSessionContractImplementor) s1;
@ -526,7 +521,7 @@ public class UnionSubclassTest extends BaseCoreFunctionalTestCase {
// after a second Session (with a different connection) is used // after a second Session (with a different connection) is used
// for a bulk operation. // for a bulk operation.
doInHibernate( this::sessionFactory, s2 -> { inTransaction( s2 -> {
// Check same assertions for s2 as was done for s1. // Check same assertions for s2 as was done for s1.
SharedSessionContractImplementor s2Implementor = (SharedSessionContractImplementor) s2; SharedSessionContractImplementor s2Implementor = (SharedSessionContractImplementor) s2;
assertTrue( s2Implementor.getJdbcCoordinator().getLogicalConnection().isPhysicallyConnected() ); assertTrue( s2Implementor.getJdbcCoordinator().getLogicalConnection().isPhysicallyConnected() );
@ -568,8 +563,8 @@ public class UnionSubclassTest extends BaseCoreFunctionalTestCase {
} ); } );
// Clean up // Clean up
doInHibernate( inTransaction(
this::sessionFactory, s -> { s -> {
Human human = (Human) s.createQuery( "from Being" ).uniqueResult(); Human human = (Human) s.createQuery( "from Being" ).uniqueResult();
assertEquals( "John Doe", human.getIdentity() ); assertEquals( "John Doe", human.getIdentity() );
s.createQuery( "delete from Being" ).executeUpdate(); s.createQuery( "delete from Being" ).executeUpdate();

View File

@ -6,29 +6,30 @@
*/ */
package org.hibernate.test.hql.joinedSubclass; package org.hibernate.test.hql.joinedSubclass;
import org.hibernate.testing.DialectChecks;
import org.hibernate.testing.RequiresDialectFeature;
import org.junit.Test;
import org.hibernate.Session;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import org.hibernate.testing.orm.junit.DialectFeatureChecks;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.RequiresDialectFeature;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.Test;
/** /**
* @author Steve Ebersole * @author Steve Ebersole
*/ */
@RequiresDialectFeature(DialectChecks.SupportsTemporaryTable.class) @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsTemporaryTable.class)
public class JoinedSubclassBulkManipTest extends BaseCoreFunctionalTestCase { @DomainModel(
@Override annotatedClasses = { Employee.class }
protected Class<?>[] getAnnotatedClasses() { )
return new Class[] { Employee.class }; @SessionFactory
} public class JoinedSubclassBulkManipTest {
@Test @Test
@TestForIssue( jiraKey = "HHH-1657" ) @TestForIssue(jiraKey = "HHH-1657")
public void testHqlDeleteOnJoinedSubclass() { public void testHqlDeleteOnJoinedSubclass(SessionFactoryScope scope) {
Session s = openSession(); scope.inTransaction(
s.beginTransaction(); s -> {
// syntax checking on the database... // syntax checking on the database...
s.createQuery( "delete from Employee" ).executeUpdate(); s.createQuery( "delete from Employee" ).executeUpdate();
s.createQuery( "delete from Person" ).executeUpdate(); s.createQuery( "delete from Person" ).executeUpdate();
@ -47,20 +48,23 @@ public class JoinedSubclassBulkManipTest extends BaseCoreFunctionalTestCase {
s.createQuery( "delete from Employee e where e.id = 1" ).executeUpdate(); s.createQuery( "delete from Employee e where e.id = 1" ).executeUpdate();
s.createQuery( "delete from Person where id = 1" ).executeUpdate(); s.createQuery( "delete from Person where id = 1" ).executeUpdate();
s.createQuery( "delete from Person p where p.id = 1" ).executeUpdate(); s.createQuery( "delete from Person p where p.id = 1" ).executeUpdate();
s.getTransaction().commit(); }
s.close(); );
} }
@Test @Test
@TestForIssue( jiraKey = "HHH-1657" ) @TestForIssue(jiraKey = "HHH-1657")
public void testHqlUpdateOnJoinedSubclass() { public void testHqlUpdateOnJoinedSubclass(SessionFactoryScope scope) {
Session s = openSession(); scope.inTransaction(
s.beginTransaction(); s -> {
// syntax checking on the database... // syntax checking on the database...
s.createQuery( "update Employee set name = 'Some Other Name' where employeeNumber like 'A%'" ).executeUpdate(); s.createQuery( "update Employee set name = 'Some Other Name' where employeeNumber like 'A%'" )
s.createQuery( "update Employee e set e.name = 'Some Other Name' where e.employeeNumber like 'A%'" ).executeUpdate(); .executeUpdate();
s.createQuery( "update Employee e set e.name = 'Some Other Name' where e.employeeNumber like 'A%'" )
.executeUpdate();
s.createQuery( "update Person set name = 'Some Other Name' where name like 'S%'" ).executeUpdate(); s.createQuery( "update Person set name = 'Some Other Name' where name like 'S%'" ).executeUpdate();
s.createQuery( "update Person p set p.name = 'Some Other Name' where p.name like 'S%'" ).executeUpdate(); s.createQuery( "update Person p set p.name = 'Some Other Name' where p.name like 'S%'" )
.executeUpdate();
// now the forms that actually fail from problem underlying HHH-1657 // now the forms that actually fail from problem underlying HHH-1657
// which is limited to references to properties mapped to column names existing in both tables // which is limited to references to properties mapped to column names existing in both tables
@ -70,8 +74,7 @@ public class JoinedSubclassBulkManipTest extends BaseCoreFunctionalTestCase {
s.createQuery( "update Employee e set e.name = 'Some Other Name' where e.id = 1" ).executeUpdate(); s.createQuery( "update Employee e set e.name = 'Some Other Name' where e.id = 1" ).executeUpdate();
s.createQuery( "update Person set name = 'Some Other Name' where id = 1" ).executeUpdate(); s.createQuery( "update Person set name = 'Some Other Name' where id = 1" ).executeUpdate();
s.createQuery( "update Person p set p.name = 'Some Other Name' where p.id = 1" ).executeUpdate(); s.createQuery( "update Person p set p.name = 'Some Other Name' where p.id = 1" ).executeUpdate();
}
s.getTransaction().commit(); );
s.close();
} }
} }

View File

@ -7,6 +7,13 @@
package org.hibernate.test.hql.joinedSubclass; package org.hibernate.test.hql.joinedSubclass;
import java.util.List; import java.util.List;
import org.hibernate.testing.TestForIssue;
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 jakarta.persistence.Basic; import jakarta.persistence.Basic;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
@ -19,79 +26,51 @@ import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany; import jakarta.persistence.OneToMany;
import jakarta.persistence.Table; import jakarta.persistence.Table;
import org.junit.Test;
import org.hibernate.Session;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
/** /**
* @author Stephen Fikes * @author Stephen Fikes
* @author Gail Badner * @author Gail Badner
*/ */
public class JoinedSubclassSubQueryTest extends BaseCoreFunctionalTestCase { @DomainModel(
annotatedClasses = {
JoinedSubclassSubQueryTest.InvestmentCompany.class,
JoinedSubclassSubQueryTest.Person.class,
JoinedSubclassSubQueryTest.Employee.class
}
)
@SessionFactory
public class JoinedSubclassSubQueryTest {
@Test @Test
@TestForIssue(jiraKey = "HHH-11182") @TestForIssue(jiraKey = "HHH-11182")
public void testSubQueryConstraintPropertyInSuperclassTable() { public void testSubQueryConstraintPropertyInSuperclassTable(SessionFactoryScope scope) {
Session s = openSession(); scope.inTransaction(
try { session -> {
s.getTransaction().begin();
// employee.firstName is in Person table (not Employee) // employee.firstName is in Person table (not Employee)
String queryHQL = "from InvestmentCompany investmentCompany " String queryHQL = "from InvestmentCompany investmentCompany "
+ "where exists " + "where exists "
+ "(select employee " + "(select employee "
+ "from investmentCompany.employees as employee " + "from investmentCompany.employees as employee "
+ " where employee.firstName = 'Joe')"; + " where employee.firstName = 'Joe')";
s.createQuery( queryHQL ).uniqueResult(); session.createQuery( queryHQL ).uniqueResult();
s.getTransaction().commit();
}
catch (Exception e) {
if ( s.getTransaction() != null && s.getTransaction().isActive() ) {
s.getTransaction().rollback();
}
throw e;
}
finally {
s.close();
} }
);
} }
@Test @Test
@TestForIssue(jiraKey = "HHH-11182") @TestForIssue(jiraKey = "HHH-11182")
public void testSubQueryConstraintPropertyInEntityTable() { public void testSubQueryConstraintPropertyInEntityTable(SessionFactoryScope scope) {
scope.inTransaction(
Session s = openSession(); session -> {
try {
s.getTransaction().begin();
// employee.employeeNumber is in Employee table // employee.employeeNumber is in Employee table
String queryHQL = "from InvestmentCompany investmentCompany " String queryHQL = "from InvestmentCompany investmentCompany "
+ "where exists " + "where exists "
+ "(select employee " + "(select employee "
+ "from investmentCompany.employees as employee " + "from investmentCompany.employees as employee "
+ " where employee.employeeNumber = 666 )"; + " where employee.employeeNumber = 666 )";
s.createQuery( queryHQL ).uniqueResult(); session.createQuery( queryHQL ).uniqueResult();
} }
catch (Exception e) { );
if ( s.getTransaction() != null && s.getTransaction().isActive() ) {
s.getTransaction().rollback();
}
throw e;
}
finally {
s.close();
}
}
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] {
InvestmentCompany.class,
Person.class,
Employee.class
};
} }
@Entity(name = "InvestmentCompany") @Entity(name = "InvestmentCompany")

View File

@ -1,60 +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.test.jpa;
import jakarta.persistence.metamodel.Metamodel;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.engine.spi.PersistenceContext;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase;
import org.hibernate.metamodel.MappingMetamodel;
import org.hibernate.metamodel.spi.MetamodelImplementor;
import org.hibernate.query.spi.QueryEngine;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.spi.SessionFactoryServiceRegistry;
import org.junit.Test;
/**
* @author Chris Cranford
*/
public class EntityManagerUnwrapTest extends BaseEntityManagerFunctionalTestCase {
@Test
public void testUnwrapSession() {
getOrCreateEntityManager().unwrap( Session.class );
getOrCreateEntityManager().unwrap( SessionImplementor.class );
getOrCreateEntityManager().unwrap( SharedSessionContractImplementor.class );
getOrCreateEntityManager().unwrap( PersistenceContext.class );
}
@Test
public void testUnwrapSessionFactory() {
entityManagerFactory().unwrap( SessionFactory.class );
entityManagerFactory().unwrap( SessionFactoryImplementor.class );
entityManagerFactory().unwrap( SessionFactoryServiceRegistry.class );
entityManagerFactory().unwrap( ServiceRegistry.class );
entityManagerFactory().unwrap( JdbcServices.class );
entityManagerFactory().unwrap( jakarta.persistence.Cache.class );
entityManagerFactory().unwrap( org.hibernate.Cache.class );
entityManagerFactory().unwrap( jakarta.persistence.metamodel.Metamodel.class );
entityManagerFactory().unwrap( Metamodel.class );
entityManagerFactory().unwrap( MetamodelImplementor.class );
entityManagerFactory().unwrap( MappingMetamodel.class );
entityManagerFactory().unwrap( QueryEngine.class );
}
}

View File

@ -1,86 +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.test.jpa.fetch;
import java.util.Date;
import org.junit.Test;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.test.jpa.AbstractJPATest;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author Emmanuel Bernard
*/
public class FetchingTest extends AbstractJPATest {
@Override
public String[] getMappings() {
return new String[] { "jpa/fetch/Person.hbm.xml" };
}
@Test
public void testLazy() throws Exception {
Session s;
Transaction tx;
s = openSession();
tx = s.beginTransaction();
Person p = new Person( "Gavin", "King", "JBoss Inc" );
Stay stay = new Stay( p, new Date(), new Date(), "A380", "Blah", "Blah" );
p.addStay( stay );
s.persist( p );
tx.commit();
s.clear();
tx = s.beginTransaction();
p = (Person) s.createQuery( "select p from Person p where p.firstName = :name" )
.setParameter( "name", "Gavin" ).uniqueResult();
assertFalse( Hibernate.isInitialized( p.getStays() ) );
s.delete( p );
tx.commit();
s.close();
}
@Test
public void testHibernateFetchingLazy() throws Exception {
Session s;
Transaction tx;
s = openSession();
tx = s.beginTransaction();
Person p = new Person( "Gavin", "King", "JBoss Inc" );
Stay stay = new Stay( null, new Date(), new Date(), "A380", "Blah", "Blah" );
Stay stay2 = new Stay( null, new Date(), new Date(), "A320", "Blah", "Blah" );
Stay stay3 = new Stay( null, new Date(), new Date(), "A340", "Blah", "Blah" );
stay.setOldPerson( p );
stay2.setVeryOldPerson( p );
stay3.setVeryOldPerson( p );
p.addOldStay( stay );
p.addVeryOldStay( stay2 );
p.addVeryOldStay( stay3 );
s.persist( p );
tx.commit();
s.clear();
tx = s.beginTransaction();
p = (Person) s.createQuery( "select p from Person p where p.firstName = :name" )
.setParameter( "name", "Gavin" ).uniqueResult();
assertFalse( Hibernate.isInitialized( p.getOldStays() ) );
assertEquals( 1, p.getOldStays().size() );
assertFalse( "lazy extra is failing", Hibernate.isInitialized( p.getOldStays() ) );
s.clear();
stay = (Stay) s.get( Stay.class, stay.getId() );
assertTrue( ! Hibernate.isInitialized( stay.getOldPerson() ) );
s.clear();
stay3 = (Stay) s.get( Stay.class, stay3.getId() );
assertTrue( "FetchMode.JOIN should overrides lazy options", Hibernate.isInitialized( stay3.getVeryOldPerson() ) );
s.delete( stay3.getVeryOldPerson() );
tx.commit();
s.close();
}
}

View File

@ -6,21 +6,20 @@
*/ */
package org.hibernate.test.jpa.naturalid; package org.hibernate.test.jpa.naturalid;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Environment;
import org.hibernate.orm.test.jpa.model.AbstractJPATest;
import org.junit.jupiter.api.Test;
import jakarta.persistence.PersistenceException; import jakarta.persistence.PersistenceException;
import org.junit.Test; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.fail;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.test.jpa.AbstractJPATest;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/** /**
* copied from {@link org.hibernate.orm.test.mapping.naturalid.immutable.ImmutableNaturalIdTest} * copied from {@link org.hibernate.orm.test.mapping.naturalid.immutable.ImmutableNaturalIdTest}
@ -29,110 +28,111 @@ import static org.junit.Assert.fail;
*/ */
public class ImmutableNaturalIdTest extends AbstractJPATest { public class ImmutableNaturalIdTest extends AbstractJPATest {
@Override @Override
public String[] getMappings() { protected String[] getOrmXmlFiles() {
return new String[] { "jpa/naturalid/User.hbm.xml" }; return new String[] { "org/hibernate/test/jpa/naturalid/User.hbm.xml" };
} }
@Override @Override
public void configure(Configuration cfg) { protected void applySettings(StandardServiceRegistryBuilder builder) {
super.configure( cfg ); super.applySettings( builder );
cfg.setProperty( Environment.USE_SECOND_LEVEL_CACHE, "true" ); builder.applySetting( Environment.USE_SECOND_LEVEL_CACHE, "true" );
cfg.setProperty( Environment.USE_QUERY_CACHE, "true" ); builder.applySetting( Environment.USE_QUERY_CACHE, "true" );
cfg.setProperty( Environment.GENERATE_STATISTICS, "true" ); builder.applySetting( Environment.GENERATE_STATISTICS, "true" );
} }
@Test @Test
public void testUpdate() { public void testUpdate() {
// prepare some test data... // prepare some test data...
Session session = openSession();
session.beginTransaction();
User user = new User(); User user = new User();
inTransaction(
session -> {
user.setUserName( "steve" ); user.setUserName( "steve" );
user.setEmail( "steve@hibernate.org" ); user.setEmail( "steve@hibernate.org" );
user.setPassword( "brewhaha" ); user.setPassword( "brewhaha" );
session.save( user ); session.save( user );
session.getTransaction().commit(); }
session.close(); );
// 'user' is now a detached entity, so lets change a property and reattch... // 'user' is now a detached entity, so lets change a property and reattch...
user.setPassword( "homebrew" ); user.setPassword( "homebrew" );
session = openSession(); inTransaction(
session.beginTransaction(); session ->
session.update( user ); session.update( user )
session.getTransaction().commit(); );
session.close();
// clean up // clean up
session = openSession(); inTransaction(
session.beginTransaction(); session ->
session.delete( user ); session.delete( user )
session.getTransaction().commit(); );
session.close();
} }
@Test @Test
public void testNaturalIdCheck() throws Exception { public void testNaturalIdCheck() throws Exception {
Session s = openSession(); sessionFactoryScope().inSession(
Transaction t = s.beginTransaction(); session -> {
Transaction t = session.beginTransaction();
User u = new User( "steve", "superSecret" ); User u = new User( "steve", "superSecret" );
s.persist( u ); session.persist( u );
u.setUserName( "Steve" ); u.setUserName( "Steve" );
try { try {
s.flush(); session.flush();
fail(); fail( "PersistenceException expected" );
} }
catch ( PersistenceException p ) { catch (PersistenceException p) {
//expected //expected
t.rollback(); t.rollback();
} }
u.setUserName( "steve" ); u.setUserName( "steve" );
s.delete( u ); session.delete( u );
s.close(); session.close();
}
);
} }
@Test @Test
public void testSimpleNaturalIdLoadAccessCache() { public void testSimpleNaturalIdLoadAccessCache() {
Session s = openSession(); inTransaction(
s.beginTransaction(); session -> {
User u = new User( "steve", "superSecret" ); User u = new User( "steve", "superSecret" );
s.persist( u ); session.persist( u );
s.getTransaction().commit(); }
s.close(); );
s = openSession(); inTransaction(
s.beginTransaction(); session -> {
u = (User) s.bySimpleNaturalId( User.class ).load( "steve" ); User u = session.bySimpleNaturalId( User.class ).load( "steve" );
assertNotNull( u ); assertNotNull( u );
User u2 = (User) s.bySimpleNaturalId( User.class ).getReference( "steve" ); User u2 = session.bySimpleNaturalId( User.class ).getReference( "steve" );
assertTrue( u == u2 ); assertSame( u2, u );
s.getTransaction().commit(); }
s.close(); );
s = openSession(); inTransaction(
s.beginTransaction(); session ->
s.createQuery( "delete User" ).executeUpdate(); session.createQuery( "delete User" ).executeUpdate()
s.getTransaction().commit(); );
s.close();
} }
@Test @Test
public void testNaturalIdLoadAccessCache() { public void testNaturalIdLoadAccessCache() {
Session s = openSession(); inTransaction(
s.beginTransaction(); session -> {
User u = new User( "steve", "superSecret" ); User u = new User( "steve", "superSecret" );
s.persist( u ); session.persist( u );
s.getTransaction().commit(); }
s.close(); );
sessionFactory().getStatistics().clear(); sessionFactory().getStatistics().clear();
s = openSession(); inTransaction(
s.beginTransaction(); session -> {
u = (User) s.byNaturalId( User.class ).using( "userName", "steve" ).load(); User u = (User) session.byNaturalId( User.class ).using( "userName", "steve" ).load();
assertNotNull( u ); assertNotNull( u );
s.getTransaction().commit(); }
s.close(); );
assertEquals( 1, sessionFactory().getStatistics().getEntityLoadCount() ); assertEquals( 1, sessionFactory().getStatistics().getEntityLoadCount() );
assertEquals( 0, sessionFactory().getStatistics().getSecondLevelCacheMissCount() ); assertEquals( 0, sessionFactory().getStatistics().getSecondLevelCacheMissCount() );
@ -142,36 +142,40 @@ public class ImmutableNaturalIdTest extends AbstractJPATest {
assertEquals( 0, sessionFactory().getStatistics().getNaturalIdCacheHitCount() ); assertEquals( 0, sessionFactory().getStatistics().getNaturalIdCacheHitCount() );
assertEquals( 0, sessionFactory().getStatistics().getNaturalIdCachePutCount() ); assertEquals( 0, sessionFactory().getStatistics().getNaturalIdCachePutCount() );
s = openSession(); inTransaction(
s.beginTransaction(); session -> {
User v = new User( "gavin", "supsup" ); User v = new User( "gavin", "supsup" );
s.persist( v ); session.persist( v );
s.getTransaction().commit(); }
s.close(); );
sessionFactory().getStatistics().clear(); sessionFactory().getStatistics().clear();
s = openSession(); inTransaction(
s.beginTransaction(); session -> {
u = (User) s.byNaturalId( User.class ).using( "userName", "steve" ).load(); User u = session.byNaturalId( User.class ).using( "userName", "steve" ).load();
assertNotNull( u ); assertNotNull( u );
assertEquals( 1, sessionFactory().getStatistics().getEntityLoadCount() ); assertEquals( 1, sessionFactory().getStatistics().getEntityLoadCount() );
assertEquals( 1, sessionFactory().getStatistics().getNaturalIdQueryExecutionCount() );//0: incorrect stats since hbm.xml can't enable NaturalId caching assertEquals(
1,
sessionFactory().getStatistics().getNaturalIdQueryExecutionCount()
);//0: incorrect stats since hbm.xml can't enable NaturalId caching
assertEquals( 0, sessionFactory().getStatistics().getNaturalIdCacheHitCount() ); assertEquals( 0, sessionFactory().getStatistics().getNaturalIdCacheHitCount() );
u = (User) s.byNaturalId( User.class ).using( "userName", "steve" ).load(); u = session.byNaturalId( User.class ).using( "userName", "steve" ).load();
assertNotNull( u ); assertNotNull( u );
assertEquals( 1, sessionFactory().getStatistics().getEntityLoadCount() ); assertEquals( 1, sessionFactory().getStatistics().getEntityLoadCount() );
assertEquals( 1, sessionFactory().getStatistics().getNaturalIdQueryExecutionCount() );//0: incorrect stats since hbm.xml can't enable NaturalId caching assertEquals(
1,
sessionFactory().getStatistics().getNaturalIdQueryExecutionCount()
);//0: incorrect stats since hbm.xml can't enable NaturalId caching
assertEquals( 0, sessionFactory().getStatistics().getNaturalIdCacheHitCount() ); assertEquals( 0, sessionFactory().getStatistics().getNaturalIdCacheHitCount() );
s.getTransaction().commit();
s.close();
s = openSession();
s.beginTransaction();
s.createQuery( "delete User" ).executeUpdate();
s.getTransaction().commit();
s.close();
} }
);
inTransaction(
session ->
session.createQuery( "delete User" ).executeUpdate()
);
}
} }

View File

@ -1,74 +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.test.jpa.naturalid;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.hibernate.Session;
import org.hibernate.dialect.AbstractHANADialect;
import org.hibernate.dialect.Oracle8iDialect;
import org.hibernate.test.jpa.AbstractJPATest;
import org.hibernate.testing.SkipForDialect;
import org.hibernate.testing.TestForIssue;
import org.junit.Test;
/**
* @author Steve Ebersole
*/
@SkipForDialect(value = { Oracle8iDialect.class, AbstractHANADialect.class },
comment = "Oracle/Hana do not support identity key generation")
public class MutableNaturalIdTest extends AbstractJPATest {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] { Group.class, ClassWithIdentityColumn.class };
}
@Test
public void testSimpleNaturalIdLoadAccessCacheWithUpdate() {
Session s = openSession();
s.beginTransaction();
Group g = new Group( 1, "admin" );
s.persist( g );
s.getTransaction().commit();
s.close();
s = openSession();
s.beginTransaction();
g = (Group) s.bySimpleNaturalId( Group.class ).load( "admin" );
assertNotNull( g );
Group g2 = (Group) s.bySimpleNaturalId( Group.class ).getReference( "admin" );
assertTrue( g == g2 );
g.setName( "admins" );
s.flush();
g2 = (Group) s.bySimpleNaturalId( Group.class ).getReference( "admins" );
assertTrue( g == g2 );
s.getTransaction().commit();
s.close();
s = openSession();
s.beginTransaction();
s.createQuery( "delete Group" ).executeUpdate();
s.getTransaction().commit();
s.close();
}
@Test
@TestForIssue( jiraKey = "HHH-7304")
public void testInLineSynchWithIdentityColumn() {
Session s = openSession();
s.beginTransaction();
ClassWithIdentityColumn e = new ClassWithIdentityColumn();
e.setName("Dampf");
s.save(e);
e.setName("Klein");
assertNotNull(session.bySimpleNaturalId(ClassWithIdentityColumn.class).load("Klein"));
session.getTransaction().rollback();
session.close();
}
}

View File

@ -1,104 +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.test.jpa.proxy;
import jakarta.persistence.EntityNotFoundException;
import junit.framework.AssertionFailedError;
import org.junit.Test;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.test.jpa.AbstractJPATest;
import org.hibernate.test.jpa.Item;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
/**
* Test relation between proxies and get()/load() processing
* and make sure the interactions match the ejb3 expectations
*
* @author Steve Ebersole
*/
public class JPAProxyTest extends AbstractJPATest {
@Test
public void testEjb3ProxyUsage() {
Session s = openSession();
Transaction txn = s.beginTransaction();
Item item = ( Item ) s.load( Item.class, new Long(-1) );
assertFalse( Hibernate.isInitialized( item ) );
try {
Hibernate.initialize( item );
fail( "proxy access did not fail on non-existent proxy" );
}
catch ( EntityNotFoundException e ) {
// expected behavior
}
catch ( Throwable t ) {
fail( "unexpected exception type on non-existent proxy access : " + t );
}
s.clear();
Item item2 = ( Item ) s.load( Item.class, new Long(-1) );
assertFalse( Hibernate.isInitialized( item2 ) );
assertFalse( item == item2 );
try {
item2.getName();
fail( "proxy access did not fail on non-existent proxy" );
}
catch ( EntityNotFoundException e ) {
// expected behavior
}
catch ( Throwable t ) {
fail( "unexpected exception type on non-existent proxy access : " + t );
}
txn.commit();
s.close();
}
/**
* The ejb3 find() method maps to the Hibernate get() method
*/
@Test
public void testGetSemantics() {
Long nonExistentId = new Long( -1 );
Session s = openSession();
Transaction txn = s.beginTransaction();
Item item = ( Item ) s.get( Item.class, nonExistentId );
assertNull( "get() of non-existent entity did not return null", item );
txn.commit();
s.close();
s = openSession();
txn = s.beginTransaction();
// first load() it to generate a proxy...
item = ( Item ) s.load( Item.class, nonExistentId );
assertFalse( Hibernate.isInitialized( item ) );
// then try to get() it to make sure we get an exception
try {
s.get( Item.class, nonExistentId );
fail( "force load did not fail on non-existent entity" );
}
catch ( EntityNotFoundException e ) {
// expected behavior
}
catch( AssertionFailedError e ) {
throw e;
}
catch ( Throwable t ) {
fail( "unexpected exception type on non-existent entity force load : " + t );
}
txn.commit();
s.close();
}
}

View File

@ -1,182 +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.test.jpa.removed;
import java.math.BigDecimal;
import org.hibernate.Session;
import org.hibernate.test.jpa.AbstractJPATest;
import org.hibernate.test.jpa.Item;
import org.hibernate.test.jpa.Part;
import org.junit.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;
/**
* @author Steve Ebersole
*/
public class RemovedEntityTest extends AbstractJPATest {
@Test
public void testRemoveThenContains() {
Session s = openSession();
s.beginTransaction();
Item item = new Item();
item.setName( "dummy" );
s.persist( item );
s.getTransaction().commit();
s.close();
s = openSession();
s.beginTransaction();
s.delete( item );
boolean contains = s.contains( item );
s.getTransaction().commit();
s.close();
assertFalse( "expecting removed entity to not be contained", contains );
}
@Test
public void testRemoveThenGet() {
Session s = openSession();
s.beginTransaction();
Item item = new Item();
item.setName( "dummy" );
s.persist( item );
s.getTransaction().commit();
s.close();
Long id = item.getId();
s = openSession();
s.beginTransaction();
s.delete( item );
item = ( Item ) s.get( Item.class, id );
s.getTransaction().commit();
s.close();
assertNull( "expecting removed entity to be returned as null from get()", item );
}
@Test
public void testRemoveThenSave() {
Session s = openSession();
s.beginTransaction();
Item item = new Item();
item.setName( "dummy" );
s.persist( item );
s.getTransaction().commit();
s.close();
Long id = item.getId();
s = openSession();
s.beginTransaction();
item = ( Item ) s.get( Item.class, id );
String sessionAsString = s.toString();
s.delete( item );
Item item2 = ( Item ) s.get( Item.class, id );
assertNull( "expecting removed entity to be returned as null from get()", item2 );
s.persist( item );
assertEquals( "expecting session to be as it was before", sessionAsString, s.toString() );
item.setName("Rescued");
item = ( Item ) s.get( Item.class, id );
assertNotNull( "expecting rescued entity to be returned from get()", item );
s.getTransaction().commit();
s.close();
s = openSession();
s.beginTransaction();
item = ( Item ) s.get( Item.class, id );
s.getTransaction().commit();
s.close();
assertNotNull( "expecting removed entity to be returned as null from get()", item );
assertEquals("Rescued", item.getName());
// clean up
s = openSession();
s.beginTransaction();
s.delete( item );
s.getTransaction().commit();
s.close();
}
@Test
public void testRemoveThenSaveWithCascades() {
Session s = openSession();
s.beginTransaction();
Item item = new Item();
item.setName( "dummy" );
Part part = new Part(item, "child", "1234", BigDecimal.ONE);
// persist cascades to part
s.persist( item );
// delete cascades to part also
s.delete( item );
assertFalse( "the item is contained in the session after deletion", s.contains( item ) );
assertFalse( "the part is contained in the session after deletion", s.contains( part ) );
// now try to persist again as a "unschedule removal" operation
s.persist( item );
assertTrue( "the item is contained in the session after deletion", s.contains( item ) );
assertTrue( "the part is contained in the session after deletion", s.contains( part ) );
s.getTransaction().commit();
s.close();
// clean up
s = openSession();
s.beginTransaction();
s.delete( item );
s.getTransaction().commit();
s.close();
}
@Test
public void testRemoveChildThenFlushWithCascadePersist() {
Session s = openSession();
s.beginTransaction();
Item item = new Item();
item.setName( "dummy" );
Part child = new Part(item, "child", "1234", BigDecimal.ONE);
// persist cascades to part
s.persist( item );
// delete the part
s.delete( child );
assertFalse("the child is contained in the session, since it is deleted", s.contains(child) );
// now try to flush, which will attempt to cascade persist again to child.
s.flush();
assertTrue("Now it is consistent again since if was cascade-persisted by the flush()", s.contains(child));
s.getTransaction().commit();
s.close();
// clean up
s = openSession();
s.beginTransaction();
s.delete( item );
s.getTransaction().commit();
s.close();
}
}

View File

@ -1,41 +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.test.mapping.joinformula;
import org.hibernate.Session;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.junit.Test;
public class JoinFormulaTest extends BaseCoreFunctionalTestCase {
@Override
protected Class[] getAnnotatedClasses() {
return new Class[] {
ParentEntity.class,
ChildEntity.class
};
}
@Override
protected void configure(Configuration configuration) {
super.configure( configuration );
configuration.setProperty( AvailableSettings.SHOW_SQL, Boolean.TRUE.toString() );
configuration.setProperty( AvailableSettings.FORMAT_SQL, Boolean.TRUE.toString() );
}
@Test
public void hhh13722Test() {
try (Session s = openSession()) {
//Nothing to do: the test just needs to verify that
//this can boot.
}
}
}

View File

@ -13,7 +13,7 @@ import java.sql.Statement;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.fail;
/** /**
* This {@link ConnectionProvider} extends any other ConnectionProvider that would be used by default taken the current configuration properties, and it * This {@link ConnectionProvider} extends any other ConnectionProvider that would be used by default taken the current configuration properties, and it

View File

@ -21,6 +21,7 @@ import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataBuilder; import org.hibernate.boot.MetadataBuilder;
import org.hibernate.boot.MetadataSources; import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.SessionFactoryBuilder; import org.hibernate.boot.SessionFactoryBuilder;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.boot.spi.MetadataImplementor;
@ -90,6 +91,11 @@ public abstract class BaseSessionFactoryFunctionalTest
return ssrBuilder.build(); return ssrBuilder.build();
} }
@Override
public void prepareBootstrapRegistryBuilder(BootstrapServiceRegistryBuilder bsrb) {
}
protected boolean exportSchema() { protected boolean exportSchema() {
return true; return true;
} }
@ -204,7 +210,7 @@ public abstract class BaseSessionFactoryFunctionalTest
log.trace( "Producing SessionFactory" ); log.trace( "Producing SessionFactory" );
final SessionFactoryBuilder sfBuilder = model.getSessionFactoryBuilder(); final SessionFactoryBuilder sfBuilder = model.getSessionFactoryBuilder();
configure( sfBuilder ); configure( sfBuilder );
final SessionFactoryImplementor factory = (SessionFactoryImplementor) model.buildSessionFactory(); final SessionFactoryImplementor factory = (SessionFactoryImplementor) sfBuilder.build();
sessionFactoryBuilt( factory ); sessionFactoryBuilt( factory );
return factory; return factory;
} }

View File

@ -21,6 +21,8 @@ import org.hibernate.dialect.TimeZoneSupport;
import org.hibernate.dialect.TiDBDialect; import org.hibernate.dialect.TiDBDialect;
import org.hibernate.query.FetchClauseType; import org.hibernate.query.FetchClauseType;
import org.hibernate.testing.DialectCheck;
/** /**
* Container class for different implementation of the {@link DialectFeatureCheck} interface. * Container class for different implementation of the {@link DialectFeatureCheck} interface.
* *
@ -351,6 +353,12 @@ abstract public class DialectFeatureChecks {
} }
} }
public static class SupportNoWait implements DialectFeatureCheck {
public boolean apply(Dialect dialect) {
return dialect.supportsNoWait();
}
}
public static class DoesRepeatableReadNotCauseReadersToBlockWritersCheck implements DialectFeatureCheck { public static class DoesRepeatableReadNotCauseReadersToBlockWritersCheck implements DialectFeatureCheck {
public boolean apply(Dialect dialect) { public boolean apply(Dialect dialect) {
return ! dialect.doesRepeatableReadCauseReadersToBlockWriters(); return ! dialect.doesRepeatableReadCauseReadersToBlockWriters();

View File

@ -91,26 +91,7 @@ public class ServiceRegistryExtension
ssrProducer = (ServiceRegistryProducer) testInstance; ssrProducer = (ServiceRegistryProducer) testInstance;
} }
else { else {
ssrProducer = ssrb -> { ssrProducer = new ServiceRegistryProducerImpl(context);
if ( !context.getElement().isPresent() ) {
throw new RuntimeException( "Unable to determine how to handle given ExtensionContext : " + context.getDisplayName() );
}
// set some baseline test settings
ssrb.applySetting( AvailableSettings.STATEMENT_INSPECTOR, org.hibernate.testing.jdbc.SQLStatementInspector.class );
final Optional<ServiceRegistry> ssrAnnWrapper = AnnotationSupport.findAnnotation(
context.getElement().get(),
ServiceRegistry.class
);
if ( ssrAnnWrapper.isPresent() ) {
final ServiceRegistry serviceRegistryAnn = ssrAnnWrapper.get();
configureServices( serviceRegistryAnn, ssrb );
}
return ssrb.build();
};
} }
final ServiceRegistryScopeImpl scope = new ServiceRegistryScopeImpl( bsrProducer, ssrProducer ); final ServiceRegistryScopeImpl scope = new ServiceRegistryScopeImpl( bsrProducer, ssrProducer );
@ -127,6 +108,39 @@ public class ServiceRegistryExtension
return existingScope; return existingScope;
} }
private static class ServiceRegistryProducerImpl implements ServiceRegistryProducer{
private final ExtensionContext context;
public ServiceRegistryProducerImpl(ExtensionContext context) {
this.context = context;
if ( !context.getElement().isPresent() ) {
throw new RuntimeException( "Unable to determine how to handle given ExtensionContext : " + context.getDisplayName() );
}
}
@Override
public StandardServiceRegistry produceServiceRegistry(StandardServiceRegistryBuilder ssrb) {
// set some baseline test settings
ssrb.applySetting( AvailableSettings.STATEMENT_INSPECTOR, org.hibernate.testing.jdbc.SQLStatementInspector.class );
final Optional<ServiceRegistry> ssrAnnWrapper = AnnotationSupport.findAnnotation(
context.getElement().get(),
ServiceRegistry.class
);
if ( ssrAnnWrapper.isPresent() ) {
final ServiceRegistry serviceRegistryAnn = ssrAnnWrapper.get();
configureServices( serviceRegistryAnn, ssrb );
}
return ssrb.build();
}
@Override
public void prepareBootstrapRegistryBuilder(BootstrapServiceRegistryBuilder bsrb) {
}
}
private static void configureIntegrators( private static void configureIntegrators(
BootstrapServiceRegistry bsrAnn, BootstrapServiceRegistry bsrAnn,
final BootstrapServiceRegistryBuilder bsrBuilder) { final BootstrapServiceRegistryBuilder bsrBuilder) {
@ -255,6 +269,7 @@ public class ServiceRegistryExtension
private StandardServiceRegistry createRegistry() { private StandardServiceRegistry createRegistry() {
BootstrapServiceRegistryBuilder bsrb = new BootstrapServiceRegistryBuilder().enableAutoClose(); BootstrapServiceRegistryBuilder bsrb = new BootstrapServiceRegistryBuilder().enableAutoClose();
ssrProducer.prepareBootstrapRegistryBuilder(bsrb);
final org.hibernate.boot.registry.BootstrapServiceRegistry bsr = bsrProducer.produceServiceRegistry( bsrb ); final org.hibernate.boot.registry.BootstrapServiceRegistry bsr = bsrProducer.produceServiceRegistry( bsrb );
try { try {

View File

@ -6,6 +6,7 @@
*/ */
package org.hibernate.testing.orm.junit; package org.hibernate.testing.orm.junit;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
@ -14,4 +15,6 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
*/ */
public interface ServiceRegistryProducer { public interface ServiceRegistryProducer {
StandardServiceRegistry produceServiceRegistry(StandardServiceRegistryBuilder builder); StandardServiceRegistry produceServiceRegistry(StandardServiceRegistryBuilder builder);
void prepareBootstrapRegistryBuilder(BootstrapServiceRegistryBuilder bsrb);
} }