6 - SQM based on JPA type system

This commit is contained in:
Andrea Boriero 2019-07-12 17:06:37 +01:00
parent fbe622fce6
commit 3d5209d105
9 changed files with 443 additions and 312 deletions

View File

@ -6,11 +6,15 @@
*/ */
package org.hibernate.test.annotations.idmanytoone; package org.hibernate.test.annotations.idmanytoone;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Root;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl; import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl;
import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
@ -23,7 +27,7 @@ import static org.junit.Assert.assertEquals;
*/ */
public class IdManyToOneTest extends BaseCoreFunctionalTestCase { public class IdManyToOneTest extends BaseCoreFunctionalTestCase {
@Test @Test
public void testFkCreationOrdering() throws Exception { public void testFkCreationOrdering() {
//no real test case, the sessionFactory building is tested //no real test case, the sessionFactory building is tested
Session s = openSession(); Session s = openSession();
s.close(); s.close();
@ -31,47 +35,49 @@ public class IdManyToOneTest extends BaseCoreFunctionalTestCase {
@Test @Test
public void testIdClassManyToOne() { public void testIdClassManyToOne() {
Session s = openSession(); inTransaction( s-> {
Transaction tx = s.beginTransaction(); Store store = new Store();
Store store = new Store(); Customer customer = new Customer();
Customer customer = new Customer(); s.persist( store );
s.persist( store ); s.persist( customer );
s.persist( customer ); StoreCustomer sc = new StoreCustomer( store, customer );
StoreCustomer sc = new StoreCustomer( store, customer ); s.persist( sc );
s.persist( sc ); s.flush();
s.flush(); s.clear();
s.clear();
store = (Store) s.get(Store.class, store.id );
assertEquals( 1, store.customers.size() );
assertEquals( customer.id, store.customers.iterator().next().customer.id );
tx.rollback();
store = s.get(Store.class, store.id );
assertEquals( 1, store.customers.size() );
assertEquals( customer.id, store.customers.iterator().next().customer.id );
} );
//TODO test Customers / ShoppingBaskets / BasketItems testIdClassManyToOneWithReferenceColumn //TODO test Customers / ShoppingBaskets / BasketItems testIdClassManyToOneWithReferenceColumn
s.close();
} }
@Test @Test
@TestForIssue( jiraKey = "HHH-7767" ) @TestForIssue( jiraKey = "HHH-7767" )
public void testCriteriaRestrictionOnIdManyToOne() { public void testCriteriaRestrictionOnIdManyToOne() {
Session s = openSession(); inTransaction( s -> {
s.beginTransaction(); s.createQuery( "from Course c join c.students cs join cs.student s where s.name = 'Foo'" ).list();
s.createQuery( "from Course c join c.students cs join cs.student s where s.name = 'Foo'" ).list(); CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder();
CriteriaQuery<Course> criteria = criteriaBuilder.createQuery( Course.class );
Root<Course> root = criteria.from( Course.class );
Join<Object, Object> students = root.join( "students", JoinType.INNER );
Join<Object, Object> student = students.join( "student", JoinType.INNER );
criteria.where( criteriaBuilder.equal( student.get( "name" ), "Foo" ) );
session.createQuery( criteria ).list();
// Criteria criteria = s.createCriteria( Course.class );
// criteria.createCriteria( "students" ).createCriteria( "student" ).add( Restrictions.eq( "name", "Foo" ) );
// criteria.list();
Criteria criteria = s.createCriteria( Course.class ); // CriteriaQuery<Course> criteria2 = criteriaBuilder.createQuery( Course.class );
criteria.createCriteria( "students" ).createCriteria( "student" ).add( Restrictions.eq( "name", "Foo" ) );
criteria.list();
Criteria criteria2 = s.createCriteria( Course.class ); // Criteria criteria2 = s.createCriteria( Course.class );
criteria2.createAlias( "students", "cs" ); // criteria2.createAlias( "students", "cs" );
criteria2.add( Restrictions.eq( "cs.value", "Bar" ) ); // criteria2.add( Restrictions.eq( "cs.value", "Bar" ) );
criteria2.createAlias( "cs.student", "s" ); // criteria2.createAlias( "cs.student", "s" );
criteria2.add( Restrictions.eq( "s.name", "Foo" ) ); // criteria2.add( Restrictions.eq( "s.name", "Foo" ) );
criteria2.list(); // criteria2.list();
} );
s.getTransaction().commit();
s.close();
} }
@Override @Override

View File

@ -8,8 +8,10 @@ package org.hibernate.test.annotations.onetoone;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import javax.persistence.PersistenceException; import javax.persistence.PersistenceException;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.hibernate.criterion.Restrictions;
import org.hibernate.id.IdentifierGenerationException; import org.hibernate.id.IdentifierGenerationException;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
@ -49,7 +51,7 @@ public class OptionalOneToOneMappedByTest extends BaseCoreFunctionalTestCase {
} }
@Test @Test
public void testBidirAssignedId() throws Exception { public void testBidirAssignedId() {
doInHibernate( this::sessionFactory, session -> { doInHibernate( this::sessionFactory, session -> {
PartyAffiliate affiliate = new PartyAffiliate(); PartyAffiliate affiliate = new PartyAffiliate();
affiliate.partyId = "id"; affiliate.partyId = "id";
@ -58,10 +60,16 @@ public class OptionalOneToOneMappedByTest extends BaseCoreFunctionalTestCase {
} ); } );
doInHibernate( this::sessionFactory, session -> { doInHibernate( this::sessionFactory, session -> {
PartyAffiliate affiliate = (PartyAffiliate) session.createCriteria( CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
PartyAffiliate.class ) CriteriaQuery<PartyAffiliate> criteria = criteriaBuilder.createQuery( PartyAffiliate.class );
.add( Restrictions.idEq( "id" ) ) Root<PartyAffiliate> root = criteria.from( PartyAffiliate.class );
.uniqueResult(); criteria.where( criteriaBuilder.equal( root.get("partyId"), "id" ) );
PartyAffiliate affiliate = session.createQuery( criteria ).uniqueResult();
// PartyAffiliate affiliate = (PartyAffiliate) session.createCriteria(
// PartyAffiliate.class )
// .add( Restrictions.idEq( "id" ) )
// .uniqueResult();
assertNotNull( affiliate ); assertNotNull( affiliate );
assertEquals( "id", affiliate.partyId ); assertEquals( "id", affiliate.partyId );
assertNull( affiliate.party ); assertNull( affiliate.party );
@ -79,7 +87,7 @@ public class OptionalOneToOneMappedByTest extends BaseCoreFunctionalTestCase {
} }
@Test @Test
public void testBidirDefaultIdGenerator() throws Exception { public void testBidirDefaultIdGenerator() {
PersonAddress _personAddress = doInHibernate( PersonAddress _personAddress = doInHibernate(
this::sessionFactory, this::sessionFactory,
session -> { session -> {
@ -93,10 +101,15 @@ public class OptionalOneToOneMappedByTest extends BaseCoreFunctionalTestCase {
); );
doInHibernate( this::sessionFactory, session -> { doInHibernate( this::sessionFactory, session -> {
PersonAddress personAddress = (PersonAddress) session.createCriteria( CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
PersonAddress.class ) CriteriaQuery<PersonAddress> criteria = criteriaBuilder.createQuery( PersonAddress.class );
.add( Restrictions.idEq( _personAddress.getId() ) ) Root<PersonAddress> root = criteria.from( PersonAddress.class );
.uniqueResult(); criteria.where( criteriaBuilder.equal( root.get("id"), _personAddress.getId()) );
PersonAddress personAddress = session.createQuery( criteria ).uniqueResult();
// PersonAddress personAddress = (PersonAddress) session.createCriteria(
// PersonAddress.class )
// .add( Restrictions.idEq( _personAddress.getId() ) )
// .uniqueResult();
assertNotNull( personAddress ); assertNotNull( personAddress );
assertNull( personAddress.getPerson() ); assertNull( personAddress.getPerson() );
} ); } );
@ -114,7 +127,7 @@ public class OptionalOneToOneMappedByTest extends BaseCoreFunctionalTestCase {
@Test @Test
@TestForIssue(jiraKey = "HHH-5757") @TestForIssue(jiraKey = "HHH-5757")
public void testBidirQueryEntityProperty() throws Exception { public void testBidirQueryEntityProperty() {
AtomicReference<Person> personHolder = new AtomicReference<>(); AtomicReference<Person> personHolder = new AtomicReference<>();
@ -135,11 +148,16 @@ public class OptionalOneToOneMappedByTest extends BaseCoreFunctionalTestCase {
} }
); );
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
doInHibernate( this::sessionFactory, session -> { doInHibernate( this::sessionFactory, session -> {
PersonAddress personAddress = (PersonAddress) session.createCriteria( CriteriaQuery<PersonAddress> criteria = criteriaBuilder.createQuery( PersonAddress.class );
PersonAddress.class ) Root<PersonAddress> root = criteria.from( PersonAddress.class );
.add( Restrictions.idEq( _personAddress.getId() ) ) criteria.where( criteriaBuilder.equal( root.get("id"), _personAddress.getId()) );
.uniqueResult(); PersonAddress personAddress = session.createQuery( criteria ).uniqueResult();
// PersonAddress personAddress = (PersonAddress) session.createCriteria(
// PersonAddress.class )
// .add( Restrictions.idEq( _personAddress.getId() ) )
// .uniqueResult();
assertNotNull( personAddress ); assertNotNull( personAddress );
assertNotNull( personAddress.getPerson() ); assertNotNull( personAddress.getPerson() );
} ); } );
@ -147,15 +165,20 @@ public class OptionalOneToOneMappedByTest extends BaseCoreFunctionalTestCase {
doInHibernate( this::sessionFactory, session -> { doInHibernate( this::sessionFactory, session -> {
Person person = personHolder.get(); Person person = personHolder.get();
// this call throws GenericJDBCException // this call throws GenericJDBCException
PersonAddress personAddress = (PersonAddress) session.createQuery( PersonAddress personAddress = session.createQuery(
"select pa from PersonAddress pa where pa.person = :person", PersonAddress.class ) "select pa from PersonAddress pa where pa.person = :person", PersonAddress.class )
.setParameter( "person", person ) .setParameter( "person", person )
.getSingleResult(); .getSingleResult();
CriteriaQuery<Person> criteria = criteriaBuilder.createQuery( Person.class );
Root<Person> root = criteria.from( Person.class );
criteria.where( criteriaBuilder.equal( root.get("personAddress"), personAddress ) );
session.createQuery( criteria ).uniqueResult();
// the other way should also work // the other way should also work
person = (Person) session.createCriteria( Person.class ) // person = (Person) session.createCriteria( Person.class )
.add( Restrictions.eq( "personAddress", personAddress ) ) // .add( Restrictions.eq( "personAddress", personAddress ) )
.uniqueResult(); // .uniqueResult();
session.delete( personAddress ); session.delete( personAddress );
} ); } );

View File

@ -7,10 +7,12 @@
package org.hibernate.test.annotations.onetoone; package org.hibernate.test.annotations.onetoone;
import javax.persistence.PersistenceException; import javax.persistence.PersistenceException;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.Transaction; import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.hibernate.id.IdentifierGenerationException; import org.hibernate.id.IdentifierGenerationException;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
@ -97,9 +99,15 @@ public class OptionalOneToOnePKJCTest extends BaseCoreFunctionalTestCase {
s = openSession(); s = openSession();
s.getTransaction().begin(); s.getTransaction().begin();
owner = ( Owner ) s.createCriteria( Owner.class ) CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder();
.add( Restrictions.idEq( owner.getId() ) ) CriteriaQuery<Owner> criteria = criteriaBuilder.createQuery( Owner.class );
.uniqueResult(); Root<Owner> root = criteria.from( Owner.class );
criteria.where( criteriaBuilder.equal( root.get( "id" ), owner.getId() ) );
owner = s.createQuery( criteria ).uniqueResult();
// owner = ( Owner ) s.createCriteria( Owner.class )
// .add( Restrictions.idEq( owner.getId() ) )
// .uniqueResult();
assertNotNull( owner ); assertNotNull( owner );
assertNull( owner.getAddress() ); assertNull( owner.getAddress() );
s.delete( owner ); s.delete( owner );
@ -127,9 +135,16 @@ public class OptionalOneToOnePKJCTest extends BaseCoreFunctionalTestCase {
s = openSession(); s = openSession();
s.getTransaction().begin(); s.getTransaction().begin();
party = ( Party ) s.createCriteria( Party.class )
.add( Restrictions.idEq( "id" ) ) CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder();
.uniqueResult(); CriteriaQuery<Party> criteria = criteriaBuilder.createQuery( Party.class );
Root<Party> root = criteria.from( Party.class );
criteria.where( criteriaBuilder.equal( root.get( "partyId" ), "id" ) );
party = s.createQuery( criteria ).uniqueResult();
// party = ( Party ) s.createCriteria( Party.class )
// .add( Restrictions.idEq( "id" ) )
// .uniqueResult();
assertNotNull( party ); assertNotNull( party );
assertEquals( "id", party.partyId ); assertEquals( "id", party.partyId );
assertNull( party.partyAffiliate ); assertNull( party.partyAffiliate );

View File

@ -9,11 +9,15 @@ package org.hibernate.test.collection.set;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map; import java.util.Map;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.hibernate.CacheMode; import org.hibernate.CacheMode;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.AvailableSettings;
import org.hibernate.collection.internal.PersistentSet; import org.hibernate.collection.internal.PersistentSet;
import org.hibernate.criterion.Restrictions; import org.hibernate.query.Query;
import org.hibernate.stat.CollectionStatistics; import org.hibernate.stat.CollectionStatistics;
import org.hibernate.testing.FailureExpected; import org.hibernate.testing.FailureExpected;
@ -146,7 +150,7 @@ public class PersistentSetTest extends BaseNonConfigCoreFunctionalTestCase {
session = openSession(); session = openSession();
session.beginTransaction(); session.beginTransaction();
parent = ( Parent ) session.get( Parent.class, "p1" ); parent = session.get( Parent.class, "p1" );
assertEquals( 1, parent.getChildren().size() ); assertEquals( 1, parent.getChildren().size() );
session.getTransaction().commit(); session.getTransaction().commit();
session.close(); session.close();
@ -243,7 +247,7 @@ public class PersistentSetTest extends BaseNonConfigCoreFunctionalTestCase {
session = openSession(); session = openSession();
session.beginTransaction(); session.beginTransaction();
container = ( Container ) session.get( Container.class, container.getId() ); container = session.get( Container.class, container.getId() );
assertEquals( 1, container.getContents().size() ); assertEquals( 1, container.getContents().size() );
session.delete( container ); session.delete( container );
session.getTransaction().commit(); session.getTransaction().commit();
@ -268,7 +272,7 @@ public class PersistentSetTest extends BaseNonConfigCoreFunctionalTestCase {
session = openSession(); session = openSession();
session.beginTransaction(); session.beginTransaction();
container = ( Container ) session.get( Container.class, container.getId() ); container = session.get( Container.class, container.getId() );
assertEquals( 1, container.getContents().size() ); assertEquals( 1, container.getContents().size() );
session.getTransaction().commit(); session.getTransaction().commit();
session.close(); session.close();
@ -279,7 +283,7 @@ public class PersistentSetTest extends BaseNonConfigCoreFunctionalTestCase {
session = openSession(); session = openSession();
session.beginTransaction(); session.beginTransaction();
container = ( Container ) session.get( Container.class, container.getId() ); container = session.get( Container.class, container.getId() );
assertEquals( 1, container.getContents().size() ); assertEquals( 1, container.getContents().size() );
session.delete( container ); session.delete( container );
session.getTransaction().commit(); session.getTransaction().commit();
@ -305,7 +309,7 @@ public class PersistentSetTest extends BaseNonConfigCoreFunctionalTestCase {
session = openSession(); session = openSession();
session.beginTransaction(); session.beginTransaction();
parent = ( Parent ) session.get( Parent.class, parent.getName() ); parent = session.get( Parent.class, parent.getName() );
assertTrue( parent.getChildren().contains( child ) ); assertTrue( parent.getChildren().contains( child ) );
assertTrue( parent.getChildren().contains( otherChild ) ); assertTrue( parent.getChildren().contains( otherChild ) );
session.getTransaction().commit(); session.getTransaction().commit();
@ -313,22 +317,34 @@ public class PersistentSetTest extends BaseNonConfigCoreFunctionalTestCase {
session = openSession(); session = openSession();
session.beginTransaction(); session.beginTransaction();
child = ( Child ) session.get( Child.class, child.getName() ); child = session.get( Child.class, child.getName() );
assertTrue( child.getParent().getChildren().contains( child ) ); assertTrue( child.getParent().getChildren().contains( child ) );
session.clear(); session.clear();
child = ( Child ) session.createCriteria( Child.class, child.getName() ) CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
.setCacheable( true ) CriteriaQuery<Child> criteria = criteriaBuilder.createQuery( Child.class );
.add( Restrictions.idEq( "c1" ) ) Root<Child> root = criteria.from( Child.class );
.uniqueResult(); criteria.where( criteriaBuilder.equal( root.get( "name" ), "c1" ));
child = session.createQuery( criteria ).uniqueResult();
// child = ( Child ) session.createCriteria( Child.class, child.getName() )
// .setCacheable( true )
// .add( Restrictions.idEq( "c1" ) )
// .uniqueResult();
assertTrue( child.getParent().getChildren().contains( child ) ); assertTrue( child.getParent().getChildren().contains( child ) );
assertTrue( child.getParent().getChildren().contains( otherChild ) ); assertTrue( child.getParent().getChildren().contains( otherChild ) );
session.clear(); session.clear();
child = ( Child ) session.createCriteria( Child.class, child.getName() ) CriteriaQuery<Child> criteriaQuery = criteriaBuilder.createQuery( Child.class );
.setCacheable( true ) Root<Child> childRoot = criteriaQuery.from( Child.class );
.add( Restrictions.idEq( "c1" ) ) criteriaQuery.where( criteriaBuilder.equal( childRoot.get( "name" ), "c1" ));
.uniqueResult(); Query<Child> query = session.createQuery( criteriaQuery );
query.setCacheable( true );
child = query.uniqueResult();
// child = ( Child ) session.createCriteria( Child.class, child.getName() )
// .setCacheable( true )
// .add( Restrictions.idEq( "c1" ) )
// .uniqueResult();
assertTrue( child.getParent().getChildren().contains( child ) ); assertTrue( child.getParent().getChildren().contains( child ) );
assertTrue( child.getParent().getChildren().contains( otherChild ) ); assertTrue( child.getParent().getChildren().contains( otherChild ) );
session.clear(); session.clear();
@ -366,7 +382,7 @@ public class PersistentSetTest extends BaseNonConfigCoreFunctionalTestCase {
session = openSession(); session = openSession();
session.beginTransaction(); session.beginTransaction();
session.setCacheMode( CacheMode.IGNORE ); session.setCacheMode( CacheMode.IGNORE );
parent = ( Parent ) session.get( Parent.class, parent.getName() ); parent = session.get( Parent.class, parent.getName() );
assertTrue( parent.getChildren().contains( child ) ); assertTrue( parent.getChildren().contains( child ) );
assertTrue( parent.getChildren().contains( otherChild ) ); assertTrue( parent.getChildren().contains( otherChild ) );
session.getTransaction().commit(); session.getTransaction().commit();
@ -375,13 +391,19 @@ public class PersistentSetTest extends BaseNonConfigCoreFunctionalTestCase {
session.beginTransaction(); session.beginTransaction();
session.setCacheMode( CacheMode.IGNORE ); session.setCacheMode( CacheMode.IGNORE );
child = ( Child ) session.get( Child.class, child.getName() ); child = session.get( Child.class, child.getName() );
assertTrue( child.getParent().getChildren().contains( child ) ); assertTrue( child.getParent().getChildren().contains( child ) );
session.clear(); session.clear();
child = ( Child ) session.createCriteria( Child.class, child.getName() ) CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
.add( Restrictions.idEq( "c1" ) ) CriteriaQuery<Child> criteria = criteriaBuilder.createQuery( Child.class );
.uniqueResult(); Root<Child> root = criteria.from( Child.class );
criteria.where( criteriaBuilder.equal( root.get( "name" ), "c1" ) );
child = session.createQuery( criteria ).uniqueResult();
// child = ( Child ) session.createCriteria( Child.class, child.getName() )
// .add( Restrictions.idEq( "c1" ) )
// .uniqueResult();
assertTrue( child.getParent().getChildren().contains( child ) ); assertTrue( child.getParent().getChildren().contains( child ) );
assertTrue( child.getParent().getChildren().contains( otherChild ) ); assertTrue( child.getParent().getChildren().contains( otherChild ) );
session.clear(); session.clear();

View File

@ -8,10 +8,13 @@ package org.hibernate.test.compositeelement;
import java.util.ArrayList; import java.util.ArrayList;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.Transaction; import org.hibernate.Transaction;
import org.hibernate.boot.Metadata; import org.hibernate.boot.Metadata;
import org.hibernate.criterion.Restrictions;
import org.hibernate.dialect.function.SQLFunction; import org.hibernate.dialect.function.SQLFunction;
import org.hibernate.mapping.Collection; import org.hibernate.mapping.Collection;
import org.hibernate.mapping.Component; import org.hibernate.mapping.Component;
@ -88,42 +91,51 @@ public class CompositeElementTest extends BaseNonConfigCoreFunctionalTestCase {
@Test @Test
public void testCustomColumnReadAndWrite() { public void testCustomColumnReadAndWrite() {
Session s = openSession(); inTransaction( s -> {
Transaction t = s.beginTransaction(); Child c = new Child( "Child One" );
Child c = new Child( "Child One" ); c.setPosition( 1 );
c.setPosition( 1 ); Parent p = new Parent( "Parent" );
Parent p = new Parent( "Parent" ); p.getChildren().add( c );
p.getChildren().add( c ); c.setParent( p );
c.setParent( p ); s.save( p );
s.save( p ); s.flush();
s.flush();
// Oracle returns BigDecimaal while other dialects return Integer; // Oracle returns BigDecimaal while other dialects return Integer;
// casting to Number so it works on all dialects // casting to Number so it works on all dialects
Number sqlValue = ((Number) s.createSQLQuery("select child_position from ParentChild c where c.name='Child One'") Number sqlValue = ( (Number) s.createNativeQuery(
.uniqueResult()); "select child_position from ParentChild c where c.name='Child One'" )
assertEquals( 0, sqlValue.intValue() ); .uniqueResult() );
assertEquals( 0, sqlValue.intValue() );
Integer hqlValue = (Integer)s.createQuery("select c.position from Parent p join p.children c where p.name='Parent'") Integer hqlValue = (Integer) s.createQuery(
.uniqueResult(); "select c.position from Parent p join p.children c where p.name='Parent'" )
assertEquals( 1, hqlValue.intValue() ); .uniqueResult();
assertEquals( 1, hqlValue.intValue() );
p = (Parent)s.createCriteria(Parent.class).add(Restrictions.eq("name", "Parent")).uniqueResult(); // p = (Parent) s.createCriteria( Parent.class ).add( Restrictions.eq( "name", "Parent" ) ).uniqueResult();
c = (Child)p.getChildren().iterator().next();
assertEquals( 1, c.getPosition() );
p = (Parent)s.createQuery("from Parent p join p.children c where c.position = 1").uniqueResult(); CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder();
c = (Child)p.getChildren().iterator().next(); CriteriaQuery<Parent> criteria = criteriaBuilder.createQuery( Parent.class );
assertEquals( 1, c.getPosition() ); Root<Parent> root = criteria.from( Parent.class );
criteria.where( criteriaBuilder.equal( root.get( "name" ),"Parent" ) );
c.setPosition( 2 ); p = s.createQuery( criteria ).uniqueResult();
s.flush();
sqlValue = ( (Number) s.createSQLQuery("select child_position from ParentChild c where c.name='Child One'") c = (Child) p.getChildren().iterator().next();
.uniqueResult() ); assertEquals( 1, c.getPosition() );
assertEquals( 1, sqlValue.intValue() );
s.delete( p ); p = (Parent) s.createQuery( "from Parent p join p.children c where c.position = 1" ).uniqueResult();
t.commit(); c = (Child) p.getChildren().iterator().next();
s.close(); assertEquals( 1, c.getPosition() );
c.setPosition( 2 );
s.flush();
sqlValue = ( (Number) s.createNativeQuery(
"select child_position from ParentChild c where c.name='Child One'" )
.uniqueResult() );
assertEquals( 1, sqlValue.intValue() );
s.delete( p );
} );
} }
} }

View File

@ -6,8 +6,9 @@
*/ */
package org.hibernate.test.fetchprofiles.join.selfReferencing; package org.hibernate.test.fetchprofiles.join.selfReferencing;
import org.hibernate.Session; import javax.persistence.criteria.CriteriaBuilder;
import org.hibernate.criterion.Restrictions; import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.junit.Test; import org.junit.Test;
@ -24,13 +25,16 @@ public class JoinSelfReferentialFetchProfileTest extends BaseCoreFunctionalTestC
@Test @Test
public void testEnablingJoinFetchProfileAgainstSelfReferentialAssociation() { public void testEnablingJoinFetchProfileAgainstSelfReferentialAssociation() {
Session s = openSession(); inTransaction( s-> {
s.beginTransaction(); s.enableFetchProfile( Employee.FETCH_PROFILE_TREE );
s.enableFetchProfile( Employee.FETCH_PROFILE_TREE ); CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder();
s.createCriteria( Employee.class ) CriteriaQuery<Employee> criteria = criteriaBuilder.createQuery( Employee.class );
.add( Restrictions.isNull( "manager" ) ) Root<Employee> root = criteria.from( Employee.class );
.list(); criteria.where( criteriaBuilder.isNull( root.get( "manager" ) ) );
s.getTransaction().commit(); s.createQuery( criteria ).list();
s.close(); // s.createCriteria( Employee.class )
// .add( Restrictions.isNull( "manager" ) )
// .list();
} );
} }
} }

View File

@ -5,18 +5,24 @@
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.joinedsubclass; package org.hibernate.test.joinedsubclass;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.junit.Test; import org.junit.Test;
import org.hibernate.Hibernate; import org.hibernate.Hibernate;
import org.hibernate.LockMode; import org.hibernate.LockMode;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.Transaction; import org.hibernate.Transaction;
import org.hibernate.criterion.Property; import org.hibernate.query.Query;
import org.hibernate.criterion.Restrictions;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
@ -37,77 +43,94 @@ public class JoinedSubclassTest extends BaseCoreFunctionalTestCase {
@Test @Test
public void testJoinedSubclass() { public void testJoinedSubclass() {
Session s = openSession(); inTransaction( s -> {
Transaction t = s.beginTransaction();
Employee mark = new Employee(); Employee mark = new Employee();
mark.setName("Mark"); mark.setName( "Mark" );
mark.setTitle("internal sales"); mark.setTitle( "internal sales" );
mark.setSex('M'); mark.setSex( 'M' );
mark.setAddress("buckhead"); mark.setAddress( "buckhead" );
mark.setZip("30305"); mark.setZip( "30305" );
mark.setCountry("USA"); mark.setCountry( "USA" );
Customer joe = new Customer(); Customer joe = new Customer();
joe.setName("Joe"); joe.setName( "Joe" );
joe.setAddress("San Francisco"); joe.setAddress( "San Francisco" );
joe.setZip("XXXXX"); joe.setZip( "XXXXX" );
joe.setCountry("USA"); joe.setCountry( "USA" );
joe.setComments("Very demanding"); joe.setComments( "Very demanding" );
joe.setSex('M'); joe.setSex( 'M' );
joe.setSalesperson(mark); joe.setSalesperson( mark );
Person yomomma = new Person(); Person yomomma = new Person();
yomomma.setName("mum"); yomomma.setName( "mum" );
yomomma.setSex('F'); yomomma.setSex( 'F' );
s.save(yomomma); s.save( yomomma );
s.save(mark); s.save( mark );
s.save(joe); s.save( joe );
assertEquals( s.createQuery("from java.io.Serializable").list().size(), 0 ); assertEquals( s.createQuery( "from java.io.Serializable" ).list().size(), 0 );
assertEquals( s.createQuery("from Person").list().size(), 3 ); assertEquals( s.createQuery( "from Person" ).list().size(), 3 );
assertEquals( s.createQuery("from Person p where p.class = Customer").list().size(), 1 ); assertEquals( s.createQuery( "from Person p where p.class = Customer" ).list().size(), 1 );
assertEquals( s.createQuery("from Person p where p.class = Person").list().size(), 1 ); assertEquals( s.createQuery( "from Person p where p.class = Person" ).list().size(), 1 );
assertEquals( s.createQuery("from Person p where type(p) in :who").setParameter("who", Customer.class).list().size(), 1 ); assertEquals( s.createQuery( "from Person p where type(p) in :who" )
assertEquals( s.createQuery("from Person p where type(p) in :who").setParameterList("who", new Class[] {Customer.class, Person.class}).list().size(), 2 ); .setParameter( "who", Customer.class )
s.clear(); .list()
.size(), 1 );
assertEquals( s.createQuery( "from Person p where type(p) in :who" ).setParameterList(
"who",
new Class[] {
Customer.class,
Person.class
}
).list().size(), 2 );
s.clear();
List customers = s.createQuery("from Customer c left join fetch c.salesperson").list(); List customers = s.createQuery( "from Customer c left join fetch c.salesperson" ).list();
for ( Iterator iter = customers.iterator(); iter.hasNext(); ) { for ( Iterator iter = customers.iterator(); iter.hasNext(); ) {
Customer c = (Customer) iter.next(); Customer c = (Customer) iter.next();
assertTrue( Hibernate.isInitialized( c.getSalesperson() ) ); assertTrue( Hibernate.isInitialized( c.getSalesperson() ) );
assertEquals( c.getSalesperson().getName(), "Mark" ); assertEquals( c.getSalesperson().getName(), "Mark" );
} }
assertEquals( customers.size(), 1 ); assertEquals( customers.size(), 1 );
s.clear(); s.clear();
customers = s.createQuery("from Customer").list(); customers = s.createQuery( "from Customer" ).list();
for ( Iterator iter = customers.iterator(); iter.hasNext(); ) { for ( Iterator iter = customers.iterator(); iter.hasNext(); ) {
Customer c = (Customer) iter.next(); Customer c = (Customer) iter.next();
assertFalse( Hibernate.isInitialized( c.getSalesperson() ) ); assertFalse( Hibernate.isInitialized( c.getSalesperson() ) );
assertEquals( c.getSalesperson().getName(), "Mark" ); assertEquals( c.getSalesperson().getName(), "Mark" );
} }
assertEquals( customers.size(), 1 ); assertEquals( customers.size(), 1 );
s.clear(); s.clear();
mark = (Employee) s.get( Employee.class, new Long( mark.getId() ) ); mark = (Employee) s.get( Employee.class, new Long( mark.getId() ) );
joe = (Customer) s.get( Customer.class, new Long( joe.getId() ) ); joe = (Customer) s.get( Customer.class, new Long( joe.getId() ) );
mark.setZip("30306"); mark.setZip( "30306" );
assertEquals( s.createQuery("from Person p where p.address.zip = '30306'" ).list().size(),1 ); assertEquals( s.createQuery( "from Person p where p.address.zip = '30306'" ).list().size(), 1 );
s.createCriteria( Person.class ).add( CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder();
Restrictions.in( "address", mark.getAddress(), joe.getAddress() ) ).list(); CriteriaQuery<Person> criteria = criteriaBuilder.createQuery( Person.class );
Root<Person> root = criteria.from( Person.class );
CriteriaBuilder.In<Address> in = criteriaBuilder.in( root.get( "address" ) );
in.value( mark.getAddress() );
in.value( joe.getAddress() );
s.delete(mark); criteria.where( in );
s.delete(joe); Query<Person> query = s.createQuery( criteria );
s.delete(yomomma); query.list();
assertTrue( s.createQuery("from Person").list().isEmpty() ); // s.createCriteria( Person.class ).add(
t.commit(); // Restrictions.in( "address", mark.getAddress(), joe.getAddress() ) ).list();
s.close();
s.delete( mark );
s.delete( joe );
s.delete( yomomma );
assertTrue( s.createQuery( "from Person" ).list().isEmpty() );
} );
} }
@Test @Test
@ -124,15 +147,15 @@ public class JoinedSubclassTest extends BaseCoreFunctionalTestCase {
s = openSession(); s = openSession();
s.beginTransaction(); s.beginTransaction();
Customer c = ( Customer ) s.get( Customer.class, new Long( e.getId() ) ); Customer c = s.get( Customer.class, new Long( e.getId() ) );
s.getTransaction().commit(); s.getTransaction().commit();
s.close(); s.close();
assertNull( c ); assertNull( c );
s = openSession(); s = openSession();
s.beginTransaction(); s.beginTransaction();
e = ( Employee ) s.get( Employee.class, new Long( e.getId() ) ); e = s.get( Employee.class, new Long( e.getId() ) );
c = ( Customer ) s.get( Customer.class, new Long( e.getId() ) ); c = s.get( Customer.class, new Long( e.getId() ) );
s.getTransaction().commit(); s.getTransaction().commit();
s.close(); s.close();
assertNotNull( e ); assertNotNull( e );
@ -147,41 +170,47 @@ public class JoinedSubclassTest extends BaseCoreFunctionalTestCase {
@Test @Test
public void testQuerySubclassAttribute() { public void testQuerySubclassAttribute() {
Session s = openSession(); inTransaction( s -> {
Transaction t = s.beginTransaction(); Person p = new Person();
Person p = new Person(); p.setName( "Emmanuel" );
p.setName("Emmanuel"); p.setSex( 'M' );
p.setSex('M'); s.persist( p );
s.persist(p); Employee q = new Employee();
Employee q = new Employee(); q.setName( "Steve" );
q.setName("Steve"); q.setSex( 'M' );
q.setSex('M'); q.setTitle( "Mr" );
q.setTitle("Mr"); q.setSalary( new BigDecimal( 1000 ) );
q.setSalary( new BigDecimal(1000) ); s.persist( q );
s.persist(q);
List result = s.createQuery("from Person where salary > 100").list(); List result = s.createQuery( "from Person where salary > 100" ).list();
assertEquals( result.size(), 1 ); assertEquals( result.size(), 1 );
assertSame( result.get(0), q ); assertSame( result.get( 0 ), q );
result = s.createQuery("from Person where salary > 100 or name like 'E%'").list(); result = s.createQuery( "from Person where salary > 100 or name like 'E%'" ).list();
assertEquals( result.size(), 2 ); assertEquals( result.size(), 2 );
result = s.createCriteria(Person.class) CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder();
.add( Property.forName("salary").gt( new BigDecimal(100) ) ) CriteriaQuery<Person> criteria = criteriaBuilder.createQuery( Person.class );
.list();
assertEquals( result.size(), 1 );
assertSame( result.get(0), q );
//TODO: make this work: Root<Person> root = criteria.from( Person.class );
criteria.where( criteriaBuilder.gt(root.get( "salary" ), new BigDecimal( 100 ) ));
result = s.createQuery( criteria ).list();
// result = s.createCriteria( Person.class )
// .add( Property.forName( "salary" ).gt( new BigDecimal( 100 ) ) )
// .list();
assertEquals( result.size(), 1 );
assertSame( result.get( 0 ), q );
//TODO: make this work:
/*result = s.createQuery("select salary from Person where salary > 100").list(); /*result = s.createQuery("select salary from Person where salary > 100").list();
assertEquals( result.size(), 1 ); assertEquals( result.size(), 1 );
assertEquals( result.get(0), new BigDecimal(1000) );*/ assertEquals( result.get(0), new BigDecimal(1000) );*/
s.delete(p); s.delete( p );
s.delete(q); s.delete( q );
t.commit(); } );
s.close();
} }
@Test @Test
@ -191,81 +220,100 @@ public class JoinedSubclassTest extends BaseCoreFunctionalTestCase {
final double HEIGHT_INCHES = 73; final double HEIGHT_INCHES = 73;
final double HEIGHT_CENTIMETERS = HEIGHT_INCHES * 2.54d; final double HEIGHT_CENTIMETERS = HEIGHT_INCHES * 2.54d;
Person p = new Person(); Person p = new Person();
p.setName("Emmanuel"); p.setName( "Emmanuel" );
p.setSex('M'); p.setSex( 'M' );
p.setHeightInches(HEIGHT_INCHES); p.setHeightInches( HEIGHT_INCHES );
s.persist(p); s.persist( p );
final double PASSWORD_EXPIRY_WEEKS = 4; final double PASSWORD_EXPIRY_WEEKS = 4;
final double PASSWORD_EXPIRY_DAYS = PASSWORD_EXPIRY_WEEKS * 7d; final double PASSWORD_EXPIRY_DAYS = PASSWORD_EXPIRY_WEEKS * 7d;
Employee e = new Employee(); Employee e = new Employee();
e.setName("Steve"); e.setName( "Steve" );
e.setSex('M'); e.setSex( 'M' );
e.setTitle("Mr"); e.setTitle( "Mr" );
e.setPasswordExpiryDays(PASSWORD_EXPIRY_DAYS); e.setPasswordExpiryDays( PASSWORD_EXPIRY_DAYS );
s.persist(e); s.persist( e );
s.flush(); s.flush();
// Test value conversion during insert // Test value conversion during insert
// Value returned by Oracle native query is a Types.NUMERIC, which is mapped to a BigDecimalType; // Value returned by Oracle native query is a Types.NUMERIC, which is mapped to a BigDecimalType;
// Cast returned value to Number then call Number.doubleValue() so it works on all dialects. // Cast returned value to Number then call Number.doubleValue() so it works on all dialects.
Double heightViaSql = Double heightViaSql =
( (Number)s.createSQLQuery("select height_centimeters from JPerson where name='Emmanuel'").uniqueResult() ) ( (Number) s.createNativeQuery( "select height_centimeters from JPerson where name='Emmanuel'" )
.uniqueResult() )
.doubleValue(); .doubleValue();
assertEquals(HEIGHT_CENTIMETERS, heightViaSql, 0.01d); assertEquals( HEIGHT_CENTIMETERS, heightViaSql, 0.01d );
Double expiryViaSql = Double expiryViaSql =
( (Number)s.createSQLQuery("select pwd_expiry_weeks from JEmployee where person_id=?") ( (Number) s.createNativeQuery( "select pwd_expiry_weeks from JEmployee where person_id=?" )
.setLong(1, e.getId()) .setParameter( 1, e.getId() )
.uniqueResult() .uniqueResult()
).doubleValue(); ).doubleValue();
assertEquals(PASSWORD_EXPIRY_WEEKS, expiryViaSql, 0.01d); assertEquals( PASSWORD_EXPIRY_WEEKS, expiryViaSql, 0.01d );
// Test projection // Test projection
Double heightViaHql = (Double)s.createQuery("select p.heightInches from Person p where p.name = 'Emmanuel'").uniqueResult(); Double heightViaHql = (Double) s.createQuery( "select p.heightInches from Person p where p.name = 'Emmanuel'" )
assertEquals(HEIGHT_INCHES, heightViaHql, 0.01d); .uniqueResult();
Double expiryViaHql = (Double)s.createQuery("select e.passwordExpiryDays from Employee e where e.name = 'Steve'").uniqueResult(); assertEquals( HEIGHT_INCHES, heightViaHql, 0.01d );
assertEquals(PASSWORD_EXPIRY_DAYS, expiryViaHql, 0.01d); Double expiryViaHql = (Double) s.createQuery(
"select e.passwordExpiryDays from Employee e where e.name = 'Steve'" ).uniqueResult();
assertEquals( PASSWORD_EXPIRY_DAYS, expiryViaHql, 0.01d );
// Test restriction and entity load via criteria // Test restriction and entity load via criteria
p = (Person)s.createCriteria(Person.class) // p = (Person)s.createCriteria(Person.class)
.add(Restrictions.between("heightInches", HEIGHT_INCHES - 0.01d, HEIGHT_INCHES + 0.01d)) // .add(Restrictions.between("heightInches", HEIGHT_INCHES - 0.01d, HEIGHT_INCHES + 0.01d))
.uniqueResult(); // .uniqueResult();
assertEquals(HEIGHT_INCHES, p.getHeightInches(), 0.01d); CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder();
e = (Employee)s.createCriteria(Employee.class) CriteriaQuery<Person> criteria = criteriaBuilder.createQuery( Person.class );
.add(Restrictions.between("passwordExpiryDays", PASSWORD_EXPIRY_DAYS - 0.01d, PASSWORD_EXPIRY_DAYS + 0.01d)) Root<Person> root = criteria.from( Person.class );
.uniqueResult(); criteria.where( criteriaBuilder.between( root.get("heightInches"),HEIGHT_INCHES - 0.01d, HEIGHT_INCHES + 0.01d ) ) ;
assertEquals(PASSWORD_EXPIRY_DAYS, e.getPasswordExpiryDays(), 0.01d); p = s.createQuery( criteria).uniqueResult();
assertEquals( HEIGHT_INCHES, p.getHeightInches(), 0.01d );
CriteriaQuery<Employee> employeeCriteriaQuery = criteriaBuilder.createQuery( Employee.class );
Root<Employee> employeeRoot = employeeCriteriaQuery.from( Employee.class );
employeeCriteriaQuery.where( criteriaBuilder.between( employeeRoot.get("passwordExpiryDays"), PASSWORD_EXPIRY_DAYS - 0.01d,
PASSWORD_EXPIRY_DAYS + 0.01d ) );
e = s.createQuery( employeeCriteriaQuery ).uniqueResult();
// e = (Employee) s.createCriteria( Employee.class )
// .add( Restrictions.between(
// "passwordExpiryDays",
// PASSWORD_EXPIRY_DAYS - 0.01d,
// PASSWORD_EXPIRY_DAYS + 0.01d
// ) )
// .uniqueResult();
assertEquals( PASSWORD_EXPIRY_DAYS, e.getPasswordExpiryDays(), 0.01d );
// Test predicate and entity load via HQL // Test predicate and entity load via HQL
p = (Person)s.createQuery("from Person p where p.heightInches between ?1 and ?2") p = (Person) s.createQuery( "from Person p where p.heightInches between ?1 and ?2" )
.setDouble(1, HEIGHT_INCHES - 0.01d) .setParameter( 1, HEIGHT_INCHES - 0.01d )
.setDouble(2, HEIGHT_INCHES + 0.01d) .setParameter( 2, HEIGHT_INCHES + 0.01d )
.uniqueResult(); .uniqueResult();
assertEquals(HEIGHT_INCHES, p.getHeightInches(), 0.01d); assertEquals( HEIGHT_INCHES, p.getHeightInches(), 0.01d );
e = (Employee)s.createQuery("from Employee e where e.passwordExpiryDays between ?1 and ?2") e = (Employee) s.createQuery( "from Employee e where e.passwordExpiryDays between ?1 and ?2" )
.setDouble(1, PASSWORD_EXPIRY_DAYS - 0.01d) .setParameter( 1, PASSWORD_EXPIRY_DAYS - 0.01d )
.setDouble(2, PASSWORD_EXPIRY_DAYS + 0.01d) .setParameter( 2, PASSWORD_EXPIRY_DAYS + 0.01d )
.uniqueResult(); .uniqueResult();
assertEquals(PASSWORD_EXPIRY_DAYS, e.getPasswordExpiryDays(), 0.01d); assertEquals( PASSWORD_EXPIRY_DAYS, e.getPasswordExpiryDays(), 0.01d );
// Test update // Test update
p.setHeightInches(1); p.setHeightInches( 1 );
e.setPasswordExpiryDays(7); e.setPasswordExpiryDays( 7 );
s.flush(); s.flush();
heightViaSql = heightViaSql =
( (Number)s.createSQLQuery("select height_centimeters from JPerson where name='Emmanuel'").uniqueResult() ) ( (Number) s.createNativeQuery( "select height_centimeters from JPerson where name='Emmanuel'" )
.uniqueResult() )
.doubleValue(); .doubleValue();
assertEquals(2.54d, heightViaSql, 0.01d); assertEquals( 2.54d, heightViaSql, 0.01d );
expiryViaSql = expiryViaSql =
( (Number)s.createSQLQuery("select pwd_expiry_weeks from JEmployee where person_id=?") ( (Number) s.createNativeQuery( "select pwd_expiry_weeks from JEmployee where person_id=?" )
.setLong(1, e.getId()) .setParameter( 1, e.getId() )
.uniqueResult() .uniqueResult()
).doubleValue(); ).doubleValue();
assertEquals(1d, expiryViaSql, 0.01d); assertEquals( 1d, expiryViaSql, 0.01d );
s.delete(p); s.delete( p );
s.delete(e); s.delete( e );
t.commit(); t.commit();
s.close(); s.close();
} }
@Test @Test
@ -273,15 +321,15 @@ public class JoinedSubclassTest extends BaseCoreFunctionalTestCase {
Session s = openSession(); Session s = openSession();
Transaction t = s.beginTransaction(); Transaction t = s.beginTransaction();
Person p = new Person(); Person p = new Person();
p.setName("Emmanuel"); p.setName( "Emmanuel" );
p.setSex('M'); p.setSex( 'M' );
s.persist(p); s.persist( p );
Employee q = new Employee(); Employee q = new Employee();
q.setName("Steve"); q.setName( "Steve" );
q.setSex('M'); q.setSex( 'M' );
q.setTitle("Mr"); q.setTitle( "Mr" );
q.setSalary( new BigDecimal(1000) ); q.setSalary( new BigDecimal( 1000 ) );
s.persist(q); s.persist( q );
t.commit(); t.commit();
s.close(); s.close();

View File

@ -7,12 +7,17 @@
package org.hibernate.test.keymanytoone.bidir.embedded; package org.hibernate.test.keymanytoone.bidir.embedded;
import java.util.List; import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Root;
import org.junit.Test; import org.junit.Test;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment; import org.hibernate.cfg.Environment;
import org.hibernate.criterion.Restrictions;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
@ -35,59 +40,55 @@ public class KeyManyToOneTest extends BaseCoreFunctionalTestCase {
@Test @Test
public void testCriteriaRestrictionOnKeyManyToOne() { public void testCriteriaRestrictionOnKeyManyToOne() {
Session s = openSession(); inTransaction( s -> {
s.beginTransaction(); s.createQuery( "from Order o where o.customer.name = 'Acme'" ).list();
s.createQuery( "from Order o where o.customer.name = 'Acme'" ).list(); // Criteria criteria = s.createCriteria( Order.class );
Criteria criteria = s.createCriteria( Order.class ); // criteria.createCriteria( "customer" ).add( Restrictions.eq( "name", "Acme" ) );
criteria.createCriteria( "customer" ).add( Restrictions.eq( "name", "Acme" ) ); // criteria.list();
criteria.list(); CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder();
s.getTransaction().commit(); CriteriaQuery<Order> criteria = criteriaBuilder.createQuery( Order.class );
s.close(); Root<Order> root = criteria.from( Order.class );
Join<Object, Object> customer = root.join( "customer", JoinType.INNER );
criteria.where( criteriaBuilder.equal( customer.get( "name" ), "Acme" ) );
s.createQuery( criteria ).list();
} );
} }
@Test @Test
public void testSaveCascadedToKeyManyToOne() { public void testSaveCascadedToKeyManyToOne() {
// test cascading a save to an association with a key-many-to-one which refers to a // test cascading a save to an association with a key-many-to-one which refers to a
// just saved entity // just saved entity
Session s = openSession(); inTransaction( s -> {
s.beginTransaction(); Customer cust = new Customer( "Acme, Inc." );
Customer cust = new Customer( "Acme, Inc." ); Order order = new Order( cust, 1 );
Order order = new Order( cust, 1 ); cust.getOrders().add( order );
cust.getOrders().add( order ); sessionFactory().getStatistics().clear();
sessionFactory().getStatistics().clear(); s.save( cust );
s.save( cust ); s.flush();
s.flush(); assertEquals( 2, sessionFactory().getStatistics().getEntityInsertCount() );
assertEquals( 2, sessionFactory().getStatistics().getEntityInsertCount() ); s.delete( cust );
s.delete( cust ); } );
s.getTransaction().commit();
s.close();
} }
@Test @Test
public void testQueryingOnMany2One() { public void testQueryingOnMany2One() {
Session s = openSession();
s.beginTransaction();
Customer cust = new Customer( "Acme, Inc." ); Customer cust = new Customer( "Acme, Inc." );
Order order = new Order( cust, 1 ); Order order = new Order( cust, 1 );
cust.getOrders().add( order ); inTransaction( s -> {
s.save( cust ); cust.getOrders().add( order );
s.getTransaction().commit(); s.save( cust );
s.close(); } );
s = openSession(); inTransaction( s -> {
s.beginTransaction(); List results = s.createQuery( "from Order o where o.customer.name = :name" )
List results = s.createQuery( "from Order o where o.customer.name = :name" ) .setParameter( "name", cust.getName() )
.setParameter( "name", cust.getName() ) .list();
.list(); assertEquals( 1, results.size() );
assertEquals( 1, results.size() ); } );
s.getTransaction().commit();
s.close();
s = openSession(); inTransaction( s -> {
s.beginTransaction(); s.delete( cust );
s.delete( cust ); } );
s.getTransaction().commit();
s.close();
} }
@Test @Test