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

View File

@ -4,77 +4,85 @@
* 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.hql;
import static org.assertj.core.api.Assertions.assertThat;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
package org.hibernate.orm.test.hql;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.junit.Before;
import org.junit.Test;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
public class DeleteWhereFunctionCallTest extends BaseCoreFunctionalTestCase {
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@Override
protected Class[] getAnnotatedClasses() {
return new Class[] {
SuperType.class,
SubType.class
};
}
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
@Override
protected boolean isCleanupTestDataRequired() {
return true;
}
import static org.assertj.core.api.Assertions.assertThat;
@Before
public void initData() {
inTransaction( s -> {
@DomainModel(
annotatedClasses = {
DeleteWhereFunctionCallTest.SuperType.class,
DeleteWhereFunctionCallTest.SubType.class
}
)
@SessionFactory
public class DeleteWhereFunctionCallTest {
@BeforeEach
public void initData(SessionFactoryScope scope) {
scope.inTransaction( s -> {
s.persist( new SuperType( -1 ) );
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
@TestForIssue(jiraKey = "HHH-14814")
public void testDeleteWhereTypeFunctionCall() {
inTransaction( s -> {
public void testDeleteWhereTypeFunctionCall(SessionFactoryScope scope) {
scope.inTransaction( s -> {
assertThat( count( s, SuperType.class ) ).isEqualTo( 2 );
assertThat( count( s, SubType.class ) ).isEqualTo( 1 );
} );
inTransaction( s -> {
scope.inTransaction( s -> {
Query<?> query = s.createQuery( "delete from " + SuperType.class.getName() + " e"
+ " where type( e ) = :type" );
+ " where type( e ) = :type" );
query.setParameter( "type", SuperType.class );
query.executeUpdate();
} );
inTransaction( s -> {
scope.inTransaction( s -> {
assertThat( count( s, SuperType.class ) ).isEqualTo( 1 );
assertThat( count( s, SubType.class ) ).isEqualTo( 1 );
} );
}
@Test
public void testDeleteWhereAbsFunctionCall() {
inTransaction( s -> {
public void testDeleteWhereAbsFunctionCall(SessionFactoryScope scope) {
scope.inTransaction( s -> {
assertThat( count( s, SuperType.class ) ).isEqualTo( 2 );
assertThat( count( s, SubType.class ) ).isEqualTo( 1 );
} );
inTransaction( s -> {
scope.inTransaction( s -> {
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.executeUpdate();
} );
inTransaction( s -> {
scope.inTransaction( s -> {
assertThat( count( s, SuperType.class ) ).isEqualTo( 1 );
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.
* 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.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.
* 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;
import org.jboss.logging.Logger;
import org.junit.Test;
package org.hibernate.orm.test.jpa.cascade2;
import org.hibernate.Session;
import org.hibernate.TransientObjectException;
import org.hibernate.test.jpa.AbstractJPATest;
import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping;
import static org.junit.Assert.fail;
import org.hibernate.orm.test.jpa.model.AbstractJPATest;
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
@ -31,8 +30,9 @@ import static org.junit.Assert.fail;
*/
public class CascadeTest extends AbstractJPATest {
public String[] getMappings() {
return new String[] { "jpa/cascade/ParentChild.hbm.xml" };
@Override
protected String[] getOrmXmlFiles() {
return new String[] { "org/hibernate/orm/test/jpa/cascade2/ParentChild.hbm.xml" };
}
@Test
@ -40,24 +40,24 @@ public class CascadeTest extends AbstractJPATest {
// NOTES: Child defines a many-to-one back to its Parent. This
// association does not define persist cascading (which is natural;
// a child should not be able to create its parent).
try {
Session s = openSession();
try (Session s = sessionFactory().openSession()) {
s.beginTransaction();
Parent p = new Parent( "parent" );
Child c = new Child( "child" );
c.setParent( p );
s.save( c );
try {
Parent p = new Parent( "parent" );
Child c = new Child( "child" );
c.setParent( p );
s.save( c );
s.getTransaction().commit();
fail( "expecting TransientObjectException on flush" );
}
catch (IllegalStateException e) {
assertTyping( TransientObjectException.class, e.getCause() );
log.trace( "handled expected exception", e );
s.getTransaction().rollback();
}
finally {
s.close();
if ( s.getTransaction().isActive() ) {
s.getTransaction().rollback();
}
}
}
finally {
@ -69,24 +69,25 @@ public class CascadeTest extends AbstractJPATest {
// NOTES: Child defines a many-to-one back to its Parent. This
// association does not define persist cascading (which is natural;
// a child should not be able to create its parent).
try {
Session s = openSession();
s.beginTransaction();
Parent p = new Parent( "parent" );
Child c = new Child( "child" );
c.setParent( p );
s.persist( c );
try (Session s = sessionFactory().openSession()) {
try {
s.beginTransaction();
Parent p = new Parent( "parent" );
Child c = new Child( "child" );
c.setParent( p );
s.persist( c );
s.getTransaction().commit();
fail( "expecting TransientObjectException on flush" );
}
catch( TransientObjectException e ) {
catch (TransientObjectException e) {
// expected result
log.trace( "handled expected exception", e );
s.getTransaction().rollback();
}
finally {
s.close();
if ( s.getTransaction().isActive() ) {
s.getTransaction().rollback();
}
}
}
finally {
@ -98,24 +99,25 @@ public class CascadeTest extends AbstractJPATest {
// NOTES: Child defines a many-to-one back to its Parent. This
// association does not define persist cascading (which is natural;
// a child should not be able to create its parent).
try {
Session s = openSession();
try (Session s = sessionFactory().openSession()) {
s.beginTransaction();
ParentAssigned p = new ParentAssigned( new Long( 1 ), "parent" );
ChildAssigned c = new ChildAssigned( new Long( 2 ), "child" );
c.setParent( p );
s.persist( c );
try {
ParentAssigned p = new ParentAssigned( 1L, "parent" );
ChildAssigned c = new ChildAssigned( 2L, "child" );
c.setParent( p );
s.persist( c );
s.getTransaction().commit();
fail( "expecting TransientObjectException on flush" );
}
catch( TransientObjectException e ) {
catch (TransientObjectException e) {
// expected result
log.trace( "handled expected exception", e );
s.getTransaction().rollback();
}
finally {
s.close();
if ( s.getTransaction().isActive() ) {
s.getTransaction().rollback();
}
}
}
finally {
@ -124,25 +126,26 @@ public class CascadeTest extends AbstractJPATest {
}
public void testOneToOneGeneratedIds() {
try {
Session s = openSession();
s.beginTransaction();
Parent p = new Parent( "parent" );
ParentInfo info = new ParentInfo( "xyz" );
p.setInfo( info );
info.setOwner( p );
s.persist( p );
try (Session s = sessionFactory().openSession()) {
try {
s.beginTransaction();
Parent p = new Parent( "parent" );
ParentInfo info = new ParentInfo( "xyz" );
p.setInfo( info );
info.setOwner( p );
s.persist( p );
s.getTransaction().commit();
fail( "expecting TransientObjectException on flush" );
}
catch( TransientObjectException e ) {
catch (TransientObjectException e) {
// expected result
log.trace( "handled expected exception", e );
s.getTransaction().rollback();
}
finally {
s.close();
if ( s.getTransaction().isActive() ) {
s.getTransaction().rollback();
}
}
}
finally {
@ -151,25 +154,26 @@ public class CascadeTest extends AbstractJPATest {
}
public void testOneToOneAssignedIds() {
try {
Session s = openSession();
s.beginTransaction();
ParentAssigned p = new ParentAssigned( new Long( 1 ), "parent" );
ParentInfoAssigned info = new ParentInfoAssigned( "something secret" );
p.setInfo( info );
info.setOwner( p );
s.persist( p );
try (Session s = sessionFactory().openSession()) {
try {
s.beginTransaction();
ParentAssigned p = new ParentAssigned( 1L, "parent" );
ParentInfoAssigned info = new ParentInfoAssigned( "something secret" );
p.setInfo( info );
info.setOwner( p );
s.persist( p );
s.getTransaction().commit();
fail( "expecting TransientObjectException on flush" );
}
catch( TransientObjectException e ) {
catch (TransientObjectException e) {
// expected result
log.trace( "handled expected exception", e );
s.getTransaction().rollback();
}
finally {
s.close();
if ( s.getTransaction().isActive() ) {
s.getTransaction().rollback();
}
}
}
finally {
@ -178,8 +182,7 @@ public class CascadeTest extends AbstractJPATest {
}
public void testManyToOnePropertyRefGeneratedIds() {
try {
Session s = openSession();
try (Session s = sessionFactory().openSession()) {
s.beginTransaction();
Parent p = new Parent( "parent" );
Other other = new Other();
@ -189,13 +192,14 @@ public class CascadeTest extends AbstractJPATest {
s.getTransaction().commit();
fail( "expecting TransientObjectException on flush" );
}
catch( TransientObjectException e ) {
catch (TransientObjectException e) {
// expected result
log.trace( "handled expected exception", e );
s.getTransaction().rollback();
}
finally {
s.close();
if ( s.getTransaction().isActive() ) {
s.getTransaction().rollback();
}
}
}
finally {
@ -204,24 +208,24 @@ public class CascadeTest extends AbstractJPATest {
}
public void testManyToOnePropertyRefAssignedIds() {
try {
Session s = openSession();
try (Session s = sessionFactory().openSession()) {
s.beginTransaction();
ParentAssigned p = new ParentAssigned( new Long( 1 ), "parent" );
OtherAssigned other = new OtherAssigned( new Long( 2 ) );
ParentAssigned p = new ParentAssigned( 1L, "parent" );
OtherAssigned other = new OtherAssigned( 2L );
other.setOwner( p );
s.persist( other );
try {
s.getTransaction().commit();
fail( "expecting TransientObjectException on flush" );
}
catch( TransientObjectException e ) {
catch (TransientObjectException e) {
// expected result
log.trace( "handled expected exception", e );
s.getTransaction().rollback();
}
finally {
s.close();
if ( s.getTransaction().isActive() ) {
s.getTransaction().rollback();
}
}
}
finally {
@ -230,8 +234,7 @@ public class CascadeTest extends AbstractJPATest {
}
public void testOneToOnePropertyRefGeneratedIds() {
try {
Session s = openSession();
try (Session s = sessionFactory().openSession()) {
s.beginTransaction();
Child c2 = new Child( "c2" );
ChildInfo info = new ChildInfo( "blah blah blah" );
@ -242,13 +245,14 @@ public class CascadeTest extends AbstractJPATest {
s.getTransaction().commit();
fail( "expecting TransientObjectException on flush" );
}
catch( TransientObjectException e ) {
catch (TransientObjectException e) {
// expected result
log.trace( "handled expected exception : " + e );
s.getTransaction().rollback();
}
finally {
s.close();
if ( s.getTransaction().isActive() ) {
s.getTransaction().rollback();
}
}
}
finally {
@ -257,11 +261,10 @@ public class CascadeTest extends AbstractJPATest {
}
public void testOneToOnePropertyRefAssignedIds() {
try {
Session s = openSession();
try (Session s = sessionFactory().openSession()) {
s.beginTransaction();
ChildAssigned c2 = new ChildAssigned( new Long( 3 ), "c3" );
ChildInfoAssigned info = new ChildInfoAssigned( new Long( 4 ), "blah blah blah" );
ChildAssigned c2 = new ChildAssigned( 3L, "c3" );
ChildInfoAssigned info = new ChildInfoAssigned( 4L, "blah blah blah" );
c2.setInfo( info );
info.setOwner( c2 );
s.persist( c2 );
@ -269,13 +272,14 @@ public class CascadeTest extends AbstractJPATest {
s.getTransaction().commit();
fail( "expecting TransientObjectException on flush" );
}
catch( TransientObjectException e ) {
catch (TransientObjectException e) {
// expected result
log.trace( "handled expected exception : " + e );
s.getTransaction().rollback();
}
finally {
s.close();
if ( s.getTransaction().isActive() ) {
s.getTransaction().rollback();
}
}
}
finally {
@ -285,29 +289,16 @@ public class CascadeTest extends AbstractJPATest {
private void cleanupData() {
Session s = null;
try {
s = openSession();
s.beginTransaction();
s.createQuery( "delete ChildInfoAssigned" ).executeUpdate();
s.createQuery( "delete ChildAssigned" ).executeUpdate();
s.createQuery( "delete ParentAssigned" ).executeUpdate();
s.createQuery( "delete ChildInfoAssigned" ).executeUpdate();
s.createQuery( "delete ChildAssigned" ).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();
inTransaction(
s -> {
s.createQuery( "delete ChildInfoAssigned" ).executeUpdate();
s.createQuery( "delete ChildAssigned" ).executeUpdate();
s.createQuery( "delete ParentAssigned" ).executeUpdate();
s.createQuery( "delete ChildInfoAssigned" ).executeUpdate();
s.createQuery( "delete ChildAssigned" ).executeUpdate();
s.createQuery( "delete ParentAssigned" ).executeUpdate();
}
catch( Throwable ignore ) {
}
}
}
);
}
}

View File

@ -4,7 +4,7 @@
* 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.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.
* 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.
* 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.
* 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.
* 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.
* 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.
* 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.
* 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"
"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 ++++++++++++++++++++++ -->

View File

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

View File

@ -6,13 +6,12 @@
*/
package org.hibernate.orm.test.jpa.compliance.tck2_2;
import jakarta.persistence.Parameter;
import org.hibernate.query.Query;
import org.hibernate.testing.transaction.TransactionUtil2;
import org.hibernate.test.jpa.AbstractJPATest;
import org.junit.Test;
import org.hibernate.orm.test.jpa.model.AbstractJPATest;
import org.junit.jupiter.api.Test;
import jakarta.persistence.Parameter;
import static org.hamcrest.CoreMatchers.either;
import static org.hamcrest.CoreMatchers.is;
@ -23,15 +22,15 @@ import static org.hamcrest.MatcherAssert.assertThat;
* @author Steve Ebersole
*/
public class JpaPositionalParameterTest extends AbstractJPATest {
@Test
public void testPositionalParameters() {
TransactionUtil2.inTransaction(
sessionFactory(),
inTransaction(
session -> {
Query query = session.createQuery( "select i from Item i where name = ?1 or name = ?2" );
for ( Parameter<?> parameter : query.getParameters() ) {
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;
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 org.junit.Test;
import jakarta.persistence.LockModeType;
/**
* @author Steve Ebersole
*/
public class NonSelectQueryLockMode extends AbstractJPATest {
@Test( expected = IllegalStateException.class )
@Test
public void testNonSelectQueryGetLockMode() {
inTransaction(
session -> session.createQuery( "delete Item" ).getLockMode()
Assertions.assertThrows(
IllegalStateException.class,
() -> inTransaction(
session -> session.createQuery( "delete Item" ).getLockMode()
)
);
}
@Test( expected = IllegalStateException.class )
@Test
public void testNonSelectQuerySetLockMode() {
inTransaction(
session -> session.createQuery( "delete Item" ).setLockMode( LockModeType.PESSIMISTIC_WRITE )
Assertions.assertThrows(
IllegalStateException.class,
() -> inTransaction(
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.
* 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.Time;
@ -13,6 +13,11 @@ import java.time.LocalDate;
import java.time.LocalDateTime;
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.Column;
import jakarta.persistence.Convert;
@ -20,32 +25,25 @@ import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase;
import org.junit.Test;
import org.hibernate.testing.TestForIssue;
import static org.hibernate.testing.transaction.TransactionUtil.doInJPA;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Chris Cranford
*/
public class JdbcTypeConverterTest extends BaseEntityManagerFunctionalTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] { JavaTimeBean.class };
}
@Jpa(
annotatedClasses = JdbcTypeConverterTest.JavaTimeBean.class
)
public class JdbcTypeConverterTest {
@Test
@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.
// This will serve sufficient for our test to verify that the retrieved values match persisted.
LocalDateTime now = LocalDateTime.now().withNano( 0 );
// persist the record.
Integer rowId = doInJPA( this::entityManagerFactory, entityManager -> {
Integer rowId = scope.fromTransaction( entityManager -> {
JavaTimeBean javaTime = new JavaTimeBean();
javaTime.setLocalDate( now.toLocalDate() );
javaTime.setLocalTime( now.toLocalTime() );
@ -55,7 +53,7 @@ public class JdbcTypeConverterTest extends BaseEntityManagerFunctionalTestCase {
} );
// retrieve the record and verify values.
doInJPA( this::entityManagerFactory, entityManager -> {
scope.inTransaction( entityManager -> {
final JavaTimeBean javaTime = entityManager.find( JavaTimeBean.class, rowId );
assertEquals( now.toLocalDate(), javaTime.getLocalDate() );
assertEquals( now.toLocalTime(), javaTime.getLocalTime() );
@ -74,7 +72,7 @@ public class JdbcTypeConverterTest extends BaseEntityManagerFunctionalTestCase {
private LocalDate localDate;
@Convert(converter = LocalTimeToTimeConverter.class)
@Column(name = "LTIME" )
@Column(name = "LTIME")
private LocalTime localTime;
@Convert(converter = LocalDateTimeToTimestampConverter.class)

View File

@ -24,4 +24,4 @@
/**
* 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"
"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">
<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.
* 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.util.ArrayList;
import java.util.Collection;

View File

@ -4,7 +4,7 @@
* 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;
package org.hibernate.orm.test.jpa.fetch;
import java.io.Serializable;
import java.util.Date;

View File

@ -9,22 +9,23 @@ package org.hibernate.orm.test.jpa.lock;
import org.hibernate.LockMode;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
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.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.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.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* 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
*/
@RequiresDialectFeature( DialectChecks.DoesReadCommittedNotCauseWritersToBlockReadersCheck.class )
@RequiresDialectFeature(feature = DialectFeatureChecks.DoesReadCommittedNotCauseWritersToBlockReadersCheck.class)
public class JPALockTest extends AbstractJPATest {
private SQLServerSnapshotIsolationConnectionProvider connectionProvider = new SQLServerSnapshotIsolationConnectionProvider();
@Override
public void configure(Configuration cfg) {
super.configure( cfg );
if( SQLServerDialect.class.isAssignableFrom( DIALECT.getClass() )) {
connectionProvider.setConnectionProvider( (ConnectionProvider) cfg.getProperties().get( AvailableSettings.CONNECTION_PROVIDER ) );
cfg.getProperties().put( AvailableSettings.CONNECTION_PROVIDER, connectionProvider );
protected void applySettings(StandardServiceRegistryBuilder builder) {
super.applySettings( builder );
if ( SQLServerDialect.class.isAssignableFrom( DIALECT.getClass() ) ) {
connectionProvider.setConnectionProvider( (ConnectionProvider) builder.getSettings()
.get( AvailableSettings.CONNECTION_PROVIDER ) );
builder.applySetting( AvailableSettings.CONNECTION_PROVIDER, connectionProvider );
}
}
@Override
protected void releaseSessionFactory() {
super.releaseSessionFactory();
@AfterAll
protected void tearDown() {
connectionProvider.stop();
}
@ -87,42 +88,72 @@ public class JPALockTest extends AbstractJPATest {
}
final String initialName = "lock test";
// set up some test data
Session s1 = sessionFactory().openSession();
Transaction t1 = s1.beginTransaction();
Item item = new Item();
item.setName( initialName );
s1.save( item );
t1.commit();
s1.close();
Item it = new Item();
Long itemId = fromTransaction(
session -> {
it.setName( initialName );
session.save( it );
return it.getId();
}
);
Long itemId = item.getId();
Session s1 = null;
Session s2 = null;
Item item;
try {
// do the isolated update
s1 = sessionFactory().openSession();
s1.beginTransaction();
item = s1.get( Item.class, itemId );
s1.lock( item, LockMode.UPGRADE );
item.setName( "updated" );
s1.flush();
// do the isolated update
s1 = sessionFactory().openSession();
t1 = s1.beginTransaction();
item = (Item) s1.get( Item.class, itemId );
s1.lock( item, LockMode.UPGRADE );
item.setName( "updated" );
s1.flush();
s2 = sessionFactory().openSession();
Transaction t2 = s2.beginTransaction();
Item item2 = s2.get( Item.class, itemId );
assertEquals( initialName, item2.getName(), "isolation not maintained" );
Session s2 = sessionFactory().openSession();
Transaction t2 = s2.beginTransaction();
Item item2 = (Item) s2.get( Item.class, itemId );
assertEquals( "isolation not maintained", initialName, item2.getName() );
s1.getTransaction().commit();
s1.close();
t1.commit();
s1.close();
item2 = s2.get( Item.class, itemId );
assertEquals( initialName, item2.getName(), "repeatable read not maintained" );
t2.commit();
s2.close();
}
finally {
if ( s1 != null ) {
try {
if ( s1.getTransaction().isActive() ) {
s1.getTransaction().rollback();
}
}
finally {
if ( s1.isOpen() ) {
s1.close();
}
}
}
item2 = (Item) s2.get( Item.class, itemId );
assertEquals( "repeatable read not maintained", initialName, item2.getName() );
t2.commit();
s2.close();
if ( s2 != null ) {
try {
if ( s2.getTransaction().isActive() ) {
s2.getTransaction().rollback();
}
}
finally {
if ( s2.isOpen() ) {
s2.close();
}
}
}
}
s1 = sessionFactory().openSession();
t1 = s1.beginTransaction();
s1.delete( item );
t1.commit();
s1.close();
inTransaction(
session ->
session.delete( item )
);
}
/**
@ -154,77 +185,101 @@ public class JPALockTest extends AbstractJPATest {
}
final String initialName = "lock test";
// set up some test data
Session s1 = sessionFactory().openSession();
Transaction t1 = s1.beginTransaction();
Item item = new Item();
item.setName( initialName );
s1.save( item );
MyEntity myEntity = new MyEntity();
myEntity.setName( "Test" );
s1.save( myEntity );
t1.commit();
s1.close();
Item it = new Item();
MyEntity entity = new MyEntity();
inTransaction(
session -> {
it.setName( initialName );
session.save( it );
entity.setName( "Test" );
session.save( entity );
}
);
Long itemId = item.getId();
long initialVersion = item.getVersion();
s1 = sessionFactory().openSession();
t1 = s1.beginTransaction();
item = (Item) s1.get( Item.class, itemId );
s1.lock( item, LockMode.FORCE );
assertEquals( "no forced version increment", initialVersion + 1, item.getVersion() );
myEntity = (MyEntity) s1.get( MyEntity.class, myEntity.getId() );
s1.lock( myEntity, LockMode.FORCE );
assertTrue( "LockMode.FORCE on a un-versioned entity should degrade nicely to UPGRADE", true );
s1.lock( item, LockMode.FORCE );
assertEquals( "subsequent LockMode.FORCE did not no-op", initialVersion + 1, item.getVersion() );
Session s2 = sessionFactory().openSession();
Transaction t2 = s2.beginTransaction();
Item item2 = (Item) s2.get( Item.class, itemId );
assertEquals( "isolation not maintained", initialName, item2.getName() );
item.setName( "updated-1" );
s1.flush();
// currently an unfortunate side effect...
assertEquals( initialVersion + 2, item.getVersion() );
t1.commit();
s1.close();
item2.setName( "updated" );
Long itemId = it.getId();
long initialVersion = it.getVersion();
Session s1 = null;
Session s2 = null;
MyEntity myEntity;
Item item;
try {
t2.commit();
fail( "optimistic lock should have failed" );
}
catch (Throwable t) {
// expected behavior
s1 = sessionFactory().openSession();
s1.beginTransaction();
item = s1.get( Item.class, itemId );
s1.lock( item, LockMode.FORCE );
assertEquals( initialVersion + 1, item.getVersion(), "no forced version increment" );
myEntity = s1.get( MyEntity.class, entity.getId() );
s1.lock( myEntity, LockMode.FORCE );
assertTrue( true, "LockMode.FORCE on a un-versioned entity should degrade nicely to UPGRADE" );
s1.lock( item, LockMode.FORCE );
assertEquals( initialVersion + 1, item.getVersion(), "subsequent LockMode.FORCE did not no-op" );
s2 = sessionFactory().openSession();
s2.beginTransaction();
Item item2 = s2.get( Item.class, itemId );
assertEquals( initialName, item2.getName(), "isolation not maintained" );
item.setName( "updated-1" );
s1.flush();
// currently an unfortunate side effect...
assertEquals( initialVersion + 2, item.getVersion() );
s1.getTransaction().commit();
s1.close();
item2.setName( "updated" );
try {
t2.rollback();
s2.getTransaction().commit();
fail( "optimistic lock should have failed" );
}
catch (Throwable ignore) {
// ignore
}
if ( t instanceof AssertionError ) {
throw (AssertionError) t;
catch (Throwable t) {
// expected behavior
try {
s2.getTransaction().rollback();
}
catch (Throwable ignore) {
// ignore
}
if ( t instanceof AssertionError ) {
throw (AssertionError) t;
}
}
}
finally {
try {
s2.close();
if ( s1 != null ) {
try {
if ( s1.getTransaction().isActive() ) {
s1.getTransaction().rollback();
}
}
finally {
if ( s1.isOpen() ) {
s1.close();
}
}
}
catch (Throwable ignore) {
// ignore
if ( s2 != null ) {
try {
if ( s2.getTransaction().isActive() ) {
s2.getTransaction().rollback();
}
}
finally {
if ( s2.isOpen() ) {
s2.close();
}
}
}
}
s1 = sessionFactory().openSession();
t1 = s1.beginTransaction();
s1.delete( item );
s1.delete( myEntity );
t1.commit();
s1.close();
inTransaction(
session -> {
session.delete( item );
session.delete( myEntity );
}
);
}
}

View File

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

View File

@ -8,27 +8,27 @@ package org.hibernate.orm.test.jpa.lock;
import java.math.BigDecimal;
import org.junit.Test;
import org.hibernate.LockMode;
import org.hibernate.Session;
import org.hibernate.StaleObjectStateException;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
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.exception.SQLGrammarException;
import org.hibernate.test.jpa.AbstractJPATest;
import org.hibernate.test.jpa.Item;
import org.hibernate.test.jpa.Part;
import org.hibernate.testing.jdbc.SQLServerSnapshotIsolationConnectionProvider;
import org.hibernate.testing.DialectChecks;
import org.hibernate.testing.RequiresDialectFeature;
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.hibernate.testing.jdbc.SQLServerSnapshotIsolationConnectionProvider;
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
@ -36,247 +36,252 @@ import static org.junit.Assert.fail;
*
* @author Steve Ebersole
*/
@RequiresDialectFeature( DialectChecks.DoesReadCommittedNotCauseWritersToBlockReadersCheck.class )
@RequiresDialectFeature(feature = DialectFeatureChecks.DoesReadCommittedNotCauseWritersToBlockReadersCheck.class)
public class RepeatableReadTest extends AbstractJPATest {
private SQLServerSnapshotIsolationConnectionProvider connectionProvider = new SQLServerSnapshotIsolationConnectionProvider();
@Override
public void configure(Configuration cfg) {
super.configure( cfg );
if( SQLServerDialect.class.isAssignableFrom( DIALECT.getClass() )) {
connectionProvider.setConnectionProvider( (ConnectionProvider) cfg.getProperties().get( AvailableSettings.CONNECTION_PROVIDER ) );
cfg.getProperties().put( AvailableSettings.CONNECTION_PROVIDER, connectionProvider );
protected void applySettings(StandardServiceRegistryBuilder builder) {
super.applySettings( builder );
if ( SQLServerDialect.class.isAssignableFrom( DIALECT.getClass() ) ) {
connectionProvider.setConnectionProvider( (ConnectionProvider) builder.getSettings()
.get( AvailableSettings.CONNECTION_PROVIDER ) );
builder.applySetting( AvailableSettings.CONNECTION_PROVIDER, connectionProvider );
}
}
@Override
protected void releaseSessionFactory() {
super.releaseSessionFactory();
@AfterAll
protected void tearDown() {
connectionProvider.stop();
}
@Test
public void testStaleVersionedInstanceFoundInQueryResult() {
String check = "EJB3 Specification";
Session s1 = sessionFactory().openSession();
Transaction t1 = s1.beginTransaction();
Item item = new Item( check );
s1.save( item );
t1.commit();
s1.close();
Item it = new Item( check );
inTransaction(
session -> {
session.save( it );
}
);
Long itemId = item.getId();
long initialVersion = item.getVersion();
Long itemId = it.getId();
long initialVersion = it.getVersion();
// Now, open a new Session and re-load the item...
s1 = sessionFactory().openSession();
t1 = s1.beginTransaction();
item = ( Item ) s1.get( Item.class, itemId );
inTransaction(
s1 -> {
Item item = s1.get( Item.class, itemId );
// 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
Session s2 = sessionFactory().openSession();
Transaction t2 = s2.beginTransaction();
Item item2 = ( Item ) s2.get( Item.class, itemId );
item2.setName( "EJB3 Persistence Spec" );
t2.commit();
s2.close();
// 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
inTransaction(
s2 -> {
Item item2 = s2.get( Item.class, itemId );
item2.setName( "EJB3 Persistence Spec" );
}
);
// 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
// (i.e., the old name and the old version)
item2 = ( Item ) s1.createQuery( "select i from Item i" ).list().get( 0 );
assertTrue( item == item2 );
assertEquals( "encountered non-repeatable read", check, item2.getName() );
assertEquals( "encountered non-repeatable read", initialVersion, item2.getVersion() );
// 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
// (i.e., the old name and the old version)
Item item2 = (Item) s1.createQuery( "select i from Item i" ).list().get( 0 );
assertTrue( item == item2 );
assertEquals( check, item2.getName(), "encountered non-repeatable read" );
assertEquals( initialVersion, item2.getVersion(), "encountered non-repeatable read" );
t1.commit();
s1.close();
}
);
// clean up
s1 = sessionFactory().openSession();
t1 = s1.beginTransaction();
s1.createQuery( "delete Item" ).executeUpdate();
t1.commit();
s1.close();
inTransaction(
session ->
session.createQuery( "delete Item" ).executeUpdate()
);
}
@Test
public void testStaleVersionedInstanceFoundOnLock() {
if ( ! readCommittedIsolationMaintained( "repeatable read tests" ) ) {
if ( !readCommittedIsolationMaintained( "repeatable read tests" ) ) {
return;
}
String check = "EJB3 Specification";
Session s1 = sessionFactory().openSession();
Transaction t1 = s1.beginTransaction();
Item item = new Item( check );
s1.save( item );
t1.commit();
s1.close();
Item it = new Item( check );
inTransaction(
session -> {
session.save( it );
}
);
Long itemId = item.getId();
long initialVersion = item.getVersion();
Long itemId = it.getId();
long initialVersion = it.getVersion();
// Now, open a new Session and re-load the item...
s1 = sessionFactory().openSession();
t1 = s1.beginTransaction();
item = ( Item ) s1.get( Item.class, itemId );
inSession(
s1 -> {
s1.beginTransaction();
try {
Item item = s1.get( Item.class, itemId );
// 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
Session s2 = sessionFactory().openSession();
Transaction t2 = s2.beginTransaction();
Item item2 = ( Item ) s2.get( Item.class, itemId );
item2.setName( "EJB3 Persistence Spec" );
t2.commit();
s2.close();
// 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
inTransaction(
s2 -> {
Item item2 = s2.get( Item.class, itemId );
item2.setName( "EJB3 Persistence Spec" );
}
);
// 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
// name and the old version)
s1.lock( item, LockMode.READ );
item2 = ( Item ) s1.get( Item.class, itemId );
assertTrue( item == item2 );
assertEquals( "encountered non-repeatable read", check, item2.getName() );
assertEquals( "encountered non-repeatable read", initialVersion, item2.getVersion() );
// 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
// name and the old version)
s1.lock( item, LockMode.READ );
Item item2 = (Item) s1.get( Item.class, itemId );
assertTrue( item == item2 );
assertEquals( check, item2.getName(), "encountered non-repeatable read" );
assertEquals( initialVersion, item2.getVersion(), "encountered non-repeatable read" );
// attempt to acquire an UPGRADE lock; this should fail
try {
s1.lock( item, LockMode.UPGRADE );
fail( "expected UPGRADE lock failure" );
}
catch( StaleObjectStateException expected ) {
// this is the expected behavior
}
catch( SQLGrammarException t ) {
if ( getDialect() instanceof SQLServerDialect ) {
// 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...
t1.rollback();
t1 = s1.beginTransaction();
}
else {
throw t;
}
}
// attempt to acquire an UPGRADE lock; this should fail
t1.commit();
s1.close();
s1.lock( item, LockMode.UPGRADE );
fail( "expected UPGRADE lock failure" );
}
catch (StaleObjectStateException expected) {
// this is the expected behavior
}
catch (SQLGrammarException t) {
if ( getDialect() instanceof SQLServerDialect ) {
// 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...
s1.getTransaction().rollback();
}
else {
throw t;
}
}
finally {
s1.getTransaction().rollback();
}
}
);
// clean up
s1 = sessionFactory().openSession();
t1 = s1.beginTransaction();
s1.createQuery( "delete Item" ).executeUpdate();
t1.commit();
s1.close();
inTransaction(
session ->
session.createQuery( "delete Item" ).executeUpdate()
);
}
@Test
public void testStaleNonVersionedInstanceFoundInQueryResult() {
String check = "Lock Modes";
Session s1 = sessionFactory().openSession();
Transaction t1 = s1.beginTransaction();
Part part = new Part( new Item( "EJB3 Specification" ), check, "3.3.5.3", new BigDecimal( 0.0 ) );
s1.save( part );
t1.commit();
s1.close();
Part p = new Part( new Item( "EJB3 Specification" ), check, "3.3.5.3", new BigDecimal( 0.0 ) );
inTransaction(
session -> {
session.save( p );
}
);
Long partId = part.getId();
Long partId = p.getId();
// Now, open a new Session and re-load the part...
s1 = sessionFactory().openSession();
t1 = s1.beginTransaction();
part = ( Part ) s1.get( Part.class, partId );
// 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
Session s2 = sessionFactory().openSession();
Transaction t2 = s2.beginTransaction();
Part part2 = ( Part ) s2.get( Part.class, partId );
part2.setName( "Lock Mode Types" );
t2.commit();
s2.close();
inTransaction(
s1 -> {
Part part = s1.get( Part.class, partId );
// 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
// (i.e., the old name)
part2 = ( Part ) s1.createQuery( "select p from Part p" ).list().get( 0 );
assertTrue( part == part2 );
assertEquals( "encountered non-repeatable read", check, part2.getName() );
// 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
inTransaction(
s2 -> {
Part part2 = s2.get( Part.class, partId );
part2.setName( "Lock Mode Types" );
}
);
t1.commit();
s1.close();
// 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
// (i.e., the old name)
Part part2 = (Part) s1.createQuery( "select p from Part p" ).list().get( 0 );
assertTrue( part == part2 );
assertEquals( check, part2.getName(), "encountered non-repeatable read" );
}
);
// clean up
s1 = sessionFactory().openSession();
t1 = s1.beginTransaction();
s1.delete( part2 );
s1.delete( part2.getItem() );
t1.commit();
s1.close();
inTransaction(
session -> {
Part part = (Part) session.createQuery( "select p from Part p" ).list().get( 0 );
session.delete( part );
session.delete( part.getItem() );
}
);
}
@Test
public void testStaleNonVersionedInstanceFoundOnLock() {
if ( ! readCommittedIsolationMaintained( "repeatable read tests" ) ) {
if ( !readCommittedIsolationMaintained( "repeatable read tests" ) ) {
return;
}
String check = "Lock Modes";
Session s1 = sessionFactory().openSession();
Transaction t1 = s1.beginTransaction();
Part part = new Part( new Item( "EJB3 Specification" ), check, "3.3.5.3", new BigDecimal( 0.0 ) );
s1.save( part );
t1.commit();
s1.close();
Part p = new Part( new Item( "EJB3 Specification" ), check, "3.3.5.3", new BigDecimal( 0.0 ) );
inTransaction(
session -> {
session.save( p );
}
);
Long partId = part.getId();
Long partId = p.getId();
// Now, open a new Session and re-load the part...
s1 = sessionFactory().openSession();
t1 = s1.beginTransaction();
part = ( Part ) s1.get( Part.class, partId );
inTransaction(
s1 -> {
Part part = s1.get( Part.class, partId );
// 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
Session s2 = sessionFactory().openSession();
Transaction t2 = s2.beginTransaction();
Part part2 = ( Part ) s2.get( Part.class, partId );
part2.setName( "Lock Mode Types" );
t2.commit();
s2.close();
// 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
inTransaction(
s2 -> {
Part part2 = s2.get( Part.class, partId );
part2.setName( "Lock Mode Types" );
}
);
// 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
// name and the old version)
s1.lock( part, LockMode.READ );
part2 = ( Part ) s1.get( Part.class, partId );
assertTrue( part == part2 );
assertEquals( "encountered non-repeatable read", check, part2.getName() );
// 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
// name and the old version)
s1.lock( part, LockMode.READ );
Part part2 = s1.get( Part.class, partId );
assertTrue( part == part2 );
assertEquals( check, part2.getName(), "encountered non-repeatable read" );
// then acquire an UPGRADE lock; this should fail
try {
s1.lock( part, LockMode.UPGRADE );
}
catch( Throwable t ) {
// SQLServer, for example, immediately throws an exception here...
t1.rollback();
t1 = s1.beginTransaction();
}
part2 = ( Part ) s1.get( Part.class, partId );
assertTrue( part == part2 );
assertEquals( "encountered non-repeatable read", check, part2.getName() );
t1.commit();
s1.close();
// then acquire an UPGRADE lock; this should fail
try {
s1.lock( part, LockMode.UPGRADE );
}
catch (Throwable t) {
// SQLServer, for example, immediately throws an exception here...
s1.getTransaction().rollback();
s1.beginTransaction();
}
part2 = s1.get( Part.class, partId );
assertTrue( part == part2 );
assertEquals( check, part2.getName(), "encountered non-repeatable read" );
}
);
// clean up
s1 = sessionFactory().openSession();
t1 = s1.beginTransaction();
s1.delete( part );
s1.delete( part.getItem() );
t1.commit();
s1.close();
inTransaction(
session -> {
Part part = session.get( Part.class, partId );
session.delete( part );
session.delete( part.getItem() );
}
);
}
}

View File

@ -4,14 +4,16 @@
* 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;
package org.hibernate.orm.test.jpa.model;
import java.sql.Connection;
import java.util.IdentityHashMap;
import jakarta.persistence.EntityNotFoundException;
import org.hibernate.Session;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.SessionFactoryBuilder;
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.engine.spi.CascadingAction;
import org.hibernate.engine.spi.CascadingActions;
@ -30,29 +32,40 @@ import org.hibernate.integrator.spi.Integrator;
import org.hibernate.proxy.EntityNotFoundDelegate;
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.
*
* @author Steve Ebersole
*/
public abstract class AbstractJPATest extends BaseCoreFunctionalTestCase {
public abstract class AbstractJPATest extends BaseSessionFactoryFunctionalTest {
@Override
public String[] getMappings() {
return new String[] { "jpa/Part.hbm.xml", "jpa/Item.hbm.xml", "jpa/MyEntity.hbm.xml" };
protected String[] getOrmXmlFiles() {
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
public void configure(Configuration cfg) {
super.configure( cfg );
cfg.setProperty( Environment.JPAQL_STRICT_COMPLIANCE, "true" );
cfg.setProperty( Environment.USE_SECOND_LEVEL_CACHE, "false" );
cfg.setEntityNotFoundDelegate( new JPAEntityNotFoundDelegate() );
protected void applySettings(StandardServiceRegistryBuilder builder) {
builder.applySetting( Environment.JPAQL_STRICT_COMPLIANCE, "true" );
builder.applySetting( Environment.USE_SECOND_LEVEL_CACHE, "false" );
}
@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(
new Integrator() {
@ -87,7 +100,7 @@ public abstract class AbstractJPATest extends BaseCoreFunctionalTestCase {
private static class JPAEntityNotFoundDelegate implements EntityNotFoundDelegate {
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 );
}
}
@ -119,7 +132,7 @@ public abstract class AbstractJPATest extends BaseCoreFunctionalTestCase {
public static class JPAPersistOnFlushEventListener extends JPAPersistEventListener {
@Override
protected CascadingAction getCascadeAction() {
protected CascadingAction getCascadeAction() {
return CascadingActions.PERSIST_ON_FLUSH;
}
}
@ -129,12 +142,12 @@ public abstract class AbstractJPATest extends BaseCoreFunctionalTestCase {
public static final AutoFlushEventListener INSTANCE = new JPAAutoFlushEventListener();
@Override
protected CascadingAction getCascadingAction() {
protected CascadingAction getCascadingAction() {
return CascadingActions.PERSIST_ON_FLUSH;
}
@Override
protected Object getAnything() {
protected Object getAnything() {
return new IdentityHashMap( 10 );
}
}
@ -144,12 +157,12 @@ public abstract class AbstractJPATest extends BaseCoreFunctionalTestCase {
public static final FlushEventListener INSTANCE = new JPAFlushEventListener();
@Override
protected CascadingAction getCascadingAction() {
protected CascadingAction getCascadingAction() {
return CascadingActions.PERSIST_ON_FLUSH;
}
@Override
protected Object getAnything() {
protected Object getAnything() {
return new IdentityHashMap( 10 );
}
}
@ -157,4 +170,21 @@ public abstract class AbstractJPATest extends BaseCoreFunctionalTestCase {
public static class JPAFlushEntityEventListener extends DefaultFlushEntityEventListener {
// 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"
"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">
<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.
* 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.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.Id;

View File

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

View File

@ -8,7 +8,7 @@
-->
<!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">
<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.
* 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.
* 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"
"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">
<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.
* 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;
/**

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.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.
* 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.Id;
import jakarta.persistence.OneToOne;
import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertNotNull;
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
*/
@TestForIssue( jiraKey = "HHH-9663" )
public class OneToOneEagerNonOptionalOrphanRemovalTest extends BaseEntityManagerFunctionalTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] { Car.class, PaintColor.class, Engine.class };
}
@TestForIssue(jiraKey = "HHH-9663")
@Jpa(
annotatedClasses = {
OneToOneEagerNonOptionalOrphanRemovalTest.Car.class,
OneToOneEagerNonOptionalOrphanRemovalTest.PaintColor.class,
OneToOneEagerNonOptionalOrphanRemovalTest.Engine.class
}
)
public class OneToOneEagerNonOptionalOrphanRemovalTest {
@Test
public void testOneToOneLazyNonOptionalOrphanRemoval() {
public void testOneToOneLazyNonOptionalOrphanRemoval(EntityManagerFactoryScope scope) {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Initialize the data
doInJPA( this::entityManagerFactory, entityManager -> {
scope.inTransaction( entityManager -> {
final PaintColor color = new PaintColor( 1, "Red" );
final Engine engine1 = new Engine( 1, 275 );
final Engine engine2 = new Engine( 2, 295 );
@ -47,14 +50,14 @@ public class OneToOneEagerNonOptionalOrphanRemovalTest extends BaseEntityManager
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Test orphan removal for unidirectional relationship
doInJPA( this::entityManagerFactory, entityManager -> {
scope.inTransaction( entityManager -> {
final Car car = entityManager.find( Car.class, 1 );
final Engine engine = entityManager.find( Engine.class, 2 );
car.setEngine( engine );
entityManager.merge( car );
} );
doInJPA( this::entityManagerFactory, entityManager -> {
scope.inTransaction( entityManager -> {
final Car car = entityManager.find( Car.class, 1 );
assertNotNull( car.getEngine() );
@ -64,7 +67,7 @@ public class OneToOneEagerNonOptionalOrphanRemovalTest extends BaseEntityManager
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Test orphan removal for bidirectional relationship
doInJPA( this::entityManagerFactory, entityManager -> {
scope.inTransaction( entityManager -> {
final PaintColor color = new PaintColor( 2, "Blue" );
final Car car = entityManager.find( Car.class, 1 );
car.setPaintColor( color );
@ -72,7 +75,7 @@ public class OneToOneEagerNonOptionalOrphanRemovalTest extends BaseEntityManager
entityManager.merge( car );
} );
doInJPA( this::entityManagerFactory, entityManager -> {
scope.inTransaction( entityManager -> {
final Car car = entityManager.find( Car.class, 1 );
assertNotNull( car.getPaintColor() );

View File

@ -4,36 +4,39 @@
* 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.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.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToOne;
import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase;
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.assertNull;
/**
* @author Chris Cranford
*/
@TestForIssue( jiraKey = "HHH-9663" )
public class OneToOneEagerOrphanRemovalTest extends BaseEntityManagerFunctionalTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] { Car.class, PaintColor.class, Engine.class };
}
@TestForIssue(jiraKey = "HHH-9663")
@Jpa(
annotatedClasses = {
OneToOneEagerOrphanRemovalTest.Car.class,
OneToOneEagerOrphanRemovalTest.PaintColor.class,
OneToOneEagerOrphanRemovalTest.Engine.class
}
)
public class OneToOneEagerOrphanRemovalTest {
@Test
public void testOneToOneEagerOrphanRemoval() {
public void testOneToOneEagerOrphanRemoval(EntityManagerFactoryScope scope) {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Initialize the data
doInJPA( this::entityManagerFactory, entityManager -> {
scope.inTransaction( entityManager -> {
final PaintColor color = new PaintColor( 1, "Red" );
final Engine engine = new Engine( 1, 275 );
final Car car = new Car( 1, engine, color );
@ -45,13 +48,13 @@ public class OneToOneEagerOrphanRemovalTest extends BaseEntityManagerFunctionalT
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Test orphan removal for unidirectional relationship
doInJPA( this::entityManagerFactory, entityManager -> {
scope.inTransaction( entityManager -> {
final Car car = entityManager.find( Car.class, 1 );
car.setEngine( null );
entityManager.merge( car );
} );
doInJPA( this::entityManagerFactory, entityManager -> {
scope.inTransaction( entityManager -> {
final Car car = entityManager.find( Car.class, 1 );
assertNull( car.getEngine() );
@ -61,13 +64,13 @@ public class OneToOneEagerOrphanRemovalTest extends BaseEntityManagerFunctionalT
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Test orphan removal for bidirectional relationship
doInJPA( this::entityManagerFactory, entityManager -> {
scope.inTransaction( entityManager -> {
final Car car = entityManager.find( Car.class, 1 );
car.setPaintColor( null );
entityManager.merge( car );
} );
doInJPA( this::entityManagerFactory, entityManager -> {
scope.inTransaction( entityManager -> {
final Car car = entityManager.find( Car.class, 1 );
assertNull( car.getPaintColor() );

View File

@ -4,37 +4,39 @@
* 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.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.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToOne;
import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase;
import org.junit.Test;
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;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* @author Chris Cranford
*/
@TestForIssue( jiraKey = "HHH-9663" )
public class OneToOneLazyNonOptionalOrphanRemovalTest extends BaseEntityManagerFunctionalTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] { Car.class, PaintColor.class, Engine.class };
}
@TestForIssue(jiraKey = "HHH-9663")
@Jpa(
annotatedClasses = {
OneToOneLazyNonOptionalOrphanRemovalTest.Car.class,
OneToOneLazyNonOptionalOrphanRemovalTest.PaintColor.class,
OneToOneLazyNonOptionalOrphanRemovalTest.Engine.class
}
)
public class OneToOneLazyNonOptionalOrphanRemovalTest {
@Test
public void testOneToOneLazyNonOptionalOrphanRemoval() {
public void testOneToOneLazyNonOptionalOrphanRemoval(EntityManagerFactoryScope scope) {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Initialize the data
doInJPA( this::entityManagerFactory, entityManager -> {
scope.inTransaction( entityManager -> {
final PaintColor color = new PaintColor( 1, "Red" );
final Engine engine1 = new Engine( 1, 275 );
final Engine engine2 = new Engine( 2, 295 );
@ -48,14 +50,14 @@ public class OneToOneLazyNonOptionalOrphanRemovalTest extends BaseEntityManagerF
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Test orphan removal for unidirectional relationship
doInJPA( this::entityManagerFactory, entityManager -> {
scope.inTransaction( entityManager -> {
final Car car = entityManager.find( Car.class, 1 );
final Engine engine = entityManager.find( Engine.class, 2 );
car.setEngine( engine );
entityManager.merge( car );
} );
doInJPA( this::entityManagerFactory, entityManager -> {
scope.inTransaction( entityManager -> {
final Car car = entityManager.find( Car.class, 1 );
assertNotNull( car.getEngine() );
@ -65,7 +67,7 @@ public class OneToOneLazyNonOptionalOrphanRemovalTest extends BaseEntityManagerF
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Test orphan removal for bidirectional relationship
doInJPA( this::entityManagerFactory, entityManager -> {
scope.inTransaction( entityManager -> {
final PaintColor color = new PaintColor( 2, "Blue" );
final Car car = entityManager.find( Car.class, 1 );
car.setPaintColor( color );
@ -73,7 +75,7 @@ public class OneToOneLazyNonOptionalOrphanRemovalTest extends BaseEntityManagerF
entityManager.merge( car );
} );
doInJPA( this::entityManagerFactory, entityManager -> {
scope.inTransaction( entityManager -> {
final Car car = entityManager.find( Car.class, 1 );
assertNotNull( car.getPaintColor() );

View File

@ -4,36 +4,39 @@
* 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.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.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToOne;
import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase;
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.assertNull;
/**
* @author Chris Cranford
*/
@TestForIssue( jiraKey = "HHH-9663" )
public class OneToOneLazyOrphanRemovalTest extends BaseEntityManagerFunctionalTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] { Car.class, PaintColor.class, Engine.class };
}
@TestForIssue(jiraKey = "HHH-9663")
@Jpa(
annotatedClasses = {
OneToOneLazyOrphanRemovalTest.Car.class,
OneToOneLazyOrphanRemovalTest.PaintColor.class,
OneToOneLazyOrphanRemovalTest.Engine.class
}
)
public class OneToOneLazyOrphanRemovalTest {
@Test
public void testOneToOneLazyOrphanRemoval() {
public void testOneToOneLazyOrphanRemoval(EntityManagerFactoryScope scope) {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Initialize the data
doInJPA( this::entityManagerFactory, entityManager -> {
scope.inTransaction( entityManager -> {
final PaintColor color = new PaintColor( 1, "Red" );
final Engine engine = new Engine( 1, 275 );
final Car car = new Car( 1, engine, color );
@ -45,13 +48,13 @@ public class OneToOneLazyOrphanRemovalTest extends BaseEntityManagerFunctionalTe
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Test orphan removal for unidirectional relationship
doInJPA( this::entityManagerFactory, entityManager -> {
scope.inTransaction( entityManager -> {
final Car car = entityManager.find( Car.class, 1 );
car.setEngine( null );
entityManager.merge( car );
} );
doInJPA( this::entityManagerFactory, entityManager -> {
scope.inTransaction( entityManager -> {
final Car car = entityManager.find( Car.class, 1 );
assertNull( car.getEngine() );
@ -61,13 +64,13 @@ public class OneToOneLazyOrphanRemovalTest extends BaseEntityManagerFunctionalTe
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Test orphan removal for bidirectional relationship
doInJPA( this::entityManagerFactory, entityManager -> {
scope.inTransaction( entityManager -> {
final Car car = entityManager.find( Car.class, 1 );
car.setPaintColor( null );
entityManager.merge( car );
} );
doInJPA( this::entityManagerFactory, entityManager -> {
scope.inTransaction( entityManager -> {
final Car car = entityManager.find( Car.class, 1 );
assertNull( car.getPaintColor() );

View File

@ -4,16 +4,23 @@
* 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.orphan.one2one.embedded;
package org.hibernate.orm.test.jpa.orphan.onetoone.embedded;
import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase;
import org.junit.Assert;
import org.junit.Test;
import org.hibernate.testing.orm.junit.EntityManagerFactoryScope;
import org.hibernate.testing.orm.junit.Jpa;
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,
@ -22,48 +29,51 @@ import static org.junit.Assert.assertNull;
*
* @TestForIssue( jiraKey = "HHH-9663" )
*/
public class OneToOneLazyOrphanRemovalInEmbeddedEntityTest extends BaseEntityManagerFunctionalTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] { RaceDriver.class, Car.class, Engine.class};
}
@Jpa(
annotatedClasses = {
OneToOneLazyOrphanRemovalInEmbeddedEntityTest.RaceDriver.class,
OneToOneLazyOrphanRemovalInEmbeddedEntityTest.Car.class,
OneToOneLazyOrphanRemovalInEmbeddedEntityTest.Engine.class
}
)
public class OneToOneLazyOrphanRemovalInEmbeddedEntityTest {
@Test
public void testOneToOneLazyOrphanRemoval() {
public void testOneToOneLazyOrphanRemoval(EntityManagerFactoryScope scope) {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Initialize the data
doInJPA( this::entityManagerFactory, entityManager -> {
scope.inTransaction( entityManager -> {
final Engine engine = new Engine( 1, 275 );
final Car car = new Car(1, engine, "red");
final RaceDriver raceDriver = new RaceDriver(1, car);
final Car car = new Car( 1, engine, "red" );
final RaceDriver raceDriver = new RaceDriver( 1, car );
entityManager.persist( engine );
entityManager.persist( raceDriver );
} );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//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 Car car = raceDriver.getCar();
//check, that at the moment the engine is orphan
Assert.assertNotNull(car.getEngine());
assertNotNull( car.getEngine() );
car.setEngine( null );
entityManager.merge( raceDriver );
final RaceDriver raceDriver2 = entityManager.find( RaceDriver.class, 1 );
Assert.assertNotNull(raceDriver2.car);
assertNotNull( raceDriver2.car );
} );
//check, that the engine is deleted:
doInJPA( this::entityManagerFactory, entityManager -> {
scope.inTransaction( entityManager -> {
final RaceDriver raceDriver = entityManager.find( RaceDriver.class, 1 );
final Car car = raceDriver.getCar();
Assert.assertNull(car.getEngine());
assertNull( car.getEngine() );
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;
import org.hibernate.orm.test.jpa.model.AbstractJPATest;
import org.junit.jupiter.api.Test;
import jakarta.persistence.Column;
import jakarta.persistence.DiscriminatorColumn;
import jakarta.persistence.DiscriminatorType;
@ -16,11 +19,6 @@ import jakarta.persistence.Inheritance;
import jakarta.persistence.InheritanceType;
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
* be treated as case-insensitive according to JPA.
@ -31,44 +29,52 @@ public class IdentificationVariablesTest extends AbstractJPATest {
@Test
public void testUsageInSelect() {
Session s = openSession();
s.createQuery( "select I from Item i" ).list();
s.close();
inSession(
session ->
session.createQuery( "select I from Item i" ).list()
);
}
@Test
public void testUsageInPath() {
Session s = openSession();
s.createQuery( "select I from Item i where I.name = 'widget'" ).list();
s.close();
inSession(
session ->
session.createQuery( "select I from Item i where I.name = 'widget'" ).list()
);
}
@Test
public void testMixedTckUsage() {
Session s = openSession();
s.createQuery( "Select DISTINCT OBJECT(P) from Product p where P.quantity < 10" ).list();
s.close();
inSession(
session ->
session.createQuery( "Select DISTINCT OBJECT(P) from Product p where P.quantity < 10" ).list()
);
}
@Test
public void testUsageInJpaInCollectionSyntax() {
Session s = openSession();
s.createQuery( "SELECT DISTINCT object(i) FROM Item I, IN(i.parts) ip where ip.stockNumber = '123'" ).list();
s.close();
inSession(
session ->
session.createQuery(
"SELECT DISTINCT object(i) FROM Item I, IN(i.parts) ip where ip.stockNumber = '123'" )
.list()
);
}
@Test
public void testUsageInDistinct() {
Session s = openSession();
s.createQuery( "select distinct(I) from Item i" ).list();
s.close();
inSession(
session ->
session.createQuery( "select distinct(I) from Item i" ).list()
);
}
@Test
public void testUsageInSelectObject() {
Session s = openSession();
s.createQuery( "select OBJECT(I) from Item i" ).list();
s.close();
inSession(
session ->
session.createQuery( "select OBJECT(I) from Item i" ).list()
);
}
@Override
@ -76,11 +82,11 @@ public class IdentificationVariablesTest extends AbstractJPATest {
return new Class[] { Product.class };
}
@Entity( name = "Product")
@Table( name = "PROD" )
@Inheritance( strategy = InheritanceType.SINGLE_TABLE )
@DiscriminatorColumn( name = "PRODUCT_TYPE", discriminatorType = DiscriminatorType.STRING )
@DiscriminatorValue( "Product" )
@Entity(name = "Product")
@Table(name = "PROD")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "PRODUCT_TYPE", discriminatorType = DiscriminatorType.STRING)
@DiscriminatorValue("Product")
public static class Product {
private String id;
private String name;

View File

@ -9,20 +9,18 @@ package org.hibernate.orm.test.jpa.ql;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.hibernate.query.SemanticException;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.transaction.TransactionUtil2;
import org.hibernate.test.jpa.AbstractJPATest;
import org.hibernate.test.jpa.Item;
import org.junit.Test;
import org.hibernate.orm.test.jpa.model.AbstractJPATest;
import org.hibernate.orm.test.jpa.model.Item;
import org.junit.jupiter.api.Test;
import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.hibernate.testing.orm.junit.ExtraAssertions.assertTyping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Tests for various JPAQL compliance issues
@ -30,61 +28,72 @@ import static org.junit.Assert.fail;
* @author Steve Ebersole
*/
public class JPAQLComplianceTest extends AbstractJPATest {
@Test
public void testAliasNameSameAsUnqualifiedEntityName() {
Session s = openSession();
s.beginTransaction();
s.createQuery( "select item from Item item" ).list();
s.createQuery( "select item from Item item where item.name = 'a'" ).list();
s.getTransaction().commit();
s.close();
inTransaction(
session -> {
session.createQuery( "select item from Item item" ).list();
session.createQuery( "select item from Item item where item.name = 'a'" ).list();
}
);
}
@Test
public void testIdentifierCaseSensitive() {
Session s = openSession( );
// a control test (a user reported that the JPA 'case insensitivity' support
// caused problems with the "discriminator resolution" code; unable to reproduce)...
s.createQuery( "select E from MyEntity e where other.class = MySubclassEntity" );
s.createQuery( "select e from MyEntity e where e.other.class = MySubclassEntity" );
s.createQuery( "select e from MyEntity E where e.class = MySubclassEntity" );
inSession(
session -> {
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();
s.close();
session.createQuery( "select object(I) from Item i" ).list();
}
);
}
@Test
public void testIdentifierCasesensitivityAndDuplicateFromElements() {
Session s = openSession();
s.createQuery( "select e from MyEntity e where exists (select 1 from MyEntity e2 where e2.other.name = 'something' and e2.other.other = e)" );
s.close();
inSession(
session ->
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
public void testGeneratedSubquery() {
Session s = openSession();
s.createQuery( "select c FROM Item c WHERE c.parts IS EMPTY" ).list();
s.close();
inSession(
session ->
session.createQuery( "select c FROM Item c WHERE c.parts IS EMPTY" ).list()
);
}
@Test
public void testOrderByAlias() {
Session s = openSession();
s.createQuery( "select c.name as myname FROM Item c ORDER BY myname" ).list();
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();
s.close();
inSession(
session -> {
session.createQuery( "select c.name as myname FROM Item c ORDER BY myname" ).list();
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
@TestForIssue(jiraKey = "HHH-12290")
public void testParametersMixturePositionalAndNamed() {
TransactionUtil2.inTransaction(
sessionFactory(),
inTransaction(
s -> {
try {
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" );
} catch ( IllegalArgumentException e ) {
}
catch (IllegalArgumentException e) {
assertNotNull( e.getCause() );
assertTyping( SemanticException.class, e.getCause() );
}
@ -95,8 +104,7 @@ public class JPAQLComplianceTest extends AbstractJPATest {
@Test
@TestForIssue(jiraKey = "HHH-12290")
public void testParametersMixtureNamedAndPositional() {
TransactionUtil2.inTransaction(
sessionFactory(),
inTransaction(
s -> {
try {
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
@TestForIssue(jiraKey = "HHH-12290")
public void testReusedNamedCollectionParam() {
TransactionUtil2.inTransaction(
sessionFactory(),
inTransaction(
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<>();
params.add( "name" );
params.add( "other" );
@ -129,8 +137,7 @@ public class JPAQLComplianceTest extends AbstractJPATest {
@Test
@TestForIssue(jiraKey = "HHH-12290")
public void testReusedPositionalCollectionParam() {
TransactionUtil2.inTransaction(
sessionFactory(),
inTransaction(
session -> {
Query q = session.createQuery( "select e from MyEntity e where e.name in (?1) or e.surname in (?1)" );
List<String> params = new ArrayList<>();
@ -149,11 +156,11 @@ public class JPAQLComplianceTest extends AbstractJPATest {
@Test
@TestForIssue(jiraKey = "HHH-12290")
public void testParametersMixtureNamedCollectionAndPositional() {
TransactionUtil2.inTransaction(
sessionFactory(),
inTransaction(
s -> {
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<>();
params.add( 0L );
params.add( 1L );
@ -178,16 +185,14 @@ public class JPAQLComplianceTest extends AbstractJPATest {
final Item item2 = new Item( "Computer" );
item2.setId( 2L );
TransactionUtil2.inTransaction(
sessionFactory(),
inTransaction(
s -> {
s.save( item );
s.save( item2 );
}
);
TransactionUtil2.inTransaction(
sessionFactory(),
inTransaction(
s -> {
Query q = s.createQuery(
"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(
sessionFactory(),
inTransaction(
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.test.jpa.MapContent;
import org.hibernate.test.jpa.MapOwner;
import org.hibernate.test.jpa.Relationship;
import org.hibernate.orm.test.jpa.model.MapContent;
import org.hibernate.orm.test.jpa.model.MapOwner;
import org.hibernate.orm.test.jpa.model.Relationship;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.jdbc.SQLStatementInspector;
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;
import org.hibernate.Session;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.engine.spi.SessionImplementor;
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.JtaTransactionCoordinatorImpl;
import org.hibernate.testing.jta.TestingJtaBootstrap;
import org.hibernate.testing.jta.TestingJtaPlatformImpl;
import org.hibernate.testing.junit4.ExtraAssertions;
import org.hibernate.test.jpa.AbstractJPATest;
import org.junit.Test;
import org.hibernate.testing.orm.junit.ExtraAssertions;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Steve Ebersole
*/
public class JtaTransactionJoiningTest extends AbstractJPATest {
@Override
public void configure(Configuration cfg) {
super.configure( cfg );
TestingJtaBootstrap.prepare( cfg.getProperties() );
cfg.setProperty(
protected void applySettings(StandardServiceRegistryBuilder builder) {
super.applySettings( builder );
TestingJtaBootstrap.prepare( builder.getSettings() );
builder.applySetting(
AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY,
JtaTransactionCoordinatorBuilderImpl.class.getName()
);
@ -41,48 +41,47 @@ public class JtaTransactionJoiningTest extends AbstractJPATest {
public void testExplicitJoining() throws Exception {
assertFalse( JtaStatusHelper.isActive( TestingJtaPlatformImpl.INSTANCE.getTransactionManager() ) );
SessionImplementor session = (SessionImplementor) sessionFactory().withOptions()
try (SessionImplementor session = (SessionImplementor) sessionFactory().withOptions()
.autoJoinTransactions( false )
.openSession();
.openSession()) {
ExtraAssertions.assertTyping( JtaTransactionCoordinatorImpl.class, session.getTransactionCoordinator() );
JtaTransactionCoordinatorImpl transactionCoordinator = (JtaTransactionCoordinatorImpl) session.getTransactionCoordinator();
ExtraAssertions.assertTyping( JtaTransactionCoordinatorImpl.class, session.getTransactionCoordinator() );
JtaTransactionCoordinatorImpl transactionCoordinator = (JtaTransactionCoordinatorImpl) session.getTransactionCoordinator();
assertFalse( transactionCoordinator.isSynchronizationRegistered() );
assertFalse( transactionCoordinator.isJtaTransactionCurrentlyActive() );
assertFalse( transactionCoordinator.isJoined() );
assertFalse( transactionCoordinator.isSynchronizationRegistered() );
assertFalse( transactionCoordinator.isJtaTransactionCurrentlyActive() );
assertFalse( transactionCoordinator.isJoined() );
session.getFlushMode(); // causes a call to TransactionCoordinator#pulse
session.getFlushMode(); // causes a call to TransactionCoordinator#pulse
assertFalse( transactionCoordinator.isSynchronizationRegistered() );
assertFalse( transactionCoordinator.isJtaTransactionCurrentlyActive() );
assertFalse( transactionCoordinator.isJoined() );
assertFalse( transactionCoordinator.isSynchronizationRegistered() );
assertFalse( transactionCoordinator.isJtaTransactionCurrentlyActive() );
assertFalse( transactionCoordinator.isJoined() );
TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
assertTrue( JtaStatusHelper.isActive( TestingJtaPlatformImpl.INSTANCE.getTransactionManager() ) );
assertTrue( transactionCoordinator.isJtaTransactionCurrentlyActive() );
assertFalse( transactionCoordinator.isJoined() );
assertFalse( transactionCoordinator.isSynchronizationRegistered() );
assertTrue( JtaStatusHelper.isActive( TestingJtaPlatformImpl.INSTANCE.getTransactionManager() ) );
assertTrue( transactionCoordinator.isJtaTransactionCurrentlyActive() );
assertFalse( transactionCoordinator.isJoined() );
assertFalse( transactionCoordinator.isSynchronizationRegistered() );
session.getFlushMode();
session.getFlushMode();
assertTrue( JtaStatusHelper.isActive( TestingJtaPlatformImpl.INSTANCE.getTransactionManager() ) );
assertTrue( transactionCoordinator.isJtaTransactionCurrentlyActive() );
assertFalse( transactionCoordinator.isSynchronizationRegistered() );
assertFalse( transactionCoordinator.isJoined() );
assertTrue( JtaStatusHelper.isActive( TestingJtaPlatformImpl.INSTANCE.getTransactionManager() ) );
assertTrue( transactionCoordinator.isJtaTransactionCurrentlyActive() );
assertFalse( transactionCoordinator.isSynchronizationRegistered() );
assertFalse( transactionCoordinator.isJoined() );
transactionCoordinator.explicitJoin();
session.getFlushMode();
transactionCoordinator.explicitJoin();
session.getFlushMode();
assertTrue( JtaStatusHelper.isActive( TestingJtaPlatformImpl.INSTANCE.getTransactionManager() ) );
assertTrue( transactionCoordinator.isJtaTransactionCurrentlyActive() );
assertTrue( transactionCoordinator.isSynchronizationRegistered() );
assertTrue( transactionCoordinator.isJoined() );
((Session) session).close();
TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();
assertTrue( JtaStatusHelper.isActive( TestingJtaPlatformImpl.INSTANCE.getTransactionManager() ) );
assertTrue( transactionCoordinator.isJtaTransactionCurrentlyActive() );
assertTrue( transactionCoordinator.isSynchronizationRegistered() );
assertTrue( transactionCoordinator.isJoined() );
}
finally {
TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();
}
}
@Test
@ -92,11 +91,14 @@ public class JtaTransactionJoiningTest extends AbstractJPATest {
TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
assertTrue( JtaStatusHelper.isActive( TestingJtaPlatformImpl.INSTANCE.getTransactionManager() ) );
SessionImplementor session = (SessionImplementor) sessionFactory().withOptions()
try (SessionImplementor session = (SessionImplementor) sessionFactory().withOptions()
.autoJoinTransactions( false )
.openSession();
session.getFlushMode();
.openSession()) {
session.getFlushMode();
}
finally {
TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();
}
}
@Test
@ -106,17 +108,17 @@ public class JtaTransactionJoiningTest extends AbstractJPATest {
TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
assertTrue( JtaStatusHelper.isActive( TestingJtaPlatformImpl.INSTANCE.getTransactionManager() ) );
SessionImplementor session = (SessionImplementor) sessionFactory().openSession();
ExtraAssertions.assertTyping( JtaTransactionCoordinatorImpl.class, session.getTransactionCoordinator() );
JtaTransactionCoordinatorImpl transactionCoordinator = (JtaTransactionCoordinatorImpl) session.getTransactionCoordinator();
try (SessionImplementor session = (SessionImplementor) sessionFactory().openSession()) {
ExtraAssertions.assertTyping( JtaTransactionCoordinatorImpl.class, session.getTransactionCoordinator() );
JtaTransactionCoordinatorImpl transactionCoordinator = (JtaTransactionCoordinatorImpl) session.getTransactionCoordinator();
assertTrue( transactionCoordinator.isSynchronizationRegistered() );
assertTrue( transactionCoordinator.isActive() );
assertTrue( transactionCoordinator.isJoined() );
( (Session) session ).close();
TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();
assertTrue( transactionCoordinator.isSynchronizationRegistered() );
assertTrue( transactionCoordinator.isActive() );
assertTrue( transactionCoordinator.isJoined() );
}
finally {
TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();
}
}
}

View File

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

View File

@ -4,7 +4,7 @@
* 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;
package org.hibernate.orm.test.mapping;
import java.util.Locale;
@ -13,9 +13,9 @@ import org.hibernate.dialect.PostgreSQL94Dialect;
import org.hibernate.mapping.Column;
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

View File

@ -4,7 +4,7 @@
* 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;
package org.hibernate.orm.test.mapping;
import java.io.Serializable;
import java.util.Objects;
@ -14,20 +14,20 @@ import jakarta.persistence.IdClass;
import jakarta.persistence.MappedSuperclass;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.junit.Test;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.junit.jupiter.api.Test;
@TestForIssue(jiraKey = "HHH-14499")
public class MappedSuperclassWithGenericsTest extends BaseCoreFunctionalTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] {
IntermediateAbstractMapped.class,
BaseEntity.class,
AbstractGenericMappedSuperType.class,
};
}
@DomainModel(
annotatedClasses = {
MappedSuperclassWithGenericsTest.IntermediateAbstractMapped.class,
MappedSuperclassWithGenericsTest.BaseEntity.class,
MappedSuperclassWithGenericsTest.AbstractGenericMappedSuperType.class,
}
)
@SessionFactory
public class MappedSuperclassWithGenericsTest {
@Test
public void testIt() {

View File

@ -4,7 +4,7 @@
* 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;
package org.hibernate.orm.test.mapping;
import org.hibernate.MappingException;
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.RootClass;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.boot.MetadataBuildingContextTestingImpl;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
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;
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 MetadataBuildingContext metadataBuildingContext;
@Before
@BeforeEach
public void prepare() {
serviceRegistry = new StandardServiceRegistryBuilder().build();
metadataBuildingContext = new MetadataBuildingContextTestingImpl( serviceRegistry );
}
@After
@AfterEach
public void release() {
StandardServiceRegistryBuilder.destroy( serviceRegistry );
}
@ -39,35 +43,36 @@ public class PersistentClassTest extends BaseUnitTestCase {
@Test
public void testGetMappedClass() {
RootClass pc = new RootClass( metadataBuildingContext );
pc.setClassName(String.class.getName());
Assert.assertEquals(String.class.getName(), pc.getClassName());
Assert.assertEquals(String.class, pc.getMappedClass());
pc.setClassName(Integer.class.getName());
Assert.assertEquals(Integer.class, pc.getMappedClass());
pc.setClassName( String.class.getName() );
assertEquals( String.class.getName(), pc.getClassName() );
assertEquals( String.class, pc.getMappedClass() );
pc.setClassName( Integer.class.getName() );
assertEquals( Integer.class, pc.getMappedClass() );
}
@Test
public void testGetProxyInterface() {
RootClass pc = new RootClass( metadataBuildingContext );
pc.setProxyInterfaceName(String.class.getName());
Assert.assertEquals(String.class.getName(), pc.getProxyInterfaceName());
Assert.assertEquals(String.class, pc.getProxyInterface());
pc.setProxyInterfaceName(Integer.class.getName());
Assert.assertEquals(Integer.class, pc.getProxyInterface());
pc.setProxyInterfaceName( String.class.getName() );
assertEquals( String.class.getName(), pc.getProxyInterfaceName() );
assertEquals( String.class, pc.getProxyInterface() );
pc.setProxyInterfaceName( Integer.class.getName() );
assertEquals( Integer.class, pc.getProxyInterface() );
}
@Test
public void testGetProperty() {
RootClass pc = new RootClass( metadataBuildingContext );
Property p = new Property();
p.setName("name");
pc.addProperty(p);
Assert.assertEquals(p, pc.getProperty("name"));
Assert.assertEquals(p, pc.getProperty("name.test"));
p.setName( "name" );
pc.addProperty( p );
assertEquals( p, pc.getProperty( "name" ) );
assertEquals( p, pc.getProperty( "name.test" ) );
try {
Assert.assertNull(pc.getProperty("test"));
Assert.fail("MappingException expected");
} catch (MappingException e) {
assertNull( pc.getProperty( "test" ) );
fail( "MappingException expected" );
}
catch (MappingException e) {
// expected
}
}

View File

@ -4,11 +4,7 @@
* 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;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
package org.hibernate.orm.test.mapping;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
@ -19,26 +15,30 @@ import org.hibernate.mapping.RootClass;
import org.hibernate.mapping.SingleTableSubclass;
import org.hibernate.mapping.Subclass;
import org.hibernate.mapping.UnionSubclass;
import org.hibernate.testing.junit4.BaseUnitTestCase;
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.
*
* @author max
*/
public class PersistentClassVisitorTest extends BaseUnitTestCase {
@BaseUnitTest
public class PersistentClassVisitorTest {
private StandardServiceRegistry serviceRegistry;
private MetadataBuildingContext metadataBuildingContext;
@Before
@BeforeEach
public void prepare() {
serviceRegistry = new StandardServiceRegistryBuilder().build();
metadataBuildingContext = new MetadataBuildingContextTestingImpl( serviceRegistry );
}
@After
@AfterEach
public void release() {
StandardServiceRegistryBuilder.destroy( serviceRegistry );
}

View File

@ -4,10 +4,21 @@
* 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.cascade;
package org.hibernate.orm.test.mapping.cascade;
import java.util.HashSet;
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.Column;
import jakarta.persistence.Entity;
@ -19,109 +30,103 @@ import jakarta.persistence.OneToMany;
import jakarta.persistence.OneToOne;
import jakarta.persistence.Table;
import org.hibernate.LazyInitializationException;
import org.hibernate.Session;
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;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Testing relationships between components: example invoice -> invoice line
*
* @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 INVOICE_A = "Invoice A";
static String INVOICELINE_A = "InvoiceLine A";
static String INVOICELINE_B = "InvoiceLine B";
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] {
Invoice.class,
InvoiceLine.class,
Receipt.class
};
static String INVOICE_A = "Invoice A";
static String INVOICELINE_A = "InvoiceLine A";
static String INVOICELINE_B = "InvoiceLine B";
public Invoice createInvoiceWithTwoInvoiceLines(Session session) {
InvoiceLine lineA = new InvoiceLine( INVOICELINE_A );
InvoiceLine lineB = new InvoiceLine( INVOICELINE_B );
Invoice invoice = new Invoice( INVOICE_A );
invoice.addInvoiceLine( lineA );
invoice.addInvoiceLine( lineB );
session.persist( invoice );
return invoice;
}
public Invoice createInvoiceWithTwoInvoiceLines(Session session) {
InvoiceLine lineA = new InvoiceLine(INVOICELINE_A);
InvoiceLine lineB = new InvoiceLine(INVOICELINE_B);
@Test
@TestForIssue(jiraKey = "HHH-11916")
public void testPersistOnAlreadyPersistentEntityWithUninitializedLazyCollection(SessionFactoryScope scope) {
Invoice invoice = new Invoice(INVOICE_A);
invoice.addInvoiceLine(lineA);
invoice.addInvoiceLine(lineB);
session.persist(invoice);
final Invoice _invoice = scope.fromTransaction( session -> createInvoiceWithTwoInvoiceLines( session ) );
return invoice;
}
@Test
@TestForIssue( jiraKey = "HHH-11916" )
public void testPersistOnAlreadyPersistentEntityWithUninitializedLazyCollection() {
final Invoice _invoice = doInHibernate( this::sessionFactory, this::createInvoiceWithTwoInvoiceLines );
Invoice invoiceAfter = doInHibernate( this::sessionFactory, session -> {
Invoice invoiceAfter = scope.fromTransaction( session -> {
SessionStatistics stats = session.getStatistics();
// load invoice, invoiceLines should not be loaded
Invoice invoice = session.get(Invoice.class, _invoice.getId());
Assert.assertEquals(
"Invoice lines should not be initialized while loading the invoice, " +
"because of the lazy association.", 1, stats.getEntityCount());
Invoice invoice = session.get( Invoice.class, _invoice.getId() );
assertEquals(
1,
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;
} );
try {
invoiceAfter.getInvoiceLines().size();
fail("Should throw LazyInitializationException");
fail( "Should throw LazyInitializationException" );
}
catch (LazyInitializationException expected) {
}
}
@Test
@TestForIssue( jiraKey = "HHH-11916" )
public void testPersistOnNewEntityRelatedToAlreadyPersistentEntityWithUninitializedLazyCollection() {
final Invoice _invoice = doInHibernate( this::sessionFactory, this::createInvoiceWithTwoInvoiceLines );
Invoice invoiceAfter = doInHibernate( this::sessionFactory, session -> {
@Test
@TestForIssue(jiraKey = "HHH-11916")
public void testPersistOnNewEntityRelatedToAlreadyPersistentEntityWithUninitializedLazyCollection(
SessionFactoryScope scope) {
final Invoice _invoice = scope.fromTransaction( session -> createInvoiceWithTwoInvoiceLines( session ) );
Invoice invoiceAfter = scope.fromTransaction( session -> {
SessionStatistics stats = session.getStatistics();
// load invoice, invoiceLines should not be loaded
Invoice invoice = session.get(Invoice.class, _invoice.getId());
Assert.assertEquals(
"Invoice lines should not be initialized while loading the invoice, " +
"because of the lazy association.", 1, stats.getEntityCount());
Invoice invoice = session.get( Invoice.class, _invoice.getId() );
assertEquals( 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);
session.persist(receipt);
receipt.setInvoice( invoice );
session.persist( receipt );
return invoice;
} );
try {
invoiceAfter.getInvoiceLines().size();
fail("Should throw LazyInitializationException");
fail( "Should throw LazyInitializationException" );
}
catch (LazyInitializationException expected) {
}
}
}
@Entity
@Table(name = "OTM_Invoice")
@ -168,7 +173,7 @@ public class PersistOnLazyCollectionTest extends BaseCoreFunctionalTestCase{
}
public void addInvoiceLine(InvoiceLine invoiceLine) {
invoiceLines.add(invoiceLine);
invoiceLines.add( invoiceLine );
}
}
@ -206,7 +211,7 @@ public class PersistOnLazyCollectionTest extends BaseCoreFunctionalTestCase{
@Table(name = "OTM_Receipt")
public static class Receipt {
@OneToOne(cascade = { CascadeType.PERSIST})
@OneToOne(cascade = { CascadeType.PERSIST })
private Invoice invoice;
@Id

View File

@ -4,7 +4,7 @@
* 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;
package org.hibernate.orm.test.mapping.joinformula;
import jakarta.persistence.Column;
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.
* 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.JoinColumnsOrFormulas;

View File

@ -4,7 +4,7 @@
* 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.lazytoone;
package org.hibernate.orm.test.mapping.lazytoone;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;

View File

@ -4,7 +4,7 @@
* 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.lazytoone;
package org.hibernate.orm.test.mapping.lazytoone;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;

View File

@ -4,7 +4,7 @@
* 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.lazytoone;
package org.hibernate.orm.test.mapping.lazytoone;
import org.hibernate.Hibernate;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

View File

@ -4,7 +4,7 @@
* 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.lazytoone;
package org.hibernate.orm.test.mapping.lazytoone;
import org.hibernate.Hibernate;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

View File

@ -4,7 +4,7 @@
* 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.lazytoone;
package org.hibernate.orm.test.mapping.lazytoone;
import java.math.BigDecimal;
import jakarta.persistence.Entity;

View File

@ -4,7 +4,7 @@
* 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.lazytoone;
package org.hibernate.orm.test.mapping.lazytoone;
import org.hibernate.Hibernate;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

View File

@ -4,7 +4,7 @@
* 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.lazytoone;
package org.hibernate.orm.test.mapping.lazytoone;
import java.math.BigDecimal;
import jakarta.persistence.Entity;

View File

@ -4,7 +4,7 @@
* 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.lazytoone;
package org.hibernate.orm.test.mapping.lazytoone;
import java.math.BigDecimal;
import jakarta.persistence.Entity;

View File

@ -4,7 +4,7 @@
* 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.lazytoone.mappedby;
package org.hibernate.orm.test.mapping.lazytoone.mappedby;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;

View File

@ -4,7 +4,7 @@
* 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.lazytoone.onetoone;
package org.hibernate.orm.test.mapping.lazytoone.onetoone;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;

View File

@ -4,7 +4,7 @@
* 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.lazytoone.onetoone;
package org.hibernate.orm.test.mapping.lazytoone.onetoone;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;

View File

@ -4,7 +4,7 @@
* 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.lazytoone.onetoone;
package org.hibernate.orm.test.mapping.lazytoone.onetoone;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;

View File

@ -4,7 +4,7 @@
* 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.lazytoone.polymorphic;
package org.hibernate.orm.test.mapping.lazytoone.polymorphic;
import java.math.BigDecimal;
import jakarta.persistence.Entity;

View File

@ -4,7 +4,7 @@
* 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.lazytoone.polymorphic;
package org.hibernate.orm.test.mapping.lazytoone.polymorphic;
import java.math.BigDecimal;
import jakarta.persistence.Entity;

View File

@ -4,7 +4,7 @@
* 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.lazytoone.polymorphic;
package org.hibernate.orm.test.mapping.lazytoone.polymorphic;
import java.math.BigDecimal;
import jakarta.persistence.Entity;

View File

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

View File

@ -10,9 +10,8 @@ import java.math.BigDecimal;
import org.hibernate.Session;
import org.junit.Test;
import org.hibernate.test.jpa.AbstractJPATest;
import org.hibernate.orm.test.jpa.model.AbstractJPATest;
import org.junit.jupiter.api.Test;
/**
* 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 {
@Test
public void basicTest() {
Session s = openSession();
s.createQuery( "select i from Item i join i.parts p on p.unitPrice > :filterPrice" )
.setParameter( "filterPrice", new BigDecimal( 100 ) )
.list();
s.close();
try (Session s = sessionFactory().openSession()) {
s.createQuery( "select i from Item i join i.parts p on p.unitPrice > :filterPrice" )
.setParameter( "filterPrice", new BigDecimal( 100 ) )
.list();
}
}
}

View File

@ -4,20 +4,16 @@
* 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.type;
package org.hibernate.orm.test.type;
import java.io.Serializable;
import java.util.Arrays;
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.TypeContributor;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.jpa.boot.spi.TypeContributorList;
import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.AbstractSingleColumnStandardBasicType;
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.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 static org.junit.Assert.assertEquals;
import jakarta.persistence.Column;
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
public Class[] getAnnotatedClasses() {
@ -40,8 +43,8 @@ public class LongListTypeContributorTest extends BaseEntityManagerFunctionalTest
}
@Override
protected void afterEntityManagerFactoryBuilt() {
entityManagerFactory().getMetamodel().getTypeConfiguration().getJavaTypeDescriptorRegistry()
protected void entityManagerFactoryBuilt(EntityManagerFactory factory) {
( (SessionFactoryImplementor) factory ).getTypeConfiguration().getJavaTypeDescriptorRegistry()
.addDescriptor( StringifiedCollectionTypeContributor.StringifiedCollectionJavaTypeDescriptor.INSTANCE );
}
@ -49,7 +52,7 @@ public class LongListTypeContributorTest extends BaseEntityManagerFunctionalTest
protected void addConfigOptions(Map options) {
super.addConfigOptions( options );
options.put( "hibernate.type_contributors", (TypeContributorList) () -> Arrays.asList(
new StringifiedCollectionTypeContributor()
new StringifiedCollectionTypeContributor()
) );
}
@ -57,28 +60,28 @@ public class LongListTypeContributorTest extends BaseEntityManagerFunctionalTest
@TestForIssue(jiraKey = "HHH-11409")
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 );
em.persist( item );
} );
doInJPA( this::entityManagerFactory, em -> {
inTransaction( em -> {
SpecialItem item = (SpecialItem) em.createNativeQuery(
"SELECT * FROM special_table WHERE longList = ?", SpecialItem.class )
.setParameter(1, longList)
.getSingleResult();
"SELECT * FROM special_table WHERE longList = ?", SpecialItem.class )
.setParameter( 1, longList )
.getSingleResult();
assertEquals( "LongList", item.getName() );
} );
doInJPA( this::entityManagerFactory, em -> {
inTransaction( em -> {
SpecialItem item = (SpecialItem) em.createNativeQuery(
"SELECT * FROM special_table WHERE longList = :longList", SpecialItem.class )
.setParameter("longList", longList)
.getSingleResult();
"SELECT * FROM special_table WHERE longList = :longList", SpecialItem.class )
.setParameter( "longList", longList )
.getSingleResult();
assertEquals( "LongList", item.getName() );
} );
@ -155,9 +158,11 @@ public class LongListTypeContributorTest extends BaseEntityManagerFunctionalTest
public static final StringifiedCollectionType INSTANCE = new StringifiedCollectionType();
public StringifiedCollectionType() {
super( LongVarcharJdbcType.INSTANCE,
StringifiedCollectionJavaTypeDescriptor.INSTANCE );
regKeys = new String[]{ LongList.class.getName() };
super(
LongVarcharJdbcType.INSTANCE,
StringifiedCollectionJavaTypeDescriptor.INSTANCE
);
regKeys = new String[] { LongList.class.getName() };
name = "StringifiedCollection";
}

View File

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

View File

@ -6,72 +6,75 @@
*/
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.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
*/
@RequiresDialectFeature(DialectChecks.SupportsTemporaryTable.class)
public class JoinedSubclassBulkManipTest extends BaseCoreFunctionalTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] { Employee.class };
@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsTemporaryTable.class)
@DomainModel(
annotatedClasses = { Employee.class }
)
@SessionFactory
public class JoinedSubclassBulkManipTest {
@Test
@TestForIssue(jiraKey = "HHH-1657")
public void testHqlDeleteOnJoinedSubclass(SessionFactoryScope scope) {
scope.inTransaction(
s -> {
// syntax checking on the database...
s.createQuery( "delete from Employee" ).executeUpdate();
s.createQuery( "delete from Person" ).executeUpdate();
s.createQuery( "delete from Employee e" ).executeUpdate();
s.createQuery( "delete from Person p" ).executeUpdate();
s.createQuery( "delete from Employee where name like 'S%'" ).executeUpdate();
s.createQuery( "delete from Employee e where e.name like 'S%'" ).executeUpdate();
s.createQuery( "delete from Person where name like 'S%'" ).executeUpdate();
s.createQuery( "delete from Person p where p.name like 'S%'" ).executeUpdate();
// 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 normally just the pks. super critical ;)
s.createQuery( "delete from Employee where 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 p where p.id = 1" ).executeUpdate();
}
);
}
@Test
@TestForIssue( jiraKey = "HHH-1657" )
public void testHqlDeleteOnJoinedSubclass() {
Session s = openSession();
s.beginTransaction();
// syntax checking on the database...
s.createQuery( "delete from Employee" ).executeUpdate();
s.createQuery( "delete from Person" ).executeUpdate();
s.createQuery( "delete from Employee e" ).executeUpdate();
s.createQuery( "delete from Person p" ).executeUpdate();
s.createQuery( "delete from Employee where name like 'S%'" ).executeUpdate();
s.createQuery( "delete from Employee e where e.name like 'S%'" ).executeUpdate();
s.createQuery( "delete from Person where name like 'S%'" ).executeUpdate();
s.createQuery( "delete from Person p where p.name like 'S%'" ).executeUpdate();
@TestForIssue(jiraKey = "HHH-1657")
public void testHqlUpdateOnJoinedSubclass(SessionFactoryScope scope) {
scope.inTransaction(
s -> {
// syntax checking on the database...
s.createQuery( "update Employee set name = 'Some Other Name' where employeeNumber like 'A%'" )
.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 p set p.name = 'Some Other Name' where p.name like 'S%'" )
.executeUpdate();
// 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 normally just the pks. super critical ;)
// 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 normally just the pks. super critical ;)
s.createQuery( "delete from Employee where 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 p where p.id = 1" ).executeUpdate();
s.getTransaction().commit();
s.close();
}
@Test
@TestForIssue( jiraKey = "HHH-1657" )
public void testHqlUpdateOnJoinedSubclass() {
Session s = openSession();
s.beginTransaction();
// syntax checking on the database...
s.createQuery( "update Employee set name = 'Some Other Name' where employeeNumber like 'A%'" ).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 p set p.name = 'Some Other Name' where p.name like 'S%'" ).executeUpdate();
// 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 normally just the pks. super critical ;)
s.createQuery( "update Employee set name = 'Some Other Name' where 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 p set p.name = 'Some Other Name' where p.id = 1" ).executeUpdate();
s.getTransaction().commit();
s.close();
s.createQuery( "update Employee set name = 'Some Other Name' where 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 p set p.name = 'Some Other Name' where p.id = 1" ).executeUpdate();
}
);
}
}

View File

@ -7,6 +7,13 @@
package org.hibernate.test.hql.joinedSubclass;
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.Column;
import jakarta.persistence.Entity;
@ -19,79 +26,51 @@ import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
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 Gail Badner
*/
public class JoinedSubclassSubQueryTest extends BaseCoreFunctionalTestCase {
@DomainModel(
annotatedClasses = {
JoinedSubclassSubQueryTest.InvestmentCompany.class,
JoinedSubclassSubQueryTest.Person.class,
JoinedSubclassSubQueryTest.Employee.class
}
)
@SessionFactory
public class JoinedSubclassSubQueryTest {
@Test
@TestForIssue(jiraKey = "HHH-11182")
public void testSubQueryConstraintPropertyInSuperclassTable() {
public void testSubQueryConstraintPropertyInSuperclassTable(SessionFactoryScope scope) {
Session s = openSession();
try {
s.getTransaction().begin();
// employee.firstName is in Person table (not Employee)
String queryHQL = "from InvestmentCompany investmentCompany "
+ "where exists "
+ "(select employee "
+ "from investmentCompany.employees as employee "
+ " where employee.firstName = 'Joe')";
s.createQuery( queryHQL ).uniqueResult();
s.getTransaction().commit();
}
catch (Exception e) {
if ( s.getTransaction() != null && s.getTransaction().isActive() ) {
s.getTransaction().rollback();
}
throw e;
}
finally {
s.close();
}
scope.inTransaction(
session -> {
// employee.firstName is in Person table (not Employee)
String queryHQL = "from InvestmentCompany investmentCompany "
+ "where exists "
+ "(select employee "
+ "from investmentCompany.employees as employee "
+ " where employee.firstName = 'Joe')";
session.createQuery( queryHQL ).uniqueResult();
}
);
}
@Test
@TestForIssue(jiraKey = "HHH-11182")
public void testSubQueryConstraintPropertyInEntityTable() {
Session s = openSession();
try {
s.getTransaction().begin();
// employee.employeeNumber is in Employee table
String queryHQL = "from InvestmentCompany investmentCompany "
+ "where exists "
+ "(select employee "
+ "from investmentCompany.employees as employee "
+ " where employee.employeeNumber = 666 )";
s.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
};
public void testSubQueryConstraintPropertyInEntityTable(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
// employee.employeeNumber is in Employee table
String queryHQL = "from InvestmentCompany investmentCompany "
+ "where exists "
+ "(select employee "
+ "from investmentCompany.employees as employee "
+ " where employee.employeeNumber = 666 )";
session.createQuery( queryHQL ).uniqueResult();
}
);
}
@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;
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 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}
@ -29,110 +28,111 @@ import static org.junit.Assert.fail;
*/
public class ImmutableNaturalIdTest extends AbstractJPATest {
@Override
public String[] getMappings() {
return new String[] { "jpa/naturalid/User.hbm.xml" };
protected String[] getOrmXmlFiles() {
return new String[] { "org/hibernate/test/jpa/naturalid/User.hbm.xml" };
}
@Override
public void configure(Configuration cfg) {
super.configure( cfg );
cfg.setProperty( Environment.USE_SECOND_LEVEL_CACHE, "true" );
cfg.setProperty( Environment.USE_QUERY_CACHE, "true" );
cfg.setProperty( Environment.GENERATE_STATISTICS, "true" );
protected void applySettings(StandardServiceRegistryBuilder builder) {
super.applySettings( builder );
builder.applySetting( Environment.USE_SECOND_LEVEL_CACHE, "true" );
builder.applySetting( Environment.USE_QUERY_CACHE, "true" );
builder.applySetting( Environment.GENERATE_STATISTICS, "true" );
}
@Test
public void testUpdate() {
// prepare some test data...
Session session = openSession();
session.beginTransaction();
User user = new User();
user.setUserName( "steve" );
user.setEmail( "steve@hibernate.org" );
user.setPassword( "brewhaha" );
session.save( user );
session.getTransaction().commit();
session.close();
User user = new User();
inTransaction(
session -> {
user.setUserName( "steve" );
user.setEmail( "steve@hibernate.org" );
user.setPassword( "brewhaha" );
session.save( user );
}
);
// 'user' is now a detached entity, so lets change a property and reattch...
user.setPassword( "homebrew" );
session = openSession();
session.beginTransaction();
session.update( user );
session.getTransaction().commit();
session.close();
inTransaction(
session ->
session.update( user )
);
// clean up
session = openSession();
session.beginTransaction();
session.delete( user );
session.getTransaction().commit();
session.close();
inTransaction(
session ->
session.delete( user )
);
}
@Test
public void testNaturalIdCheck() throws Exception {
Session s = openSession();
Transaction t = s.beginTransaction();
sessionFactoryScope().inSession(
session -> {
Transaction t = session.beginTransaction();
User u = new User( "steve", "superSecret" );
session.persist( u );
u.setUserName( "Steve" );
try {
session.flush();
fail( "PersistenceException expected" );
}
catch (PersistenceException p) {
//expected
t.rollback();
}
u.setUserName( "steve" );
session.delete( u );
session.close();
}
);
User u = new User( "steve", "superSecret" );
s.persist( u );
u.setUserName( "Steve" );
try {
s.flush();
fail();
}
catch ( PersistenceException p ) {
//expected
t.rollback();
}
u.setUserName( "steve" );
s.delete( u );
s.close();
}
@Test
public void testSimpleNaturalIdLoadAccessCache() {
Session s = openSession();
s.beginTransaction();
User u = new User( "steve", "superSecret" );
s.persist( u );
s.getTransaction().commit();
s.close();
inTransaction(
session -> {
User u = new User( "steve", "superSecret" );
session.persist( u );
}
);
s = openSession();
s.beginTransaction();
u = (User) s.bySimpleNaturalId( User.class ).load( "steve" );
assertNotNull( u );
User u2 = (User) s.bySimpleNaturalId( User.class ).getReference( "steve" );
assertTrue( u == u2 );
s.getTransaction().commit();
s.close();
inTransaction(
session -> {
User u = session.bySimpleNaturalId( User.class ).load( "steve" );
assertNotNull( u );
User u2 = session.bySimpleNaturalId( User.class ).getReference( "steve" );
assertSame( u2, u );
}
);
s = openSession();
s.beginTransaction();
s.createQuery( "delete User" ).executeUpdate();
s.getTransaction().commit();
s.close();
inTransaction(
session ->
session.createQuery( "delete User" ).executeUpdate()
);
}
@Test
public void testNaturalIdLoadAccessCache() {
Session s = openSession();
s.beginTransaction();
User u = new User( "steve", "superSecret" );
s.persist( u );
s.getTransaction().commit();
s.close();
inTransaction(
session -> {
User u = new User( "steve", "superSecret" );
session.persist( u );
}
);
sessionFactory().getStatistics().clear();
s = openSession();
s.beginTransaction();
u = (User) s.byNaturalId( User.class ).using( "userName", "steve" ).load();
assertNotNull( u );
s.getTransaction().commit();
s.close();
inTransaction(
session -> {
User u = (User) session.byNaturalId( User.class ).using( "userName", "steve" ).load();
assertNotNull( u );
}
);
assertEquals( 1, sessionFactory().getStatistics().getEntityLoadCount() );
assertEquals( 0, sessionFactory().getStatistics().getSecondLevelCacheMissCount() );
@ -142,36 +142,40 @@ public class ImmutableNaturalIdTest extends AbstractJPATest {
assertEquals( 0, sessionFactory().getStatistics().getNaturalIdCacheHitCount() );
assertEquals( 0, sessionFactory().getStatistics().getNaturalIdCachePutCount() );
s = openSession();
s.beginTransaction();
User v = new User( "gavin", "supsup" );
s.persist( v );
s.getTransaction().commit();
s.close();
inTransaction(
session -> {
User v = new User( "gavin", "supsup" );
session.persist( v );
}
);
sessionFactory().getStatistics().clear();
s = openSession();
s.beginTransaction();
u = (User) s.byNaturalId( User.class ).using( "userName", "steve" ).load();
assertNotNull( u );
assertEquals( 1, sessionFactory().getStatistics().getEntityLoadCount() );
assertEquals( 1, sessionFactory().getStatistics().getNaturalIdQueryExecutionCount() );//0: incorrect stats since hbm.xml can't enable NaturalId caching
assertEquals( 0, sessionFactory().getStatistics().getNaturalIdCacheHitCount() );
u = (User) s.byNaturalId( User.class ).using( "userName", "steve" ).load();
assertNotNull( u );
assertEquals( 1, sessionFactory().getStatistics().getEntityLoadCount() );
assertEquals( 1, sessionFactory().getStatistics().getNaturalIdQueryExecutionCount() );//0: incorrect stats since hbm.xml can't enable NaturalId caching
assertEquals( 0, sessionFactory().getStatistics().getNaturalIdCacheHitCount() );
s.getTransaction().commit();
s.close();
inTransaction(
session -> {
User u = session.byNaturalId( User.class ).using( "userName", "steve" ).load();
assertNotNull( u );
assertEquals( 1, sessionFactory().getStatistics().getEntityLoadCount() );
assertEquals(
1,
sessionFactory().getStatistics().getNaturalIdQueryExecutionCount()
);//0: incorrect stats since hbm.xml can't enable NaturalId caching
assertEquals( 0, sessionFactory().getStatistics().getNaturalIdCacheHitCount() );
u = session.byNaturalId( User.class ).using( "userName", "steve" ).load();
assertNotNull( u );
assertEquals( 1, sessionFactory().getStatistics().getEntityLoadCount() );
assertEquals(
1,
sessionFactory().getStatistics().getNaturalIdQueryExecutionCount()
);//0: incorrect stats since hbm.xml can't enable NaturalId caching
assertEquals( 0, sessionFactory().getStatistics().getNaturalIdCacheHitCount() );
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 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

View File

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

View File

@ -21,6 +21,8 @@ import org.hibernate.dialect.TimeZoneSupport;
import org.hibernate.dialect.TiDBDialect;
import org.hibernate.query.FetchClauseType;
import org.hibernate.testing.DialectCheck;
/**
* 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 boolean apply(Dialect dialect) {
return ! dialect.doesRepeatableReadCauseReadersToBlockWriters();

View File

@ -91,26 +91,7 @@ public class ServiceRegistryExtension
ssrProducer = (ServiceRegistryProducer) testInstance;
}
else {
ssrProducer = ssrb -> {
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();
};
ssrProducer = new ServiceRegistryProducerImpl(context);
}
final ServiceRegistryScopeImpl scope = new ServiceRegistryScopeImpl( bsrProducer, ssrProducer );
@ -127,6 +108,39 @@ public class ServiceRegistryExtension
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(
BootstrapServiceRegistry bsrAnn,
final BootstrapServiceRegistryBuilder bsrBuilder) {
@ -255,6 +269,7 @@ public class ServiceRegistryExtension
private StandardServiceRegistry createRegistry() {
BootstrapServiceRegistryBuilder bsrb = new BootstrapServiceRegistryBuilder().enableAutoClose();
ssrProducer.prepareBootstrapRegistryBuilder(bsrb);
final org.hibernate.boot.registry.BootstrapServiceRegistry bsr = bsrProducer.produceServiceRegistry( bsrb );
try {

View File

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