diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/AbstractHqlQueryCacheResultTransformerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/AbstractHqlQueryCacheResultTransformerTest.java new file mode 100644 index 0000000000..57094eaec0 --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/AbstractHqlQueryCacheResultTransformerTest.java @@ -0,0 +1,1688 @@ +package org.hibernate.orm.test.querycache; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.hibernate.CacheMode; +import org.hibernate.Hibernate; +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.hibernate.cfg.Configuration; +import org.hibernate.cfg.Environment; +import org.hibernate.proxy.HibernateProxy; +import org.hibernate.query.Query; +import org.hibernate.transform.ResultTransformer; +import org.hibernate.transform.Transformers; + +import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +public abstract class AbstractHqlQueryCacheResultTransformerTest extends BaseCoreFunctionalTestCase { + private Student yogiExpected; + private Student shermanExpected; + private CourseMeeting courseMeetingExpected1; + private CourseMeeting courseMeetingExpected2; + private Course courseExpected; + private Enrolment yogiEnrolmentExpected; + private Enrolment shermanEnrolmentExpected; + + @Override + public String[] getMappings() { + return new String[] { "querycache/Enrolment.hbm.xml" }; + } + + @Override + protected String getBaseForMappings() { + return "org/hibernate/orm/test/"; + } + + @Override + public void configure(Configuration cfg) { + super.configure( cfg ); + cfg.setProperty( Environment.USE_QUERY_CACHE, "true" ); + cfg.setProperty( Environment.CACHE_REGION_PREFIX, "foo" ); + cfg.setProperty( Environment.USE_SECOND_LEVEL_CACHE, "true" ); + cfg.setProperty( Environment.GENERATE_STATISTICS, "true" ); + } + + protected abstract class HqlExecutor extends QueryExecutor { + protected abstract Query getQuery(Session s); + + @Override + protected Object getResults(Session s, boolean isSingleResult) { + Query query = getQuery( s ).setCacheable( getQueryCacheMode() != CacheMode.IGNORE ).setCacheMode( + getQueryCacheMode() ); + return ( isSingleResult ? query.uniqueResult() : query.list() ); + } + } + + protected abstract class QueryExecutor { + public Object execute(boolean isSingleResult) throws Exception { + Session s = openSession(); + Transaction t = s.beginTransaction(); + Object result; + try { + result = getResults( s, isSingleResult ); + t.commit(); + } + catch (Exception ex) { + t.rollback(); + throw ex; + } + finally { + s.close(); + } + return result; + } + + protected abstract Object getResults(Session s, boolean isSingleResult) throws Exception; + } + + protected interface ResultChecker { + void check(Object results); + } + + protected abstract CacheMode getQueryCacheMode(); + + protected boolean areDynamicNonLazyAssociationsChecked() { + return true; + } + + protected void createData() { + inTransaction( + s -> { + courseExpected = new Course(); + courseExpected.setCourseCode( "HIB" ); + courseExpected.setDescription( "Hibernate Training" ); + courseMeetingExpected1 = new CourseMeeting( courseExpected, "Monday", 1, "1313 Mockingbird Lane" ); + courseMeetingExpected2 = new CourseMeeting( courseExpected, "Tuesday", 2, "1313 Mockingbird Lane" ); + courseExpected.getCourseMeetings().add( courseMeetingExpected1 ); + courseExpected.getCourseMeetings().add( courseMeetingExpected2 ); + s.save( courseExpected ); + + yogiExpected = new Student(); + yogiExpected.setName( new PersonName( "Yogi", "The", "Bear" ) ); + yogiExpected.setStudentNumber( 111 ); + yogiExpected.setPreferredCourse( courseExpected ); + List yogiSecretCodes = new ArrayList(); + yogiSecretCodes.add( 0 ); + yogiExpected.setSecretCodes( yogiSecretCodes ); + s.save( yogiExpected ); + + Address address1 = new Address( + yogiExpected, + "home", + "1 Main Street", + "Podunk", + "WA", + "98000", + "USA" + ); + Address address2 = new Address( + yogiExpected, + "work", + "2 Main Street", + "NotPodunk", + "WA", + "98001", + "USA" + ); + yogiExpected.getAddresses().put( address1.getAddressType(), address1 ); + yogiExpected.getAddresses().put( address2.getAddressType(), address2 ); + s.save( address1 ); + s.save( address2 ); + + shermanExpected = new Student(); + shermanExpected.setName( new PersonName( "Sherman", null, "Grote" ) ); + shermanExpected.setStudentNumber( 999 ); + List shermanSecretCodes = new ArrayList(); + shermanSecretCodes.add( 1 ); + shermanSecretCodes.add( 2 ); + shermanExpected.setSecretCodes( shermanSecretCodes ); + s.save( shermanExpected ); + + shermanEnrolmentExpected = new Enrolment(); + shermanEnrolmentExpected.setCourse( courseExpected ); + shermanEnrolmentExpected.setCourseCode( courseExpected.getCourseCode() ); + shermanEnrolmentExpected.setSemester( (short) 1 ); + shermanEnrolmentExpected.setYear( (short) 1999 ); + shermanEnrolmentExpected.setStudent( shermanExpected ); + shermanEnrolmentExpected.setStudentNumber( shermanExpected.getStudentNumber() ); + shermanExpected.getEnrolments().add( shermanEnrolmentExpected ); + s.save( shermanEnrolmentExpected ); + + yogiEnrolmentExpected = new Enrolment(); + yogiEnrolmentExpected.setCourse( courseExpected ); + yogiEnrolmentExpected.setCourseCode( courseExpected.getCourseCode() ); + yogiEnrolmentExpected.setSemester( (short) 3 ); + yogiEnrolmentExpected.setYear( (short) 1998 ); + yogiEnrolmentExpected.setStudent( yogiExpected ); + yogiEnrolmentExpected.setStudentNumber( yogiExpected.getStudentNumber() ); + yogiExpected.getEnrolments().add( yogiEnrolmentExpected ); + s.save( yogiEnrolmentExpected ); + } + ); + } + + protected void deleteData() { + inTransaction( + s -> { + s.delete( yogiExpected ); + s.delete( shermanExpected ); + s.delete( yogiEnrolmentExpected ); + s.delete( shermanEnrolmentExpected ); + s.delete( courseMeetingExpected1 ); + s.delete( courseMeetingExpected2 ); + s.delete( courseExpected ); + } + ); + } + + @Test + public void testAliasToEntityMapNoProjectionList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "from Student s left join s.enrolments e left join e.course c order by s.studentNumber" ) + .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP ); + } + }; + + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Map yogiMap = (Map) resultList.get( 0 ); + assertEquals( 3, yogiMap.size() ); + Map shermanMap = (Map) resultList.get( 1 ); + assertEquals( 3, shermanMap.size() ); + assertEquals( yogiExpected, yogiMap.get( "s" ) ); + assertEquals( yogiEnrolmentExpected, yogiMap.get( "e" ) ); + assertEquals( courseExpected, yogiMap.get( "c" ) ); + assertEquals( shermanExpected, shermanMap.get( "s" ) ); + assertEquals( shermanEnrolmentExpected, shermanMap.get( "e" ) ); + assertEquals( courseExpected, shermanMap.get( "c" ) ); + assertSame( ( (Map) resultList.get( 0 ) ).get( "c" ), shermanMap.get( "c" ) ); + }; + + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testAliasToEntityMapNoProjectionMultiAndNullList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "from Student s left join s.preferredCourse p left join s.addresses a order by s.studentNumber" ) + .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 3, resultList.size() ); + Map yogiMap1 = (Map) resultList.get( 0 ); + assertEquals( 3, yogiMap1.size() ); + Map yogiMap2 = (Map) resultList.get( 1 ); + assertEquals( 3, yogiMap2.size() ); + Map shermanMap = (Map) resultList.get( 2 ); + assertEquals( 3, shermanMap.size() ); + assertEquals( yogiExpected, yogiMap1.get( "s" ) ); + assertEquals( courseExpected, yogiMap1.get( "p" ) ); + Address yogiAddress1 = (Address) yogiMap1.get( "a" ); + assertEquals( + yogiExpected.getAddresses().get( yogiAddress1.getAddressType() ), + yogiMap1.get( "a" ) + ); + assertEquals( yogiExpected, yogiMap2.get( "s" ) ); + assertEquals( courseExpected, yogiMap2.get( "p" ) ); + Address yogiAddress2 = (Address) yogiMap2.get( "a" ); + assertEquals( + yogiExpected.getAddresses().get( yogiAddress2.getAddressType() ), + yogiMap2.get( "a" ) + ); + assertSame( yogiMap1.get( "s" ), yogiMap2.get( "s" ) ); + assertSame( yogiMap1.get( "p" ), yogiMap2.get( "p" ) ); + assertNotEquals( yogiAddress1.getAddressType(), yogiAddress2.getAddressType() ); + assertEquals( shermanExpected, shermanMap.get( "s" ) ); + assertEquals( shermanExpected.getPreferredCourse(), shermanMap.get( "p" ) ); + assertNull( shermanMap.get( "a" ) ); + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testAliasToEntityMapNoProjectionNullAndNonNullAliasList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "from Student s left join s.addresses a left join s.preferredCourse order by s.studentNumber" ) + .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Map yogiMap1 = (Map) resultList.get( 0 ); + assertEquals( 2, yogiMap1.size() ); + Map yogiMap2 = (Map) resultList.get( 1 ); + assertEquals( 2, yogiMap2.size() ); + assertEquals( yogiExpected, yogiMap1.get( "s" ) ); + Address yogiAddress1 = (Address) yogiMap1.get( "a" ); + assertEquals( + yogiExpected.getAddresses().get( yogiAddress1.getAddressType() ), + yogiMap1.get( "a" ) + ); + assertEquals( yogiExpected, yogiMap2.get( "s" ) ); + Address yogiAddress2 = (Address) yogiMap2.get( "a" ); + assertEquals( + yogiExpected.getAddresses().get( yogiAddress2.getAddressType() ), + yogiMap2.get( "a" ) + ); + assertSame( yogiMap1.get( "s" ), yogiMap2.get( "s" ) ); + assertNotEquals( yogiAddress1.getAddressType(), yogiAddress2.getAddressType() ); + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testEntityWithNonLazyOneToManyUnique() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( "from Course" ); + } + }; + ResultChecker checker = results -> { + assertTrue( results instanceof Course ); + assertEquals( courseExpected, results ); + assertTrue( Hibernate.isInitialized( courseExpected.getCourseMeetings() ) ); + assertEquals( courseExpected.getCourseMeetings(), courseExpected.getCourseMeetings() ); + }; + runTest( hqlExecutor, checker, true ); + } + + @Test + public void testEntityWithNonLazyManyToOneList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + protected Query getQuery(Session s) { + return s.createQuery( "from CourseMeeting order by id.day" ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + assertEquals( courseMeetingExpected1, resultList.get( 0 ) ); + assertEquals( courseMeetingExpected2, resultList.get( 1 ) ); + assertTrue( Hibernate.isInitialized( ( (CourseMeeting) resultList.get( 0 ) ).getCourse() ) ); + assertTrue( Hibernate.isInitialized( ( (CourseMeeting) resultList.get( 1 ) ).getCourse() ) ); + assertEquals( courseExpected, ( (CourseMeeting) resultList.get( 0 ) ).getCourse() ); + assertEquals( courseExpected, ( (CourseMeeting) resultList.get( 1 ) ).getCourse() ); + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testEntityWithLazyAssnUnique() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( "from Student s where s.studentNumber = :studentNumber" ) + .setParameter( "studentNumber", shermanExpected.getStudentNumber() ); + } + }; + + ResultChecker checker = results -> { + assertTrue( results instanceof Student ); + assertEquals( shermanExpected, results ); + assertNotNull( ( (Student) results ).getEnrolments() ); + assertFalse( Hibernate.isInitialized( ( (Student) results ).getEnrolments() ) ); + assertNull( ( (Student) results ).getPreferredCourse() ); + }; + + runTest( hqlExecutor, checker, true ); + } + + @Test + public void testEntityWithLazyAssnList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( "from Student order by studentNumber" ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + assertEquals( yogiExpected, resultList.get( 0 ) ); + assertEquals( shermanExpected, resultList.get( 1 ) ); + assertNotNull( ( (Student) resultList.get( 0 ) ).getEnrolments() ); + assertNotNull( ( (Student) resultList.get( 0 ) ).getPreferredCourse() ); + assertNotNull( ( (Student) resultList.get( 1 ) ).getEnrolments() ); + assertNull( ( (Student) resultList.get( 1 ) ).getPreferredCourse() ); + assertFalse( Hibernate.isInitialized( ( (Student) resultList.get( 0 ) ).getEnrolments() ) ); + assertFalse( Hibernate.isInitialized( ( (Student) resultList.get( 0 ) ).getPreferredCourse() ) ); + assertFalse( Hibernate.isInitialized( ( (Student) resultList.get( 1 ) ).getEnrolments() ) ); + assertNull( ( (Student) resultList.get( 1 ) ).getPreferredCourse() ); + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testEntityWithUnaliasedJoinFetchedLazyOneToManySingleElementList() throws Exception { + HqlExecutor hqlExecutorUnaliased = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( "from Student s left join fetch s.enrolments order by s.studentNumber" ); + } + }; + + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + assertEquals( yogiExpected, resultList.get( 0 ) ); + assertEquals( shermanExpected, resultList.get( 1 ) ); + assertNotNull( ( (Student) resultList.get( 0 ) ).getEnrolments() ); + assertNotNull( ( (Student) resultList.get( 1 ) ).getEnrolments() ); + if ( areDynamicNonLazyAssociationsChecked() ) { + assertTrue( Hibernate.isInitialized( ( (Student) resultList.get( 0 ) ).getEnrolments() ) ); + assertEquals( yogiExpected.getEnrolments(), ( (Student) resultList.get( 0 ) ).getEnrolments() ); + assertTrue( Hibernate.isInitialized( ( (Student) resultList.get( 1 ) ).getEnrolments() ) ); + assertEquals( shermanExpected.getEnrolments(), ( (Student) resultList.get( 1 ) ).getEnrolments() ); + } + }; + + runTest( hqlExecutorUnaliased, checker, false ); + } + + @Test + public void testJoinWithFetchJoinListHql() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "select s, s.preferredCourse from Student s left join fetch s.enrolments left join s.preferredCourse order by s.studentNumber" + ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Object[] yogiObjects = (Object[]) resultList.get( 0 ); + assertEquals( yogiExpected, yogiObjects[0] ); + assertEquals( yogiExpected.getPreferredCourse(), yogiObjects[1] ); + Object[] shermanObjects = (Object[]) resultList.get( 1 ); + assertEquals( shermanExpected, shermanObjects[0] ); + assertNull( shermanObjects[1] ); + assertNull( ( (Student) shermanObjects[0] ).getPreferredCourse() ); + if ( areDynamicNonLazyAssociationsChecked() ) { + assertTrue( Hibernate.isInitialized( ( (Student) yogiObjects[0] ).getEnrolments() ) ); + assertEquals( yogiExpected.getEnrolments(), ( (Student) yogiObjects[0] ).getEnrolments() ); + assertTrue( Hibernate.isInitialized( ( (Student) shermanObjects[0] ).getEnrolments() ) ); + assertEquals( shermanExpected.getEnrolments(), ( ( (Student) shermanObjects[0] ).getEnrolments() ) ); + } + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testJoinWithFetchJoinWithOwnerAndPropProjectedList() throws Exception { + HqlExecutor hqlSelectNewMapExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "select s, s.name from Student s left join fetch s.enrolments left join s.preferredCourse order by s.studentNumber" ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Object[] yogiObjects = (Object[]) resultList.get( 0 ); + assertEquals( yogiExpected, yogiObjects[0] ); + assertEquals( yogiExpected.getName(), yogiObjects[1] ); + Object[] shermanObjects = (Object[]) resultList.get( 1 ); + assertEquals( shermanExpected, shermanObjects[0] ); + assertEquals( shermanExpected.getName(), shermanObjects[1] ); + if ( areDynamicNonLazyAssociationsChecked() ) { + assertTrue( Hibernate.isInitialized( ( (Student) yogiObjects[0] ).getEnrolments() ) ); + assertEquals( yogiExpected.getEnrolments(), ( (Student) yogiObjects[0] ).getEnrolments() ); + assertTrue( Hibernate.isInitialized( ( (Student) shermanObjects[0] ).getEnrolments() ) ); + assertEquals( shermanExpected.getEnrolments(), ( ( (Student) shermanObjects[0] ).getEnrolments() ) ); + } + }; + runTest( hqlSelectNewMapExecutor, checker, false ); + } + + @Test + public void testJoinWithFetchJoinWithPropAndOwnerProjectedList() throws Exception { + HqlExecutor hqlSelectNewMapExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "select s.name, s from Student s left join fetch s.enrolments left join s.preferredCourse order by s.studentNumber" ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Object[] yogiObjects = (Object[]) resultList.get( 0 ); + assertEquals( yogiExpected.getName(), yogiObjects[0] ); + assertEquals( yogiExpected, yogiObjects[1] ); + Object[] shermanObjects = (Object[]) resultList.get( 1 ); + assertEquals( shermanExpected.getName(), shermanObjects[0] ); + assertEquals( shermanExpected, shermanObjects[1] ); + if ( areDynamicNonLazyAssociationsChecked() ) { + assertTrue( Hibernate.isInitialized( ( (Student) yogiObjects[1] ).getEnrolments() ) ); + assertEquals( yogiExpected.getEnrolments(), ( (Student) yogiObjects[1] ).getEnrolments() ); + assertTrue( Hibernate.isInitialized( ( (Student) shermanObjects[1] ).getEnrolments() ) ); + assertEquals( shermanExpected.getEnrolments(), ( ( (Student) shermanObjects[1] ).getEnrolments() ) ); + } + }; + runTest( hqlSelectNewMapExecutor, checker, false ); + } + + @Test + public void testJoinWithFetchJoinWithOwnerAndAliasedJoinedProjectedListHql() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "select s, pc from Student s left join fetch s.enrolments left join s.preferredCourse pc order by s.studentNumber" ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Object[] yogiObjects = (Object[]) resultList.get( 0 ); + assertEquals( yogiExpected, yogiObjects[0] ); + assertEquals( + yogiExpected.getPreferredCourse().getCourseCode(), + ( (Course) yogiObjects[1] ).getCourseCode() + ); + Object[] shermanObjects = (Object[]) resultList.get( 1 ); + assertEquals( shermanExpected, shermanObjects[0] ); + assertNull( shermanObjects[1] ); + if ( areDynamicNonLazyAssociationsChecked() ) { + assertEquals( yogiExpected.getPreferredCourse(), yogiObjects[1] ); + assertTrue( Hibernate.isInitialized( ( (Student) yogiObjects[0] ).getEnrolments() ) ); + assertEquals( yogiExpected.getEnrolments(), ( (Student) yogiObjects[0] ).getEnrolments() ); + assertTrue( Hibernate.isInitialized( ( (Student) shermanObjects[0] ).getEnrolments() ) ); + assertEquals( shermanExpected.getEnrolments(), ( ( (Student) shermanObjects[0] ).getEnrolments() ) ); + } + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testJoinWithFetchJoinWithAliasedJoinedAndOwnerProjectedListHql() throws Exception { + HqlExecutor hqlSelectNewMapExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "select pc, s from Student s left join fetch s.enrolments left join s.preferredCourse pc order by s.studentNumber" + ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Object[] yogiObjects = (Object[]) resultList.get( 0 ); + assertEquals( yogiExpected, yogiObjects[1] ); + assertEquals( + yogiExpected.getPreferredCourse().getCourseCode(), + ( (Course) yogiObjects[0] ).getCourseCode() + ); + Object[] shermanObjects = (Object[]) resultList.get( 1 ); + assertEquals( shermanExpected, shermanObjects[1] ); + assertNull( shermanObjects[0] ); + if ( areDynamicNonLazyAssociationsChecked() ) { + assertEquals( yogiExpected.getPreferredCourse(), yogiObjects[0] ); + assertTrue( Hibernate.isInitialized( ( (Student) yogiObjects[1] ).getEnrolments() ) ); + assertEquals( yogiExpected.getEnrolments(), ( (Student) yogiObjects[1] ).getEnrolments() ); + assertTrue( Hibernate.isInitialized( ( (Student) shermanObjects[1] ).getEnrolments() ) ); + assertEquals( shermanExpected.getEnrolments(), ( ( (Student) shermanObjects[1] ).getEnrolments() ) ); + } + }; + runTest( hqlSelectNewMapExecutor, checker, false ); + } + + @Test + public void testEntityWithAliasedJoinFetchedLazyOneToManySingleElementListHql() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( "from Student s left join fetch s.enrolments e order by s.studentNumber" ); + } + }; + + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + assertEquals( yogiExpected, resultList.get( 0 ) ); + assertEquals( + yogiExpected.getPreferredCourse().getCourseCode(), + ( (Student) resultList.get( 0 ) ).getPreferredCourse().getCourseCode() + ); + assertEquals( shermanExpected, resultList.get( 1 ) ); + assertNull( ( (Student) resultList.get( 1 ) ).getPreferredCourse() ); + if ( areDynamicNonLazyAssociationsChecked() ) { + assertTrue( Hibernate.isInitialized( ( (Student) resultList.get( 0 ) ).getEnrolments() ) ); + assertEquals( yogiExpected.getEnrolments(), ( (Student) resultList.get( 0 ) ).getEnrolments() ); + assertTrue( Hibernate.isInitialized( ( (Student) resultList.get( 1 ) ).getEnrolments() ) ); + assertEquals( shermanExpected.getEnrolments(), ( ( (Student) resultList.get( 1 ) ).getEnrolments() ) ); + } + }; + + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testEntityWithJoinFetchedLazyOneToManyMultiAndNullElementList() throws Exception { + HqlExecutor hqlExecutorUnaliased = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( "from Student s left join fetch s.addresses order by s.studentNumber" ); + } + }; + + HqlExecutor hqlExecutorAliased = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( "from Student s left join fetch s.addresses a order by s.studentNumber" ); + } + }; + + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + assertEquals( yogiExpected, resultList.get( 0 ) ); +// assertSame( resultList.get( 0 ), resultList.get( 1 ) ); + assertEquals( shermanExpected, resultList.get( 1 ) ); + assertNotNull( ( (Student) resultList.get( 0 ) ).getAddresses() ); +// assertNotNull( ( (Student) resultList.get( 1 ) ).getAddresses() ); + assertNotNull( ( (Student) resultList.get( 1 ) ).getAddresses() ); + if ( areDynamicNonLazyAssociationsChecked() ) { + assertTrue( Hibernate.isInitialized( ( (Student) resultList.get( 0 ) ).getAddresses() ) ); + assertEquals( yogiExpected.getAddresses(), ( (Student) resultList.get( 0 ) ).getAddresses() ); + assertTrue( ( (Student) resultList.get( 1 ) ).getAddresses().isEmpty() ); + } + }; + runTest( hqlExecutorUnaliased, checker, false ); + runTest( hqlExecutorAliased, checker, false ); + } + + @Test + public void testEntityWithJoinFetchedLazyManyToOneList() throws Exception { + HqlExecutor hqlExecutorUnaliased = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( "from Student s left join fetch s.preferredCourse order by s.studentNumber" ); + } + }; + + HqlExecutor hqlExecutorAliased = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "from Student s left join fetch s.preferredCourse pCourse order by s.studentNumber" ); + } + }; + + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + assertEquals( yogiExpected, resultList.get( 0 ) ); + assertEquals( shermanExpected, resultList.get( 1 ) ); + assertEquals( + yogiExpected.getPreferredCourse().getCourseCode(), + ( (Student) resultList.get( 0 ) ).getPreferredCourse().getCourseCode() + ); + assertNull( ( (Student) resultList.get( 1 ) ).getPreferredCourse() ); + }; + runTest( hqlExecutorUnaliased, checker, false ); + runTest( hqlExecutorAliased, checker, false ); + } + + @Test + public void testEntityWithJoinFetchedLazyManyToOneUsingProjectionList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "select s.name, s from Enrolment e left join e.student s left join fetch s.preferredCourse order by s.studentNumber" + ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Object[] yogiObjects = (Object[]) resultList.get( 0 ); + Object[] shermanObjects = (Object[]) resultList.get( 1 ); + assertEquals( yogiExpected.getName(), yogiObjects[0] ); + assertEquals( shermanExpected.getName(), shermanObjects[0] ); + // The following fails for criteria due to HHH-1425 + // assertEquals( yogiExpected, yogiObjects[ 1 ] ); + // assertEquals( shermanExpected, shermanObjects[ 1 ] ); + assertEquals( yogiExpected.getStudentNumber(), ( (Student) yogiObjects[1] ).getStudentNumber() ); + assertEquals( shermanExpected.getStudentNumber(), ( (Student) shermanObjects[1] ).getStudentNumber() ); + if ( areDynamicNonLazyAssociationsChecked() ) { + // The following fails for criteria due to HHH-1425 + //assertTrue( Hibernate.isInitialized( ( ( Student ) yogiObjects[ 1 ] ).getPreferredCourse() ) ); + //assertEquals( yogiExpected.getPreferredCourse(), ( ( Student ) yogiObjects[ 1 ] ).getPreferredCourse() ); + //assertTrue( Hibernate.isInitialized( ( ( Student ) shermanObjects[ 1 ] ).getPreferredCourse() ) ); + //assertEquals( shermanExpected.getPreferredCourse(), ( ( Student ) shermanObjects[ 1 ] ).getPreferredCourse() ); + } + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testEntityWithJoinedLazyOneToManySingleElementListHql() throws Exception { + HqlExecutor hqlExecutorUnaliased = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( "select s, s.enrolments from Student s left join s.enrolments order by s.studentNumber" ); + } + }; + HqlExecutor hqlExecutorAliased = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( "select s, e from Student s left join s.enrolments e order by s.studentNumber" ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + assertTrue( resultList.get( 0 ) instanceof Object[] ); + Object[] yogiObjects = (Object[]) resultList.get( 0 ); + assertEquals( yogiExpected, yogiObjects[0] ); + assertEquals( yogiEnrolmentExpected, yogiObjects[1] ); + assertTrue( resultList.get( 0 ) instanceof Object[] ); + Object[] shermanObjects = (Object[]) resultList.get( 1 ); + assertEquals( shermanExpected, shermanObjects[0] ); + assertEquals( shermanEnrolmentExpected, shermanObjects[1] ); + }; + runTest( hqlExecutorUnaliased, checker, false ); + runTest( hqlExecutorAliased, checker, false ); + } + + @Test + public void testEntityWithJoinedLazyOneToManyMultiAndNullListHql() throws Exception { + HqlExecutor hqlExecutorUnaliased = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( "from Student s left join s.addresses order by s.studentNumber" ); + } + }; + HqlExecutor hqlExecutorAliased = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( "from Student s left join s.addresses a order by s.studentNumber" ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); +// assertTrue( resultList.get( 0 ) instanceof Object[] ); + Student yogiObjects1 = (Student) resultList.get( 0 ); + assertEquals( yogiExpected, yogiObjects1 ); + assertFalse(Hibernate.isInitialized( yogiObjects1.getAddresses() ) ); +// Address address1 = (Address) yogiObjects1.getAddresses().get( 0 ); +// assertEquals( yogiExpected.getAddresses().get( address1.getAddressType() ), address1 ); +// Object[] yogiObjects2 = (Object[]) resultList.get( 1 ); +// assertSame( yogiObjects1[0], yogiObjects2[0] ); +// Address address2 = (Address) yogiObjects2[1]; +// assertEquals( yogiExpected.getAddresses().get( address2.getAddressType() ), address2 ); +// assertNotEquals( address1.getAddressType(), address2.getAddressType() ); + Student shermanObjects = (Student) resultList.get( 1 ); + assertEquals( shermanExpected, shermanObjects ); + }; + runTest( hqlExecutorUnaliased, checker, false ); + runTest( hqlExecutorAliased, checker, false ); + } + + @Test + public void testEntityWithJoinedLazyManyToOneListHql() throws Exception { + HqlExecutor hqlExecutorUnaliased = new HqlExecutor() { + @Override + protected Query getQuery(Session s) { + return s.createQuery( + "select s, s.preferredCourse from Student s left join s.preferredCourse order by s.studentNumber" ); + } + }; + HqlExecutor hqlExecutorAliased = new HqlExecutor() { + @Override + protected Query getQuery(Session s) { + return s.createQuery( + "select s, p from Student s left join s.preferredCourse p order by s.studentNumber" ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Object[] yogiObjects = (Object[]) resultList.get( 0 ); + assertEquals( yogiExpected, yogiObjects[0] ); + assertEquals( yogiExpected.getPreferredCourse(), yogiObjects[1] ); + Object[] shermanObjects = (Object[]) resultList.get( 1 ); + assertEquals( shermanExpected, shermanObjects[0] ); + assertNull( shermanObjects[1] ); + }; + runTest( hqlExecutorUnaliased, checker, false ); + runTest( hqlExecutorAliased, checker, false ); + } + + @Test + public void testAliasToEntityMapOneProjectionList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( "select e.student as student from Enrolment e order by e.studentNumber" ) + .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Map yogiMap = (Map) resultList.get( 0 ); + Map shermanMap = (Map) resultList.get( 1 ); + assertEquals( 1, yogiMap.size() ); + assertEquals( 1, shermanMap.size() ); + // TODO: following are initialized for hql and uninitialied for criteria; why? + // assertFalse( Hibernate.isInitialized( yogiMap.get( "student" ) ) ); + // assertFalse( Hibernate.isInitialized( shermanMap.get( "student" ) ) ); + assertTrue( yogiMap.get( "student" ) instanceof Student ); + assertTrue( shermanMap.get( "student" ) instanceof Student ); + assertEquals( yogiExpected.getStudentNumber(), ( (Student) yogiMap.get( "student" ) ).getStudentNumber() ); + assertEquals( + shermanExpected.getStudentNumber(), + ( (Student) shermanMap.get( "student" ) ).getStudentNumber() + ); + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testAliasToEntityMapMultiProjectionList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "select e.student as student, e.semester as semester, e.year as year, e.course as course from Enrolment e order by e.studentNumber" ) + .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Map yogiMap = (Map) resultList.get( 0 ); + Map shermanMap = (Map) resultList.get( 1 ); + assertEquals( 4, yogiMap.size() ); + assertEquals( 4, shermanMap.size() ); + assertTrue( yogiMap.get( "student" ) instanceof Student ); + assertTrue( shermanMap.get( "student" ) instanceof Student ); + // TODO: following are initialized for hql and uninitialied for criteria; why? + // assertFalse( Hibernate.isInitialized( yogiMap.get( "student" ) ) ); + // assertFalse( Hibernate.isInitialized( shermanMap.get( "student" ) ) ); + assertEquals( yogiExpected.getStudentNumber(), ( (Student) yogiMap.get( "student" ) ).getStudentNumber() ); + assertEquals( + shermanExpected.getStudentNumber(), + ( (Student) shermanMap.get( "student" ) ).getStudentNumber() + ); + assertEquals( yogiEnrolmentExpected.getSemester(), yogiMap.get( "semester" ) ); + assertEquals( yogiEnrolmentExpected.getYear(), yogiMap.get( "year" ) ); + assertEquals( courseExpected, yogiMap.get( "course" ) ); + assertEquals( shermanEnrolmentExpected.getSemester(), shermanMap.get( "semester" ) ); + assertEquals( shermanEnrolmentExpected.getYear(), shermanMap.get( "year" ) ); + assertEquals( courseExpected, shermanMap.get( "course" ) ); + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testAliasToEntityMapMultiProjectionWithNullAliasList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "select e.student as student, e.semester, e.year, e.course as course from Enrolment e order by e.studentNumber" ) + .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Map yogiMap = (Map) resultList.get( 0 ); + Map shermanMap = (Map) resultList.get( 1 ); + // TODO: following are initialized for hql and uninitialied for criteria; why? + // assertFalse( Hibernate.isInitialized( yogiMap.get( "student" ) ) ); + // assertFalse( Hibernate.isInitialized( shermanMap.get( "student" ) ) ); + assertTrue( yogiMap.get( "student" ) instanceof Student ); + assertEquals( yogiExpected.getStudentNumber(), ( (Student) yogiMap.get( "student" ) ).getStudentNumber() ); + assertEquals( + shermanExpected.getStudentNumber(), + ( (Student) shermanMap.get( "student" ) ).getStudentNumber() + ); + assertNull( yogiMap.get( "semester" ) ); + assertNull( yogiMap.get( "year" ) ); + assertEquals( courseExpected, yogiMap.get( "course" ) ); + assertNull( shermanMap.get( "semester" ) ); + assertNull( shermanMap.get( "year" ) ); + assertEquals( courseExpected, shermanMap.get( "course" ) ); + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testAliasToEntityMapMultiAggregatedPropProjectionSingleResult() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "select min( e.studentNumber ) as minStudentNumber, max( e.studentNumber ) as maxStudentNumber from Enrolment e" ) + .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP ); + } + }; + ResultChecker checker = results -> { + assertTrue( results instanceof Map ); + Map resultMap = (Map) results; + assertEquals( 2, resultMap.size() ); + assertEquals( yogiExpected.getStudentNumber(), resultMap.get( "minStudentNumber" ) ); + assertEquals( shermanExpected.getStudentNumber(), resultMap.get( "maxStudentNumber" ) ); + }; + runTest( hqlExecutor, checker, true ); + } + + @Test + public void testOneNonEntityProjectionUnique() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( "select e.semester from Enrolment e where e.studentNumber = :studentNumber" ) + .setParameter( "studentNumber", shermanEnrolmentExpected.getStudentNumber() ); + } + }; + ResultChecker checker = results -> { + assertTrue( results instanceof Short ); + assertEquals( shermanEnrolmentExpected.getSemester(), results ); + }; + runTest( hqlExecutor, checker, true ); + } + + @Test + public void testOneNonEntityProjectionList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( "select e.semester from Enrolment e order by e.studentNumber" ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + assertEquals( yogiEnrolmentExpected.getSemester(), resultList.get( 0 ) ); + assertEquals( shermanEnrolmentExpected.getSemester(), resultList.get( 1 ) ); + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testListElementsProjectionList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( "select elements(s.secretCodes) from Student s" ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 3, resultList.size() ); + assertTrue( resultList.contains( yogiExpected.getSecretCodes().get( 0 ) ) ); + assertTrue( resultList.contains( shermanExpected.getSecretCodes().get( 0 ) ) ); + assertTrue( resultList.contains( shermanExpected.getSecretCodes().get( 1 ) ) ); + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testOneEntityProjectionUnique() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( "select e.student from Enrolment e where e.studentNumber = :studentNumber" ) + .setParameter( "studentNumber", Long.valueOf( yogiExpected.getStudentNumber() ) ); + } + }; + ResultChecker checker = results -> { + assertTrue( results instanceof Student ); + Student student = (Student) results; + // TODO: following is initialized for hql and uninitialied for criteria; why? + //assertFalse( Hibernate.isInitialized( student ) ); + assertEquals( yogiExpected.getStudentNumber(), student.getStudentNumber() ); + }; + runTest( hqlExecutor, checker, true ); + } + + @Test + public void testOneEntityProjectionList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( "select e.student from Enrolment e order by e.studentNumber" ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + // TODO: following is initialized for hql and uninitialied for criteria; why? + //assertFalse( Hibernate.isInitialized( resultList.get( 0 ) ) ); + //assertFalse( Hibernate.isInitialized( resultList.get( 1 ) ) ); + assertEquals( yogiExpected.getStudentNumber(), ( (Student) resultList.get( 0 ) ).getStudentNumber() ); + assertEquals( shermanExpected.getStudentNumber(), ( (Student) resultList.get( 1 ) ).getStudentNumber() ); + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testMultiEntityProjectionUnique() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "select e.student, e.semester, e.year, e.course from Enrolment e where e.studentNumber = :studentNumber" ) + .setParameter( "studentNumber", shermanEnrolmentExpected.getStudentNumber() ); + } + }; + ResultChecker checker = results -> { + assertTrue( results instanceof Object[] ); + Object shermanObjects[] = (Object[]) results; + assertEquals( 4, shermanObjects.length ); + assertNotNull( shermanObjects[0] ); + assertTrue( shermanObjects[0] instanceof Student ); + // TODO: following is initialized for hql and uninitialied for criteria; why? + //assertFalse( Hibernate.isInitialized( shermanObjects[ 0 ] ) ); + assertEquals( shermanEnrolmentExpected.getSemester(), ( (Short) shermanObjects[1] ).shortValue() ); + assertEquals( shermanEnrolmentExpected.getYear(), ( (Short) shermanObjects[2] ).shortValue() ); + assertFalse( shermanObjects[3] instanceof HibernateProxy ); + assertTrue( shermanObjects[3] instanceof Course ); + assertEquals( courseExpected, shermanObjects[3] ); + }; + runTest( hqlExecutor, checker, true ); + } + + @Test + public void testMultiEntityProjectionList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "select e.student, e.semester, e.year, e.course from Enrolment e order by e.studentNumber" ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Object[] yogiObjects = (Object[]) resultList.get( 0 ); + Object[] shermanObjects = (Object[]) resultList.get( 1 ); + assertEquals( 4, yogiObjects.length ); + // TODO: following is initialized for hql and uninitialied for criteria; why? + //assertFalse( Hibernate.isInitialized( yogiObjects[ 0 ] ) ); + //assertFalse( Hibernate.isInitialized( shermanObjects[ 0 ] ) ); + assertTrue( yogiObjects[0] instanceof Student ); + assertTrue( shermanObjects[0] instanceof Student ); + assertEquals( yogiEnrolmentExpected.getSemester(), ( (Short) yogiObjects[1] ).shortValue() ); + assertEquals( yogiEnrolmentExpected.getYear(), ( (Short) yogiObjects[2] ).shortValue() ); + assertEquals( courseExpected, yogiObjects[3] ); + assertEquals( shermanEnrolmentExpected.getSemester(), ( (Short) shermanObjects[1] ).shortValue() ); + assertEquals( shermanEnrolmentExpected.getYear(), ( (Short) shermanObjects[2] ).shortValue() ); + assertTrue( shermanObjects[3] instanceof Course ); + assertEquals( courseExpected, shermanObjects[3] ); + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testMultiEntityProjectionAliasedList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "select e.student as st, e.semester as sem, e.year as yr, e.course as c from Enrolment e order by e.studentNumber" ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Object[] yogiObjects = (Object[]) resultList.get( 0 ); + Object[] shermanObjects = (Object[]) resultList.get( 1 ); + assertEquals( 4, yogiObjects.length ); + // TODO: following is initialized for hql and uninitialied for criteria; why? + //assertFalse( Hibernate.isInitialized( yogiObjects[ 0 ] ) ); + //assertFalse( Hibernate.isInitialized( shermanObjects[ 0 ] ) ); + assertTrue( yogiObjects[0] instanceof Student ); + assertTrue( shermanObjects[0] instanceof Student ); + assertEquals( yogiEnrolmentExpected.getSemester(), ( (Short) yogiObjects[1] ).shortValue() ); + assertEquals( yogiEnrolmentExpected.getYear(), ( (Short) yogiObjects[2] ).shortValue() ); + assertEquals( courseExpected, yogiObjects[3] ); + assertEquals( shermanEnrolmentExpected.getSemester(), ( (Short) shermanObjects[1] ).shortValue() ); + assertEquals( shermanEnrolmentExpected.getYear(), ( (Short) shermanObjects[2] ).shortValue() ); + assertTrue( shermanObjects[3] instanceof Course ); + assertEquals( courseExpected, shermanObjects[3] ); + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testSingleAggregatedPropProjectionSingleResult() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( "select min( e.studentNumber ) from Enrolment e" ); + } + }; + ResultChecker checker = results -> { + assertTrue( results instanceof Long ); + assertEquals( yogiExpected.getStudentNumber(), results ); + }; + runTest( hqlExecutor, checker, true ); + } + + @Test + public void testMultiAggregatedPropProjectionSingleResult() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "select min( e.studentNumber ) as minStudentNumber, max( e.studentNumber ) as maxStudentNumber from Enrolment e" ); + } + }; + ResultChecker checker = results -> { + assertTrue( results instanceof Object[] ); + Object[] resultObjects = (Object[]) results; + assertEquals( yogiExpected.getStudentNumber(), resultObjects[0] ); + assertEquals( shermanExpected.getStudentNumber(), resultObjects[1] ); + }; + runTest( hqlExecutor, checker, true ); + } + + @Test + public void testAliasToBeanDtoOneArgList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( "select st.name as studentName from Student st order by st.studentNumber" ) + .setResultTransformer( Transformers.aliasToBean( StudentDTO.class ) ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + StudentDTO dto = (StudentDTO) resultList.get( 0 ); + assertNull( dto.getDescription() ); + assertEquals( yogiExpected.getName(), dto.getName() ); + dto = (StudentDTO) resultList.get( 1 ); + assertNull( dto.getDescription() ); + assertEquals( shermanExpected.getName(), dto.getName() ); + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testAliasToBeanDtoMultiArgList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "select st.name as studentName, co.description as courseDescription from Enrolment e join e.student st join e.course co order by e.studentNumber" ) + .setResultTransformer( Transformers.aliasToBean( StudentDTO.class ) ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + StudentDTO dto = (StudentDTO) resultList.get( 0 ); + assertEquals( courseExpected.getDescription(), dto.getDescription() ); + assertEquals( yogiExpected.getName(), dto.getName() ); + dto = (StudentDTO) resultList.get( 1 ); + assertEquals( courseExpected.getDescription(), dto.getDescription() ); + assertEquals( shermanExpected.getName(), dto.getName() ); + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testMultiProjectionListThenApplyAliasToBean() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "select st.name as studentName, co.description as courseDescription from Enrolment e join e.student st join e.course co order by e.studentNumber" ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + ResultTransformer transformer = Transformers.aliasToBean( StudentDTO.class ); + String[] aliases = new String[] { "studentName", "courseDescription" }; + for ( int i = 0; i < resultList.size(); i++ ) { + resultList.set( + i, + transformer.transformTuple( (Object[]) resultList.get( i ), aliases ) + ); + } + + assertEquals( 2, resultList.size() ); + StudentDTO dto = (StudentDTO) resultList.get( 0 ); + assertEquals( courseExpected.getDescription(), dto.getDescription() ); + assertEquals( yogiExpected.getName(), dto.getName() ); + dto = (StudentDTO) resultList.get( 1 ); + assertEquals( courseExpected.getDescription(), dto.getDescription() ); + assertEquals( shermanExpected.getName(), dto.getName() ); + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testAliasToBeanDtoLiteralArgList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "select st.name as studentName, 'lame description' as courseDescription from Enrolment e join e.student st join e.course co order by e.studentNumber" ) + .setResultTransformer( Transformers.aliasToBean( StudentDTO.class ) ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + StudentDTO dto = (StudentDTO) resultList.get( 0 ); + assertEquals( "lame description", dto.getDescription() ); + assertEquals( yogiExpected.getName(), dto.getName() ); + dto = (StudentDTO) resultList.get( 1 ); + assertEquals( "lame description", dto.getDescription() ); + assertEquals( shermanExpected.getName(), dto.getName() ); + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testAliasToBeanDtoWithNullAliasList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "select st.name as studentName, co.description as courseDescription from Enrolment e join e.student st join e.course co order by e.studentNumber" ) + .setResultTransformer( Transformers.aliasToBean( StudentDTO.class ) ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + StudentDTO dto = (StudentDTO) resultList.get( 0 ); + assertEquals( courseExpected.getDescription(), dto.getDescription() ); + assertEquals( yogiExpected.getName(), dto.getName() ); + dto = (StudentDTO) resultList.get( 1 ); + assertEquals( courseExpected.getDescription(), dto.getDescription() ); + assertEquals( shermanExpected.getName(), dto.getName() ); + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testOneSelectNewNoAliasesList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "select new org.hibernate.orm.test.querycache.StudentDTO(s.name) from Student s order by s.studentNumber" ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + StudentDTO yogi = (StudentDTO) resultList.get( 0 ); + assertNull( yogi.getDescription() ); + assertEquals( yogiExpected.getName(), yogi.getName() ); + StudentDTO sherman = (StudentDTO) resultList.get( 1 ); + assertEquals( shermanExpected.getName(), sherman.getName() ); + assertNull( sherman.getDescription() ); + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testOneSelectNewAliasesList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "select new org.hibernate.orm.test.querycache.StudentDTO(s.name) from Student s order by s.studentNumber" ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + StudentDTO yogi = (StudentDTO) resultList.get( 0 ); + assertNull( yogi.getDescription() ); + assertEquals( yogiExpected.getName(), yogi.getName() ); + StudentDTO sherman = (StudentDTO) resultList.get( 1 ); + assertEquals( shermanExpected.getName(), sherman.getName() ); + assertNull( sherman.getDescription() ); + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testMultiSelectNewList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "select new Student(s.studentNumber, s.name) from Student s order by s.studentNumber" ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Student yogi = (Student) resultList.get( 0 ); + assertEquals( yogiExpected.getStudentNumber(), yogi.getStudentNumber() ); + assertEquals( yogiExpected.getName(), yogi.getName() ); + Student sherman = (Student) resultList.get( 1 ); + assertEquals( shermanExpected.getStudentNumber(), sherman.getStudentNumber() ); + assertEquals( shermanExpected.getName(), sherman.getName() ); + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testMultiSelectNewWithLiteralList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( "select new Student(555L, s.name) from Student s order by s.studentNumber" ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Student yogi = (Student) resultList.get( 0 ); + assertEquals( 555L, yogi.getStudentNumber() ); + assertEquals( yogiExpected.getName(), yogi.getName() ); + Student sherman = (Student) resultList.get( 1 ); + assertEquals( 555L, sherman.getStudentNumber() ); + assertEquals( shermanExpected.getName(), sherman.getName() ); + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testMultiSelectNewListList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( "select new list(s.studentNumber, s.name) from Student s order by s.studentNumber" ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + List yogiList = (List) resultList.get( 0 ); + assertEquals( yogiExpected.getStudentNumber(), yogiList.get( 0 ) ); + assertEquals( yogiExpected.getName(), yogiList.get( 1 ) ); + List shermanList = (List) resultList.get( 1 ); + assertEquals( shermanExpected.getStudentNumber(), shermanList.get( 0 ) ); + assertEquals( shermanExpected.getName(), shermanList.get( 1 ) ); + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testMultiSelectNewMapUsingAliasesList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "select new map(s.studentNumber as sNumber, s.name as sName) from Student s order by s.studentNumber" ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Map yogiMap = (Map) resultList.get( 0 ); + assertEquals( yogiExpected.getStudentNumber(), yogiMap.get( "sNumber" ) ); + assertEquals( yogiExpected.getName(), yogiMap.get( "sName" ) ); + Map shermanMap = (Map) resultList.get( 1 ); + assertEquals( shermanExpected.getStudentNumber(), shermanMap.get( "sNumber" ) ); + assertEquals( shermanExpected.getName(), shermanMap.get( "sName" ) ); + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testMultiSelectNewMapUsingAliasesWithFetchJoinList() throws Exception { + HqlExecutor hqlSelectNewMapExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "select new map(s as s, pc as pc) from Student s left join s.preferredCourse pc left join fetch s.enrolments order by s.studentNumber" ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Map yogiMap = (Map) resultList.get( 0 ); + assertEquals( yogiExpected, yogiMap.get( "s" ) ); + assertEquals( yogiExpected.getPreferredCourse(), yogiMap.get( "pc" ) ); + Map shermanMap = (Map) resultList.get( 1 ); + assertEquals( shermanExpected, shermanMap.get( "s" ) ); + assertNull( shermanMap.get( "pc" ) ); + if ( areDynamicNonLazyAssociationsChecked() ) { + assertTrue( Hibernate.isInitialized( ( (Student) yogiMap.get( "s" ) ).getEnrolments() ) ); + assertEquals( yogiExpected.getEnrolments(), ( (Student) yogiMap.get( "s" ) ).getEnrolments() ); + assertTrue( Hibernate.isInitialized( ( (Student) shermanMap.get( "s" ) ).getEnrolments() ) ); + assertEquals( + shermanExpected.getEnrolments(), + ( ( (Student) shermanMap.get( "s" ) ).getEnrolments() ) + ); + } + }; + runTest( hqlSelectNewMapExecutor, checker, false ); + } + + @Test + public void testMultiSelectAliasToEntityMapUsingAliasesWithFetchJoinList() throws Exception { + HqlExecutor hqlAliasToEntityMapExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "select s as s, pc as pc from Student s left join s.preferredCourse pc left join fetch s.enrolments order by s.studentNumber" ) + .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Map yogiMap = (Map) resultList.get( 0 ); + assertEquals( yogiExpected, yogiMap.get( "s" ) ); + assertEquals( + yogiExpected.getPreferredCourse().getCourseCode(), + ( (Course) yogiMap.get( "pc" ) ).getCourseCode() + ); + Map shermanMap = (Map) resultList.get( 1 ); + assertEquals( shermanExpected, shermanMap.get( "s" ) ); + assertNull( shermanMap.get( "pc" ) ); + if ( areDynamicNonLazyAssociationsChecked() ) { + assertEquals( yogiExpected.getPreferredCourse(), yogiMap.get( "pc" ) ); + assertTrue( Hibernate.isInitialized( ( (Student) yogiMap.get( "s" ) ).getEnrolments() ) ); + assertEquals( yogiExpected.getEnrolments(), ( (Student) yogiMap.get( "s" ) ).getEnrolments() ); + assertTrue( Hibernate.isInitialized( ( (Student) shermanMap.get( "s" ) ).getEnrolments() ) ); + assertEquals( + shermanExpected.getEnrolments(), + ( ( (Student) shermanMap.get( "s" ) ).getEnrolments() ) + ); + } + }; + runTest( hqlAliasToEntityMapExecutor, checker, false ); + } + + @Test + public void testMultiSelectUsingImplicitJoinWithFetchJoinListHql() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "select s as s, s.preferredCourse as pc from Student s left join fetch s.enrolments" ); + } + }; + ResultChecker checker = results -> { + assertTrue( results instanceof Object[] ); + Object[] yogiObjects = (Object[]) results; + assertEquals( 2, yogiObjects.length ); + assertEquals( yogiExpected, yogiObjects[0] ); + assertEquals( + yogiExpected.getPreferredCourse().getCourseCode(), + ( (Course) yogiObjects[1] ).getCourseCode() + ); + if ( areDynamicNonLazyAssociationsChecked() ) { + assertEquals( yogiExpected.getPreferredCourse(), yogiObjects[1] ); + assertTrue( Hibernate.isInitialized( ( (Student) yogiObjects[0] ).getEnrolments() ) ); + assertEquals( yogiExpected.getEnrolments(), ( (Student) yogiObjects[0] ).getEnrolments() ); + } + }; + runTest( hqlExecutor, checker, true ); + } + + @Test + public void testSelectNewMapUsingAliasesList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "select new map(s.studentNumber as sNumber, s.name as sName) from Student s order by s.studentNumber" ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Map yogiMap = (Map) resultList.get( 0 ); + assertEquals( yogiExpected.getStudentNumber(), yogiMap.get( "sNumber" ) ); + assertEquals( yogiExpected.getName(), yogiMap.get( "sName" ) ); + Map shermanMap = (Map) resultList.get( 1 ); + assertEquals( shermanExpected.getStudentNumber(), shermanMap.get( "sNumber" ) ); + assertEquals( shermanExpected.getName(), shermanMap.get( "sName" ) ); + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testSelectNewEntityConstructorList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( + "select new Student(s.studentNumber, s.name) from Student s order by s.studentNumber" ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Student yogi = (Student) resultList.get( 0 ); + assertEquals( yogiExpected.getStudentNumber(), yogi.getStudentNumber() ); + assertEquals( yogiExpected.getName(), yogi.getName() ); + Student sherman = (Student) resultList.get( 1 ); + assertEquals( shermanExpected.getStudentNumber(), sherman.getStudentNumber() ); + assertEquals( shermanExpected.getName(), sherman.getName() ); + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testMapKeyList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( "select key(s.addresses) from Student s" ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + assertTrue( resultList.contains( "home" ) ); + assertTrue( resultList.contains( "work" ) ); + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testMapValueList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( "select value(s.addresses) from Student s" ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + assertTrue( resultList.contains( yogiExpected.getAddresses().get( "home" ) ) ); + assertTrue( resultList.contains( yogiExpected.getAddresses().get( "work" ) ) ); + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testMapEntryList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( "select entry(s.addresses) from Student s" ); + } + }; + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Iterator it = resultList.iterator(); + assertTrue( resultList.get( 0 ) instanceof Map.Entry ); + Map.Entry entry = (Map.Entry) it.next(); + if ( "home".equals( entry.getKey() ) ) { + assertEquals( yogiExpected.getAddresses().get( "home" ), entry.getValue() ); + entry = (Map.Entry) it.next(); + assertEquals( yogiExpected.getAddresses().get( "work" ), entry.getValue() ); + } + else { + assertEquals( "work", entry.getKey() ); + assertEquals( yogiExpected.getAddresses().get( "work" ), entry.getValue() ); + entry = (Map.Entry) it.next(); + assertEquals( yogiExpected.getAddresses().get( "home" ), entry.getValue() ); + } + }; + runTest( hqlExecutor, checker, false ); + } + + @Test + public void testMapElementsList() throws Exception { + HqlExecutor hqlExecutor = new HqlExecutor() { + @Override + public Query getQuery(Session s) { + return s.createQuery( "select elements(a) from Student s inner join s.addresses a" ); + } + }; + + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + assertTrue( resultList.contains( yogiExpected.getAddresses().get( "home" ) ) ); + assertTrue( resultList.contains( yogiExpected.getAddresses().get( "work" ) ) ); + }; + runTest( hqlExecutor, checker, false ); + } + + private boolean isQueryCacheGetEnabled() { + return getQueryCacheMode() == CacheMode.NORMAL || + getQueryCacheMode() == CacheMode.GET; + } + + private boolean isQueryCachePutEnabled() { + return getQueryCacheMode() == CacheMode.NORMAL || + getQueryCacheMode() == CacheMode.PUT; + } + + protected void runTest(QueryExecutor queryExecutor, ResultChecker resultChecker, boolean isSingleResult) + throws Exception { + createData(); + try { + clearCache(); + clearStatistics(); + + Object results = queryExecutor.execute( isSingleResult ); + + assertHitCount( 0 ); + assertMissCount( isQueryCacheGetEnabled() ? 1 : 0 ); + assertPutCount( isQueryCachePutEnabled() ? 1 : 0 ); + clearStatistics(); + + resultChecker.check( results ); + + // check again to make sure nothing got initialized while checking results; + assertHitCount( 0 ); + assertMissCount( 0 ); + assertPutCount( 0 ); + clearStatistics(); + + results = queryExecutor.execute( isSingleResult ); + + assertHitCount( isQueryCacheGetEnabled() ? 1 : 0 ); + assertMissCount( 0 ); + assertPutCount( !isQueryCacheGetEnabled() && isQueryCachePutEnabled() ? 1 : 0 ); + clearStatistics(); + + resultChecker.check( results ); + + // check again to make sure nothing got initialized while checking results; + assertHitCount( 0 ); + assertMissCount( 0 ); + assertPutCount( 0 ); + clearStatistics(); + }finally { + deleteData(); + } + } + + protected void clearCache() { + sessionFactory().getCache().evictQueryRegions(); + } + + protected void clearStatistics() { + sessionFactory().getStatistics().clear(); + } + + protected void assertEntityFetchCount(int expected) { + int actual = (int) sessionFactory().getStatistics().getEntityFetchCount(); + assertEquals( expected, actual ); + } + + protected void assertCount(int expected) { + int actual = sessionFactory().getStatistics().getQueries().length; + assertEquals( expected, actual ); + } + + protected void assertHitCount(int expected) { + int actual = (int) sessionFactory().getStatistics().getQueryCacheHitCount(); + assertEquals( expected, actual ); + } + + protected void assertMissCount(int expected) { + int actual = (int) sessionFactory().getStatistics().getQueryCacheMissCount(); + assertEquals( expected, actual ); + } + + protected void assertPutCount(int expected) { + int actual = (int) sessionFactory().getStatistics().getQueryCachePutCount(); + assertEquals( expected, actual ); + } + + protected void assertInsertCount(int expected) { + int inserts = (int) sessionFactory().getStatistics().getEntityInsertCount(); + assertEquals( "unexpected insert count", expected, inserts ); + } + + protected void assertUpdateCount(int expected) { + int updates = (int) sessionFactory().getStatistics().getEntityUpdateCount(); + assertEquals( "unexpected update counts", expected, updates ); + } + + protected void assertDeleteCount(int expected) { + int deletes = (int) sessionFactory().getStatistics().getEntityDeleteCount(); + assertEquals( "unexpected delete counts", expected, deletes ); + } +} diff --git a/hibernate-core/src/test/java/org/hibernate/test/querycache/Address.java b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/Address.java similarity index 98% rename from hibernate-core/src/test/java/org/hibernate/test/querycache/Address.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/querycache/Address.java index 21f14494bf..ac0e165f9b 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/querycache/Address.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/Address.java @@ -6,7 +6,7 @@ */ // $Id: Address.java 7996 2005-08-22 14:49:57Z steveebersole $ -package org.hibernate.test.querycache; +package org.hibernate.orm.test.querycache; /** diff --git a/hibernate-core/src/test/java/org/hibernate/test/querycache/CompositeKey.java b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/CompositeKey.java similarity index 91% rename from hibernate-core/src/test/java/org/hibernate/test/querycache/CompositeKey.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/querycache/CompositeKey.java index 7a19626f3b..6189c29114 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/querycache/CompositeKey.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/CompositeKey.java @@ -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 . */ -package org.hibernate.test.querycache; +package org.hibernate.orm.test.querycache; import java.io.Serializable; diff --git a/hibernate-core/src/test/java/org/hibernate/test/querycache/Course.java b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/Course.java similarity index 97% rename from hibernate-core/src/test/java/org/hibernate/test/querycache/Course.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/querycache/Course.java index f492b687a3..c3a69f2412 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/querycache/Course.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/Course.java @@ -6,7 +6,7 @@ */ //$Id: Course.java 5686 2005-02-12 07:27:32Z steveebersole $ -package org.hibernate.test.querycache; +package org.hibernate.orm.test.querycache; import java.io.Serializable; import java.util.HashSet; import java.util.Set; diff --git a/hibernate-core/src/test/java/org/hibernate/test/querycache/CourseMeeting.java b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/CourseMeeting.java similarity index 96% rename from hibernate-core/src/test/java/org/hibernate/test/querycache/CourseMeeting.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/querycache/CourseMeeting.java index 5cd5cd3374..ec94914bc2 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/querycache/CourseMeeting.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/CourseMeeting.java @@ -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 . */ -package org.hibernate.test.querycache; +package org.hibernate.orm.test.querycache; /** diff --git a/hibernate-core/src/test/java/org/hibernate/test/querycache/CourseMeetingId.java b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/CourseMeetingId.java similarity index 97% rename from hibernate-core/src/test/java/org/hibernate/test/querycache/CourseMeetingId.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/querycache/CourseMeetingId.java index c6c2b21650..5874991d5f 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/querycache/CourseMeetingId.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/CourseMeetingId.java @@ -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 . */ -package org.hibernate.test.querycache; +package org.hibernate.orm.test.querycache; import java.io.Serializable; /** diff --git a/hibernate-core/src/test/java/org/hibernate/test/querycache/Enrolment.hbm.xml b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/Enrolment.hbm.xml similarity index 98% rename from hibernate-core/src/test/java/org/hibernate/test/querycache/Enrolment.hbm.xml rename to hibernate-core/src/test/java/org/hibernate/orm/test/querycache/Enrolment.hbm.xml index 08ab4db86a..f1bfd1d335 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/querycache/Enrolment.hbm.xml +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/Enrolment.hbm.xml @@ -9,7 +9,7 @@ "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> - + diff --git a/hibernate-core/src/test/java/org/hibernate/test/querycache/Enrolment.java b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/Enrolment.java similarity index 98% rename from hibernate-core/src/test/java/org/hibernate/test/querycache/Enrolment.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/querycache/Enrolment.java index b954557aec..078f67cc8e 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/querycache/Enrolment.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/Enrolment.java @@ -6,7 +6,7 @@ */ //$Id: Enrolment.java 6970 2005-05-31 20:24:41Z oneovthafew $ -package org.hibernate.test.querycache; +package org.hibernate.orm.test.querycache; import java.io.Serializable; /** diff --git a/hibernate-core/src/test/java/org/hibernate/test/querycache/EntityWithCompositeKey.java b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/EntityWithCompositeKey.java similarity index 88% rename from hibernate-core/src/test/java/org/hibernate/test/querycache/EntityWithCompositeKey.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/querycache/EntityWithCompositeKey.java index 14614cce3a..5d2e810cc1 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/querycache/EntityWithCompositeKey.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/EntityWithCompositeKey.java @@ -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 . */ -package org.hibernate.test.querycache; +package org.hibernate.orm.test.querycache; import javax.persistence.EmbeddedId; import javax.persistence.Entity; diff --git a/hibernate-core/src/test/java/org/hibernate/test/querycache/EntityWithStringCompositeKey.java b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/EntityWithStringCompositeKey.java similarity index 90% rename from hibernate-core/src/test/java/org/hibernate/test/querycache/EntityWithStringCompositeKey.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/querycache/EntityWithStringCompositeKey.java index ac07f19f0c..7158fbe7fc 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/querycache/EntityWithStringCompositeKey.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/EntityWithStringCompositeKey.java @@ -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 . */ -package org.hibernate.test.querycache; +package org.hibernate.orm.test.querycache; import javax.persistence.EmbeddedId; import javax.persistence.Entity; diff --git a/hibernate-core/src/test/java/org/hibernate/test/querycache/HqlQueryCacheIgnoreResultTransformerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/HqlQueryCacheIgnoreResultTransformerTest.java similarity index 76% rename from hibernate-core/src/test/java/org/hibernate/test/querycache/HqlQueryCacheIgnoreResultTransformerTest.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/querycache/HqlQueryCacheIgnoreResultTransformerTest.java index bfec316c92..9c33b888ec 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/querycache/HqlQueryCacheIgnoreResultTransformerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/HqlQueryCacheIgnoreResultTransformerTest.java @@ -4,32 +4,24 @@ * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or . */ -package org.hibernate.test.querycache; +package org.hibernate.orm.test.querycache; import org.junit.Test; import org.hibernate.CacheMode; +import org.hibernate.orm.test.querycache.AbstractHqlQueryCacheResultTransformerTest; + import org.hibernate.testing.FailureExpected; /** * @author Gail Badner */ -public class HqlQueryCacheIgnoreResultTransformerTest extends AbstractQueryCacheResultTransformerTest { +public class HqlQueryCacheIgnoreResultTransformerTest extends AbstractHqlQueryCacheResultTransformerTest { @Override protected CacheMode getQueryCacheMode() { return CacheMode.IGNORE; } - @Override - protected void runTest(HqlExecutor hqlExecutor, CriteriaExecutor criteriaExecutor, ResultChecker checker, boolean isSingleResult) - throws Exception { - createData(); - if ( hqlExecutor != null ) { - runTest( hqlExecutor, checker, isSingleResult ); - } - deleteData(); - } - @Test @Override @FailureExpected( jiraKey = "N/A", message = "HQL query using Transformers.ALIAS_TO_ENTITY_MAP with no projection" ) @@ -53,7 +45,6 @@ public class HqlQueryCacheIgnoreResultTransformerTest extends AbstractQueryCache @Test @Override - @FailureExpected( jiraKey = "HHH-3345", message = "HQL query using 'select new' and 'join fetch'" ) public void testMultiSelectNewMapUsingAliasesWithFetchJoinList() throws Exception { super.testMultiSelectNewMapUsingAliasesWithFetchJoinList(); } diff --git a/hibernate-core/src/test/java/org/hibernate/test/querycache/HqlQueryCacheNormalResultTransformerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/HqlQueryCacheNormalResultTransformerTest.java similarity index 91% rename from hibernate-core/src/test/java/org/hibernate/test/querycache/HqlQueryCacheNormalResultTransformerTest.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/querycache/HqlQueryCacheNormalResultTransformerTest.java index 19a9416916..3b5f0a4c2d 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/querycache/HqlQueryCacheNormalResultTransformerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/HqlQueryCacheNormalResultTransformerTest.java @@ -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 . */ -package org.hibernate.test.querycache; +package org.hibernate.orm.test.querycache; import org.hibernate.CacheMode; diff --git a/hibernate-core/src/test/java/org/hibernate/test/querycache/HqlQueryCachePutResultTransformerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/HqlQueryCachePutResultTransformerTest.java similarity index 93% rename from hibernate-core/src/test/java/org/hibernate/test/querycache/HqlQueryCachePutResultTransformerTest.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/querycache/HqlQueryCachePutResultTransformerTest.java index 35a43370b1..9e1cf01105 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/querycache/HqlQueryCachePutResultTransformerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/HqlQueryCachePutResultTransformerTest.java @@ -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 . */ -package org.hibernate.test.querycache; +package org.hibernate.orm.test.querycache; import org.hibernate.CacheMode; diff --git a/hibernate-core/src/test/java/org/hibernate/test/querycache/Item.hbm.xml b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/Item.hbm.xml similarity index 93% rename from hibernate-core/src/test/java/org/hibernate/test/querycache/Item.hbm.xml rename to hibernate-core/src/test/java/org/hibernate/orm/test/querycache/Item.hbm.xml index 9a0eaeaeff..0a2b452049 100755 --- a/hibernate-core/src/test/java/org/hibernate/test/querycache/Item.hbm.xml +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/Item.hbm.xml @@ -10,7 +10,7 @@ "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> + package="org.hibernate.orm.test.querycache"> diff --git a/hibernate-core/src/test/java/org/hibernate/test/querycache/Item.java b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/Item.java similarity index 94% rename from hibernate-core/src/test/java/org/hibernate/test/querycache/Item.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/querycache/Item.java index 8c69b190cd..7ce075a3e8 100755 --- a/hibernate-core/src/test/java/org/hibernate/test/querycache/Item.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/Item.java @@ -6,7 +6,7 @@ */ //$Id: Item.java 9587 2006-03-09 21:38:26Z steve.ebersole@jboss.com $ -package org.hibernate.test.querycache; +package org.hibernate.orm.test.querycache; diff --git a/hibernate-core/src/test/java/org/hibernate/test/querycache/PersonName.java b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/PersonName.java similarity index 97% rename from hibernate-core/src/test/java/org/hibernate/test/querycache/PersonName.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/querycache/PersonName.java index 35e68ef4ca..2d01c2e31f 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/querycache/PersonName.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/PersonName.java @@ -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 . */ -package org.hibernate.test.querycache; +package org.hibernate.orm.test.querycache; /** diff --git a/hibernate-core/src/test/java/org/hibernate/test/querycache/QueryCacheJoinFetchTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/QueryCacheJoinFetchTest.java similarity index 62% rename from hibernate-core/src/test/java/org/hibernate/test/querycache/QueryCacheJoinFetchTest.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/querycache/QueryCacheJoinFetchTest.java index 388312c76d..19af044f1a 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/querycache/QueryCacheJoinFetchTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/QueryCacheJoinFetchTest.java @@ -4,11 +4,10 @@ * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or . */ -package org.hibernate.test.querycache; +package org.hibernate.orm.test.querycache; import java.util.ArrayList; import java.util.List; -import java.util.Map; import java.util.Objects; import javax.persistence.CascadeType; import javax.persistence.Column; @@ -24,39 +23,36 @@ import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.NaturalId; import org.hibernate.annotations.QueryHints; import org.hibernate.cfg.AvailableSettings; -import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase; -import org.hibernate.testing.FailureExpected; import org.hibernate.testing.TestForIssue; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; /** * @author Vlad Mihalcea */ -@TestForIssue( jiraKey = "HHH-12430" ) -public class QueryCacheJoinFetchTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class, - }; - } - - protected void addConfigOptions(Map options) { - options.put( AvailableSettings.USE_QUERY_CACHE, "true" ); - options.put( AvailableSettings.USE_SECOND_LEVEL_CACHE, "true" ); - options.put( AvailableSettings.GENERATE_STATISTICS, "true" ); - } +@TestForIssue(jiraKey = "HHH-12430") +@Jpa( + annotatedClasses = { + QueryCacheJoinFetchTest.Person.class, + QueryCacheJoinFetchTest.Phone.class + }, + generateStatistics = true, + integrationSettings = { + @Setting(name = AvailableSettings.USE_QUERY_CACHE, value = "true"), + @Setting(name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "true") + } +) +public class QueryCacheJoinFetchTest { @Test - @FailureExpected( jiraKey = "HHH-12430" ) - public void testLifecycle() { - doInJPA( this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(); Phone phone1 = new Phone( "123-456-7890" ); Phone phone2 = new Phone( "321-654-0987" ); @@ -66,38 +62,38 @@ public class QueryCacheJoinFetchTest extends BaseEntityManagerFunctionalTestCase entityManager.persist( person ); } ); - entityManagerFactory().getCache().evictAll(); - entityManagerFactory().unwrap( SessionFactory.class ).getStatistics().clear(); + scope.getEntityManagerFactory().getCache().evictAll(); + scope.getEntityManagerFactory().unwrap( SessionFactory.class ).getStatistics().clear(); - Person person = doInJPA( this::entityManagerFactory, entityManager -> { + Person person = scope.fromEntityManager( entityManager -> { return entityManager.createQuery( - "select distinct p " + - "from Person p " + - "join fetch p.phones ph", Person.class ) - .setHint( QueryHints.CACHEABLE, Boolean.TRUE ) - .getSingleResult(); + "select distinct p " + + "from Person p " + + "join fetch p.phones ph", Person.class ) + .setHint( QueryHints.CACHEABLE, Boolean.TRUE ) + .getSingleResult(); } ); assertEquals( 2, person.getPhones().size() ); assertEquals( 0, - entityManagerFactory().unwrap( SessionFactory.class ).getStatistics().getQueryCacheHitCount() + scope.getEntityManagerFactory().unwrap( SessionFactory.class ).getStatistics().getQueryCacheHitCount() ); - person = doInJPA( this::entityManagerFactory, entityManager -> { - entityManager.getEntityManagerFactory().getCache().evictAll(); + person = scope.fromEntityManager( entityManager -> { + scope.getEntityManagerFactory().getCache().evictAll(); return entityManager.createQuery( - "select distinct p " + - "from Person p " + - "join fetch p.phones ph", Person.class ) - .setHint( QueryHints.CACHEABLE, Boolean.TRUE ) - .getSingleResult(); + "select distinct p " + + "from Person p " + + "join fetch p.phones ph", Person.class ) + .setHint( QueryHints.CACHEABLE, Boolean.TRUE ) + .getSingleResult(); } ); assertEquals( 1, - entityManagerFactory().unwrap( SessionFactory.class ).getStatistics().getQueryCacheHitCount() + scope.getEntityManagerFactory().unwrap( SessionFactory.class ).getStatistics().getQueryCacheHitCount() ); assertEquals( 2, person.getPhones().size() ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/QueryCacheTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/QueryCacheTest.java new file mode 100644 index 0000000000..e9d865734c --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/QueryCacheTest.java @@ -0,0 +1,770 @@ +/* + * 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 . + */ +package org.hibernate.orm.test.querycache; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; + +import org.hibernate.EmptyInterceptor; +import org.hibernate.Hibernate; +import org.hibernate.Session; +import org.hibernate.SessionBuilder; +import org.hibernate.Transaction; +import org.hibernate.cfg.AvailableSettings; +import org.hibernate.query.NativeQuery; +import org.hibernate.query.Query; +import org.hibernate.stat.EntityStatistics; +import org.hibernate.stat.QueryStatistics; +import org.hibernate.stat.spi.StatisticsImplementor; +import org.hibernate.transform.Transformers; +import org.hibernate.type.Type; + +import org.hibernate.testing.TestForIssue; +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.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.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +/** + * @author Gavin King + * @author Brett Meyer + */ +@DomainModel( + xmlMappings = "org/hibernate/orm/test/querycache/Item.hbm.xml", + annotatedClasses = { + CompositeKey.class, + EntityWithCompositeKey.class, + StringCompositeKey.class, + EntityWithStringCompositeKey.class + }, + concurrencyStrategy = "nonstrict-read-write" +) +@SessionFactory(generateStatistics = true) +@ServiceRegistry( + settings = { + @Setting(name = AvailableSettings.USE_QUERY_CACHE, value = "true"), + @Setting(name = AvailableSettings.CACHE_REGION_PREFIX, value = "foo"), + @Setting(name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "true") + } +) +public class QueryCacheTest { + + private static final CompositeKey PK = new CompositeKey( 1, 2 ); + private static final ExecutorService executor = Executors.newFixedThreadPool( 4 ); + + + @AfterEach + public void tearDown(SessionFactoryScope scope) { + scope.inTransaction( + session -> + session.createQuery( "from java.lang.Object" ).list().forEach( session::remove ) + ); + } + + @AfterAll + protected void shutDown() { + executor.shutdown(); + } + + + @Test + @TestForIssue(jiraKey = "HHH-5426") + public void testInvalidationFromBulkHQL(SessionFactoryScope scope) { + scope.getSessionFactory().getCache().evictQueryRegions(); + scope.getSessionFactory().getStatistics().clear(); + + scope.inTransaction( + session -> { + for ( int i = 0; i < 3; i++ ) { + Item a = new Item(); + a.setName( "a" + i ); + a.setDescription( "a" + i ); + session.persist( a ); + } + } + ); + + String queryString = "select count(*) from Item"; + scope.inTransaction( + session -> { + // this query will hit the database and create the cache + Long result = (Long) session.createQuery( queryString ).setCacheable( true ).uniqueResult(); + assertEquals( 3, result.intValue() ); + } + ); + + scope.inTransaction( + session -> + session.createQuery( "delete from Item" ).executeUpdate() + ); + + scope.inTransaction( + session -> { + // and this one SHOULD not be served by the cache + Number result2 = (Number) session.createQuery( queryString ).setCacheable( true ).uniqueResult(); + assertEquals( 0, result2.intValue() ); + } + ); + } + + @Test + @TestForIssue(jiraKey = "JBPAPP-4224") + public void testHitCacheInSameSession(SessionFactoryScope scope) { + scope.getSessionFactory().getCache().evictQueryRegions(); + scope.getSessionFactory().getStatistics().clear(); + + List list = new ArrayList<>(); + scope.inSession( + session -> { + try { + session.beginTransaction(); + for ( int i = 0; i < 3; i++ ) { + Item a = new Item(); + a.setName( "a" + i ); + a.setDescription( "a" + i ); + list.add( a ); + session.persist( a ); + } + session.getTransaction().commit(); + +// s.close(); +// s=openSession(); + + session.beginTransaction(); + String queryString = "from Item"; + // this query will hit the database and create the cache + session.createQuery( queryString ).setCacheable( true ).list(); + session.getTransaction().commit(); + + session.beginTransaction(); + //and this one SHOULD served by the cache + session.createQuery( queryString ).setCacheable( true ).list(); + session.getTransaction().commit(); + QueryStatistics qs = session.getSessionFactory() + .getStatistics() + .getQueryStatistics( queryString ); + assertEquals( 1, qs.getCacheHitCount() ); + assertEquals( 1, qs.getCachePutCount() ); + } + finally { + if ( session.getTransaction().isActive() ) { + session.getTransaction().rollback(); + } + } + } + ); + scope.inTransaction( + session -> { + for ( Object obj : list ) { + session.delete( obj ); + } + } + ); + } + + private static final String queryString = "from Item i where i.name='widget'"; + + @Test + public void testQueryCacheInvalidation(SessionFactoryScope scope) throws Exception { + scope.getSessionFactory().getCache().evictQueryRegions(); + + final StatisticsImplementor statistics = scope.getSessionFactory().getStatistics(); + statistics.clear(); + + final String queryString = "from Item i where i.name='widget'"; + + final QueryStatistics qs = statistics.getQueryStatistics( queryString ); + final EntityStatistics es = statistics.getEntityStatistics( Item.class.getName() ); + + scope.inTransaction( + session -> { + session.createQuery( queryString ).setCacheable( true ).list(); + Item i = new Item(); + i.setName( "widget" ); + i.setDescription( "A really top-quality, full-featured widget." ); + session.save( i ); + } + ); + + // hit -> 0 + // miss -> 1 + // put -> 1 + + assertEquals( 1, es.getInsertCount() ); + assertEquals( 0, es.getUpdateCount() ); + + assertEquals( 0, statistics.getQueryCacheHitCount() ); + assertEquals( 0, qs.getCacheHitCount() ); + + assertEquals( 1, statistics.getQueryCacheMissCount() ); + assertEquals( 1, qs.getCacheMissCount() ); + + assertEquals( 1, statistics.getQueryCachePutCount() ); + assertEquals( 1, qs.getCachePutCount() ); + + assertEquals( 1, statistics.getQueryExecutionCount() ); + assertEquals( 1, qs.getExecutionCount() ); + + assertEquals( 0, statistics.getEntityFetchCount() ); + + + scope.inTransaction( + session -> { + List result = session.createQuery( queryString ).setCacheable( true ).list(); + assertEquals( 1, result.size() ); + } + ); + + // hit -> 0 + // miss -> 2 + // put -> 2 + + assertEquals( 1, es.getInsertCount() ); + assertEquals( 0, es.getUpdateCount() ); + + assertEquals( 0, statistics.getQueryCacheHitCount() ); + assertEquals( 0, qs.getCacheHitCount() ); + + assertEquals( 2, statistics.getQueryCacheMissCount() ); + assertEquals( 2, qs.getCacheMissCount() ); + + assertEquals( 2, statistics.getQueryCachePutCount() ); + assertEquals( 2, qs.getCachePutCount() ); + + assertEquals( 2, statistics.getQueryExecutionCount() ); + assertEquals( 2, qs.getExecutionCount() ); + + assertEquals( 0, statistics.getEntityFetchCount() ); + + scope.inTransaction( + session -> { + List result = session.createQuery( queryString ).setCacheable( true ).list(); + assertEquals( 1, result.size() ); + } + ); + + // hit -> 1 + // miss -> 2 + // put -> 2 + + assertEquals( 1, es.getInsertCount() ); + assertEquals( 0, es.getUpdateCount() ); + + assertEquals( 1, statistics.getQueryCacheHitCount() ); + assertEquals( 1, qs.getCacheHitCount() ); + + assertEquals( 2, statistics.getQueryCacheMissCount() ); + assertEquals( 2, qs.getCacheMissCount() ); + + assertEquals( 2, statistics.getQueryCachePutCount() ); + assertEquals( 2, qs.getCachePutCount() ); + + assertEquals( 2, statistics.getQueryExecutionCount() ); + assertEquals( 2, qs.getExecutionCount() ); + + assertEquals( 0, statistics.getEntityFetchCount() ); + + assertEquals( 1, qs.getCacheHitCount() ); + assertEquals( 0, statistics.getEntityFetchCount() ); + + Item item = scope.fromTransaction( + session -> { + List result = session.createQuery( queryString ).setCacheable( true ).list(); + assertEquals( 1, result.size() ); + Item i = result.get( 0 ); + assertTrue( Hibernate.isInitialized( i ) ); + assertTrue( session.contains( i ) ); + i.setName( "Widget" ); + session.flush(); + return i; + } + ); + + // hit -> 2 + // miss -> 2 + // put -> 2 + // + // + another invalidation + + assertEquals( 1, es.getInsertCount() ); + assertEquals( 1, es.getUpdateCount() ); + + assertEquals( 2, statistics.getQueryCacheHitCount() ); + assertEquals( 2, qs.getCacheHitCount() ); + + assertEquals( 2, statistics.getQueryCacheMissCount() ); + assertEquals( 2, qs.getCacheMissCount() ); + + assertEquals( 2, statistics.getQueryCachePutCount() ); + assertEquals( 2, qs.getCachePutCount() ); + + assertEquals( 2, statistics.getQueryExecutionCount() ); + assertEquals( 2, qs.getExecutionCount() ); + + assertEquals( 0, statistics.getEntityFetchCount() ); + + + Thread.sleep( 200 ); + + scope.inTransaction( + session -> { + session.createQuery( queryString ).setCacheable( true ).list(); + Item i = session.get( Item.class, item.getId() ); + + session.delete( i ); + } + ); + + // hit -> 2 + // miss -> 3 + // put -> 3 + + assertEquals( 1, es.getInsertCount() ); + assertEquals( 1, es.getUpdateCount() ); + + assertEquals( 2, statistics.getQueryCacheHitCount() ); + assertEquals( 2, qs.getCacheHitCount() ); + + assertEquals( 3, statistics.getQueryCacheMissCount() ); + assertEquals( 3, qs.getCacheMissCount() ); + + assertEquals( 3, statistics.getQueryCachePutCount() ); + assertEquals( 3, qs.getCachePutCount() ); + + assertEquals( 3, statistics.getQueryExecutionCount() ); + assertEquals( 3, qs.getExecutionCount() ); + + assertEquals( 0, statistics.getEntityFetchCount() ); + assertEquals( 0, es.getFetchCount() ); + + assertEquals( 2, qs.getCacheHitCount() ); + assertEquals( 3, qs.getCacheMissCount() ); + assertEquals( 3, qs.getCachePutCount() ); + assertEquals( 3, qs.getExecutionCount() ); + assertEquals( 0, es.getFetchCount() ); //check that it was being cached + + } + + @Test + @RequiresDialectFeature( + feature = DialectFeatureChecks.CaseSensitiveCheck.class, + comment = "i.name='widget' should not match on case sensitive database." + ) + public void testCaseInsensitiveComparison(SessionFactoryScope scope) { + Item item = new Item(); + scope.inTransaction( + session -> { + item.setName( "Widget" ); + item.setDescription( "A really top-quality, full-featured widget." ); + session.save( item ); + } + ); + + scope.inTransaction( + session -> { + List result = session.createQuery( queryString ).list(); + assertEquals( 1, result.size() ); + Item i = session.get( Item.class, item.getId() ); + assertEquals( "Widget", i.getName() ); + session.delete( i ); + } + ); + } + + + @Test + public void testProjectionCache(SessionFactoryScope scope) throws Exception { + scope.getSessionFactory().getCache().evictQueryRegions(); + scope.getSessionFactory().getStatistics().clear(); + + final String queryString = "select i.description as desc from Item i where i.name='widget'"; + + Item item = new Item(); + scope.inTransaction( + session -> { + session.createQuery( queryString ).setCacheable( true ).list(); + item.setName( "widget" ); + item.setDescription( "A really top-quality, full-featured widget." ); + session.save( item ); + } + ); + + QueryStatistics qs = scope.getSessionFactory().getStatistics().getQueryStatistics( queryString ); + EntityStatistics es = scope.getSessionFactory().getStatistics().getEntityStatistics( Item.class.getName() ); + + assertEquals( 0, qs.getCacheHitCount() ); + assertEquals( 1, qs.getCacheMissCount() ); + assertEquals( 1, qs.getCachePutCount() ); + + Thread.sleep( 200 ); + + scope.inTransaction( + session -> { + List result = session.createQuery( queryString ).setCacheable( true ).list(); + assertEquals( 1, result.size() ); + assertEquals( item.getDescription(), result.get( 0 ) ); + } + ); + + + assertEquals( 0, qs.getCacheHitCount() ); + assertEquals( 2, qs.getCacheMissCount() ); + assertEquals( 2, qs.getCachePutCount() ); + + scope.inTransaction( + session -> { + List result = session.createQuery( queryString ).setCacheable( true ).list(); + assertEquals( 1, result.size() ); + assertEquals( item.getDescription(), result.get( 0 ) ); + } + ); + + assertEquals( 1, qs.getCacheHitCount() ); + assertEquals( 2, qs.getCacheMissCount() ); + assertEquals( 2, qs.getCachePutCount() ); + + scope.inTransaction( + session -> { + List result = session.createQuery( queryString ) + .setCacheable( true ) + .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP ) + .list(); + assertEquals( 1, result.size() ); + Map m = (Map) result.get( 0 ); + assertEquals( 1, m.size() ); + assertEquals( item.getDescription(), m.get( "desc" ) ); + } + ); + + assertEquals( + 2, + qs.getCacheHitCount(), + "hit count should go up since data is not transformed until after it is cached" + ); + assertEquals( 2, qs.getCacheMissCount() ); + assertEquals( 2, qs.getCachePutCount() ); + + scope.inTransaction( + session -> { + List result = session.createQuery( queryString ) + .setCacheable( true ) + .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP ) + .list(); + assertEquals( 1, result.size() ); + Map m = (Map) result.get( 0 ); + assertEquals( 1, m.size() ); + assertEquals( item.getDescription(), m.get( "desc" ) ); + } + ); + + assertEquals( + 3, + qs.getCacheHitCount(), + "hit count should go up since data is not transformed until after it is cachedr" + ); + assertEquals( 2, qs.getCacheMissCount() ); + assertEquals( 2, qs.getCachePutCount() ); + + scope.inTransaction( + session -> { + List result = session.createQuery( queryString ).setCacheable( true ).list(); + assertEquals( 1, result.size() ); + assertTrue( Hibernate.isInitialized( result.get( 0 ) ) ); + Item i = session.get( Item.class, item.getId() ); + i.setName( "widget" ); + i.setDescription( "A middle-quality widget." ); + } + ); + + assertEquals( 4, qs.getCacheHitCount() ); + assertEquals( 2, qs.getCacheMissCount() ); + assertEquals( 2, qs.getCachePutCount() ); + + Thread.sleep( 200 ); + + scope.inTransaction( + session -> { + List result = session.createQuery( queryString ).setCacheable( true ).list(); + assertEquals( 1, result.size() ); + Item i = session.get( Item.class, item.getId() ); + assertEquals( "A middle-quality widget.", result.get( 0 ) ); + + assertEquals( 4, qs.getCacheHitCount() ); + assertEquals( 3, qs.getCacheMissCount() ); + assertEquals( 3, qs.getCachePutCount() ); + + session.delete( i ); + } + ); + + assertEquals( 4, qs.getCacheHitCount() ); + assertEquals( 3, qs.getCacheMissCount() ); + assertEquals( 3, qs.getCachePutCount() ); + assertEquals( 3, qs.getExecutionCount() ); + assertEquals( 0, es.getFetchCount() ); //check that it was being cached + } + + @Test + @TestForIssue(jiraKey = "HHH-4459") + public void testGetByCompositeId(SessionFactoryScope scope) { + + scope.inSession( + session -> { + session.beginTransaction(); + try { + session.persist( new EntityWithCompositeKey( PK ) ); + Query query = session.createQuery( "FROM EntityWithCompositeKey e WHERE e.pk = :pk" ); + query.setCacheable( true ); + query.setParameter( "pk", PK ); + assertEquals( 1, query.list().size() ); + } + finally { + session.getTransaction().rollback(); + } + } + ); + + scope.inSession( + session -> { + session.beginTransaction(); + try { + EntityWithStringCompositeKey entity = new EntityWithStringCompositeKey(); + StringCompositeKey key = new StringCompositeKey(); + key.setAnalog( "foo1" ); + key.setDevice( "foo2" ); + key.setDeviceType( "foo3" ); + key.setSubstation( "foo4" ); + entity.setPk( key ); + session.persist( entity ); + CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); + CriteriaQuery criteria = criteriaBuilder.createQuery( + EntityWithStringCompositeKey.class ); + Root root = criteria.from( EntityWithStringCompositeKey.class ); + criteria.where( criteriaBuilder.equal( root.get( "pk" ), key ) ); + session.createQuery( criteria ).setCacheable( true ); + + assertEquals( 1, session.createQuery( criteria ).list().size() ); +// Criteria c = s.createCriteria( +// EntityWithStringCompositeKey.class ).add( Restrictions.eq( +// "pk", key ) ); +// c.setCacheable( true ); +// assertEquals( 1, c.list().size() ); + } + finally { + session.getTransaction().rollback(); + } + } + ); + } + + @Test + @TestForIssue(jiraKey = "HHH-3051") + public void testScalarSQLQuery(SessionFactoryScope scope) { + scope.getSessionFactory().getCache().evictQueryRegions(); + scope.getSessionFactory().getStatistics().clear(); + + scope.inTransaction( + session -> { + Item item = new Item(); + item.setName( "fooName" ); + item.setDescription( "fooDescription" ); + session.persist( item ); + } + ); + + scope.inTransaction( + session -> { + // Note: StandardQueryCache#put handles single results and multiple results differently. So, test both + // 1 and 2+ scalars. + + String sqlQuery = "select name, description from Items"; + NativeQuery query = session.createNativeQuery( sqlQuery ); + query.setCacheable( true ); + query.addScalar( "name" ); + query.addScalar( "description" ); + Object[] result1 = (Object[]) query.uniqueResult(); + assertNotNull( result1 ); + assertEquals( 2, result1.length ); + assertEquals( "fooName", result1[0] ); + assertEquals( "fooDescription", result1[1] ); + + sqlQuery = "select name from Items"; + query = session.createNativeQuery( sqlQuery ); + query.setCacheable( true ); + query.addScalar( "name" ); + String result2 = (String) query.uniqueResult(); + assertNotNull( result2 ); + assertEquals( "fooName", result2 ); + } + ); + } + +// @Test +// public void testGetByCompositeIdNoCache() { +// Query query = em.createQuery("FROM EntityWithCompositeKey e WHERE e.pk = :pk"); +// query.setParameter("pk", PK); +// assertEquals(1, query.getResultList().size()); +// } +// +// @Test +// public void testGetByEntityIself() { +// Query query = em.createQuery("FROM EntityWithCompositeKey e WHERE e = :ent"); +// query.setParameter("ent", new EntityWithCompositeKey(PK)); +// assertEquals(1, query.getResultList().size()); +// } + + @Test + @TestForIssue(jiraKey = "HHH-9962") + /* Test courtesy of Giambattista Bloisi */ + public void testDelayedLoad(SessionFactoryScope scope) throws InterruptedException, ExecutionException { + DelayLoadOperations interceptor = new DelayLoadOperations(); + final SessionBuilder sessionBuilder = scope.getSessionFactory().withOptions().interceptor( interceptor ); + Item item1 = new Item(); + item1.setName( "Item1" ); + item1.setDescription( "Washington" ); + + try (Session s1 = sessionBuilder.openSession()) { + Transaction tx1 = s1.beginTransaction(); + try { + s1.persist( item1 ); + tx1.commit(); + } + finally { + if ( tx1.isActive() ) { + tx1.rollback(); + } + } + } + + Item item2 = new Item(); + item2.setName( "Item2" ); + item2.setDescription( "Chicago" ); + try (Session s2 = sessionBuilder.openSession()) { + Transaction tx2 = s2.beginTransaction(); + try { + s2.persist( item2 ); + tx2.commit(); + } + finally { + if ( tx2.isActive() ) { + tx2.rollback(); + } + } + } + + interceptor.blockOnLoad(); + + Future fetchedItem = executor.submit( () -> findByDescription( sessionBuilder, "Washington" ) ); + + // wait for the onLoad listener to be called + interceptor.waitOnLoad(); + + try (Session s3 = sessionBuilder.openSession()) { + Transaction tx3 = s3.beginTransaction(); + try { + item1.setDescription( "New York" ); + item2.setDescription( "Washington" ); + s3.update( item1 ); + s3.update( item2 ); + tx3.commit(); + } + finally { + if ( tx3.isActive() ) { + tx3.rollback(); + } + } + } + + interceptor.unblockOnLoad(); + + // the concurrent query was executed before the data was amended so + // let's expect "Item1" to be returned as living in Washington + Item fetched = fetchedItem.get(); + assertEquals( "Item1", fetched.getName() ); + + // Query again: now "Item2" is expected to live in Washington + fetched = findByDescription( sessionBuilder, "Washington" ); + assertEquals( "Item2", fetched.getName() ); + } + + protected Item findByDescription(SessionBuilder sessionBuilder, final String description) { + try (Session s = sessionBuilder.openSession()) { + CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); + CriteriaQuery criteria = criteriaBuilder.createQuery( Item.class ); + Root root = criteria.from( Item.class ); + criteria.where( criteriaBuilder.equal( root.get( "description" ), description ) ); + + return s.createQuery( criteria ).setCacheable( true ).setReadOnly( true ).uniqueResult(); +// return (Item) s.createCriteria(Item.class) +// .setCacheable(true) +// .setReadOnly(true) +// .add(Restrictions.eq("description", description)) +// .uniqueResult(); + + } + } + + public class DelayLoadOperations extends EmptyInterceptor { + + private volatile CountDownLatch blockLatch; + private volatile CountDownLatch waitLatch; + + @Override + public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) { + // Synchronize load and update activities + try { + if ( waitLatch != null ) { + waitLatch.countDown(); + } + if ( blockLatch != null ) { + blockLatch.await(); + } + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException( e ); + } + return true; + } + + public void blockOnLoad() { + blockLatch = new CountDownLatch( 1 ); + waitLatch = new CountDownLatch( 1 ); + } + + public void waitOnLoad() throws InterruptedException { + waitLatch.await(); + } + + public void unblockOnLoad() { + if ( blockLatch != null ) { + blockLatch.countDown(); + } + } + } +} diff --git a/hibernate-core/src/test/java/org/hibernate/test/querycache/StringCompositeKey.java b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/StringCompositeKey.java similarity index 92% rename from hibernate-core/src/test/java/org/hibernate/test/querycache/StringCompositeKey.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/querycache/StringCompositeKey.java index 47b3b97823..f7969f0bf0 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/querycache/StringCompositeKey.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/StringCompositeKey.java @@ -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 . */ -package org.hibernate.test.querycache; +package org.hibernate.orm.test.querycache; import java.io.Serializable; import javax.persistence.Column; diff --git a/hibernate-core/src/test/java/org/hibernate/test/querycache/StructuredQueryCacheTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/StructuredQueryCacheTest.java similarity index 62% rename from hibernate-core/src/test/java/org/hibernate/test/querycache/StructuredQueryCacheTest.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/querycache/StructuredQueryCacheTest.java index 1dac7cdf16..bfc91c1eb5 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/querycache/StructuredQueryCacheTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/StructuredQueryCacheTest.java @@ -4,11 +4,10 @@ * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or . */ -package org.hibernate.test.querycache; +package org.hibernate.orm.test.querycache; import java.io.Serializable; import java.util.HashSet; -import java.util.Map; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; @@ -20,72 +19,72 @@ import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; -import org.hibernate.CacheMode; -import org.hibernate.Session; import org.hibernate.cfg.AvailableSettings; import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.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.AfterEach; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Vlad Mihalceca */ @TestForIssue( jiraKey = "HHH-12107" ) -public class StructuredQueryCacheTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + StructuredQueryCacheTest.OneToManyWithEmbeddedId.class, + StructuredQueryCacheTest.OneToManyWithEmbeddedIdChild.class, + StructuredQueryCacheTest.OneToManyWithEmbeddedIdKey.class + }, + concurrencyStrategy = "transactional" +) +@SessionFactory +@ServiceRegistry(settings = { + @Setting( name = AvailableSettings.USE_QUERY_CACHE, value = "true" ), + @Setting( name = AvailableSettings.CACHE_REGION_PREFIX, value = "foo" ), + @Setting( name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "true" ), + @Setting( name = AvailableSettings.GENERATE_STATISTICS, value = "true" ), + @Setting( name = AvailableSettings.USE_STRUCTURED_CACHE, value = "true" ), +}) +public class StructuredQueryCacheTest { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - OneToManyWithEmbeddedId.class, - OneToManyWithEmbeddedIdChild.class, - OneToManyWithEmbeddedIdKey.class - }; - } - - @Override - protected void addSettings(Map settings) { - settings.put( AvailableSettings.USE_QUERY_CACHE, "true" ); - settings.put( AvailableSettings.CACHE_REGION_PREFIX, "foo" ); - settings.put( AvailableSettings.USE_SECOND_LEVEL_CACHE, "true" ); - settings.put( AvailableSettings.GENERATE_STATISTICS, "true" ); - settings.put( AvailableSettings.USE_STRUCTURED_CACHE, "true" ); - } - - @Override - protected boolean isCleanupTestDataRequired() { - return true; - } - - @Override - protected String getCacheConcurrencyStrategy() { - return "transactional"; + @AfterEach + public void tearDown(SessionFactoryScope scope){ + scope.inTransaction( + session -> { + session.createQuery( "delete from OneToManyWithEmbeddedIdChild" ).executeUpdate(); + session.createQuery( "delete from OneToManyWithEmbeddedId" ).executeUpdate(); + } + ); } @Test @TestForIssue( jiraKey = "HHH-12107" ) - public void testEmbeddedIdInOneToMany() { + public void testEmbeddedIdInOneToMany(SessionFactoryScope scope) { OneToManyWithEmbeddedIdKey key = new OneToManyWithEmbeddedIdKey( 1234 ); final OneToManyWithEmbeddedId o = new OneToManyWithEmbeddedId( key ); o.setItems( new HashSet<>() ); o.getItems().add( new OneToManyWithEmbeddedIdChild( 1 ) ); - doInHibernate( this::sessionFactory, session -> { - session.persist( o ); - }); + scope.inTransaction( session -> + session.persist( o ) + ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { OneToManyWithEmbeddedId _entity = session.find( OneToManyWithEmbeddedId.class, key ); assertTrue( session.getSessionFactory().getCache().containsEntity( OneToManyWithEmbeddedId.class, key ) ); assertNotNull( _entity ); }); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { OneToManyWithEmbeddedId _entity = session.find( OneToManyWithEmbeddedId.class, key ); assertTrue( session.getSessionFactory().getCache().containsEntity( OneToManyWithEmbeddedId.class, key ) ); assertNotNull( _entity ); @@ -97,6 +96,8 @@ public class StructuredQueryCacheTest extends BaseNonConfigCoreFunctionalTestCas private OneToManyWithEmbeddedIdKey id; + private String name; + private Set items = new HashSet<>( ); public OneToManyWithEmbeddedId() { @@ -130,6 +131,8 @@ public class StructuredQueryCacheTest extends BaseNonConfigCoreFunctionalTestCas public static class OneToManyWithEmbeddedIdChild { private Integer id; + public String name; + public OneToManyWithEmbeddedIdChild() { } @@ -146,6 +149,14 @@ public class StructuredQueryCacheTest extends BaseNonConfigCoreFunctionalTestCas public void setId(int id) { this.id = id; } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } } @Embeddable diff --git a/hibernate-core/src/test/java/org/hibernate/test/querycache/Student.java b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/Student.java similarity index 98% rename from hibernate-core/src/test/java/org/hibernate/test/querycache/Student.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/querycache/Student.java index cb80e96ed5..8e3b0e52ed 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/querycache/Student.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/Student.java @@ -6,7 +6,7 @@ */ //$Id: Student.java 9116 2006-01-23 21:21:01Z steveebersole $ -package org.hibernate.test.querycache; +package org.hibernate.orm.test.querycache; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; diff --git a/hibernate-core/src/test/java/org/hibernate/test/querycache/StudentDTO.java b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/StudentDTO.java similarity index 97% rename from hibernate-core/src/test/java/org/hibernate/test/querycache/StudentDTO.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/querycache/StudentDTO.java index 6463ecc619..2bcb24d929 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/querycache/StudentDTO.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/StudentDTO.java @@ -9,7 +9,7 @@ * Created on 28-Jan-2005 * */ -package org.hibernate.test.querycache; +package org.hibernate.orm.test.querycache; /** diff --git a/hibernate-core/src/test/java/org/hibernate/test/querycache/AbstractQueryCacheResultTransformerTest.java b/hibernate-core/src/test/java/org/hibernate/test/querycache/AbstractQueryCacheResultTransformerTest.java index bdea363046..5822782f52 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/querycache/AbstractQueryCacheResultTransformerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/querycache/AbstractQueryCacheResultTransformerTest.java @@ -8,44 +8,45 @@ package org.hibernate.test.querycache; import java.lang.reflect.Constructor; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import java.util.Map; - import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Expression; -import javax.persistence.criteria.Fetch; import javax.persistence.criteria.Join; import javax.persistence.criteria.JoinType; -import javax.persistence.criteria.Order; +import javax.persistence.criteria.Path; import javax.persistence.criteria.Root; - -import org.junit.Test; +import javax.persistence.criteria.Selection; import org.hibernate.CacheMode; -import org.hibernate.FetchMode; import org.hibernate.Hibernate; -import org.hibernate.NotYetImplementedFor6Exception; -import org.hibernate.query.Query; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.internal.util.ReflectHelper; +import org.hibernate.orm.test.querycache.Address; +import org.hibernate.orm.test.querycache.Course; +import org.hibernate.orm.test.querycache.CourseMeeting; +import org.hibernate.orm.test.querycache.Enrolment; +import org.hibernate.orm.test.querycache.PersonName; +import org.hibernate.orm.test.querycache.Student; +import org.hibernate.orm.test.querycache.StudentDTO; import org.hibernate.proxy.HibernateProxy; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; - +import org.hibernate.query.Query; import org.hibernate.query.criteria.JpaCriteriaQuery; -import org.hibernate.query.criteria.JpaFetch; import org.hibernate.query.criteria.JpaRoot; import org.hibernate.transform.AliasToBeanConstructorResultTransformer; import org.hibernate.transform.AliasToEntityMapResultTransformer; import org.hibernate.transform.ResultTransformer; +import org.hibernate.transform.RootEntityResultTransformer; import org.hibernate.transform.Transformers; import org.hibernate.type.StandardBasicTypes; import org.hibernate.type.Type; +import org.hibernate.testing.FailureExpected; +import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.junit.Test; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -70,6 +71,11 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu return new String[] { "querycache/Enrolment.hbm.xml" }; } + @Override + protected String getBaseForMappings() { + return "org/hibernate/orm/test/"; + } + @Override public void configure(Configuration cfg) { super.configure( cfg ); @@ -82,12 +88,12 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu protected abstract class CriteriaExecutor extends QueryExecutor { protected abstract JpaCriteriaQuery getCriteria(Session s) throws Exception; - protected ResultTransformer getResultTransformer() { + protected ResultTransformer getResultTransformer() throws Exception { return AliasToEntityMapResultTransformer.INSTANCE; } @Override - protected Object getResults(Session s, boolean isSingleResult) throws Exception { + protected Object getResults(Session s, boolean isSingleResult) throws Exception { final CacheMode cacheMode = getQueryCacheMode(); final JpaCriteriaQuery criteria = getCriteria( s ); @@ -105,17 +111,8 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu } } - protected abstract class HqlExecutor extends QueryExecutor { - protected abstract Query getQuery(Session s); - @Override - protected Object getResults(Session s, boolean isSingleResult) { - Query query = getQuery( s ).setCacheable( getQueryCacheMode() != CacheMode.IGNORE ).setCacheMode( getQueryCacheMode() ); - return ( isSingleResult ? query.uniqueResult() : query.list() ); - } - } - protected abstract class QueryExecutor { - public Object execute(boolean isSingleResult) throws Exception{ + public Object execute(boolean isSingleResult) throws Exception { Session s = openSession(); Transaction t = s.beginTransaction(); Object result = null; @@ -123,7 +120,7 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu result = getResults( s, isSingleResult ); t.commit(); } - catch ( Exception ex ) { + catch (Exception ex) { t.rollback(); throw ex; } @@ -132,6 +129,7 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu } return result; } + protected abstract Object getResults(Session s, boolean isSingleResult) throws Exception; } @@ -166,10 +164,26 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu yogiExpected.setSecretCodes( yogiSecretCodes ); s.save( yogiExpected ); - Address address1 = new Address( yogiExpected, "home", "1 Main Street", "Podunk", "WA", "98000", "USA" ); - Address address2 = new Address( yogiExpected, "work", "2 Main Street", "NotPodunk", "WA", "98001", "USA" ); + Address address1 = new Address( + yogiExpected, + "home", + "1 Main Street", + "Podunk", + "WA", + "98000", + "USA" + ); + Address address2 = new Address( + yogiExpected, + "work", + "2 Main Street", + "NotPodunk", + "WA", + "98001", + "USA" + ); yogiExpected.getAddresses().put( address1.getAddressType(), address1 ); - yogiExpected.getAddresses().put( address2.getAddressType(), address2 ); + yogiExpected.getAddresses().put( address2.getAddressType(), address2 ); s.save( address1 ); s.save( address2 ); @@ -185,8 +199,8 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu shermanEnrolmentExpected = new Enrolment(); shermanEnrolmentExpected.setCourse( courseExpected ); shermanEnrolmentExpected.setCourseCode( courseExpected.getCourseCode() ); - shermanEnrolmentExpected.setSemester( ( short ) 1 ); - shermanEnrolmentExpected.setYear( ( short ) 1999 ); + shermanEnrolmentExpected.setSemester( (short) 1 ); + shermanEnrolmentExpected.setYear( (short) 1999 ); shermanEnrolmentExpected.setStudent( shermanExpected ); shermanEnrolmentExpected.setStudentNumber( shermanExpected.getStudentNumber() ); shermanExpected.getEnrolments().add( shermanEnrolmentExpected ); @@ -195,8 +209,8 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu yogiEnrolmentExpected = new Enrolment(); yogiEnrolmentExpected.setCourse( courseExpected ); yogiEnrolmentExpected.setCourseCode( courseExpected.getCourseCode() ); - yogiEnrolmentExpected.setSemester( ( short ) 3 ); - yogiEnrolmentExpected.setYear( ( short ) 1998 ); + yogiEnrolmentExpected.setSemester( (short) 3 ); + yogiEnrolmentExpected.setYear( (short) 1998 ); yogiEnrolmentExpected.setStudent( yogiExpected ); yogiEnrolmentExpected.setStudentNumber( yogiExpected.getStudentNumber() ); yogiExpected.getEnrolments().add( yogiEnrolmentExpected ); @@ -219,11 +233,12 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu ); } - + @Test + @FailureExpected(jiraKey = "N/A", message = "Using Transformers.ALIAS_TO_ENTITY_MAP with no projection") public void testAliasToEntityMapNoProjectionList() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { @Override - protected JpaCriteriaQuery getCriteria(Session s) { + protected JpaCriteriaQuery getCriteria(Session s) { final CriteriaBuilder builder = s.getSessionFactory().getCriteriaBuilder(); final JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery( Student.class ); @@ -234,23 +249,23 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu criteria.orderBy( builder.asc( studentRoot.get( "studentNumber" ) ) ); return criteria; - } - }; - HqlExecutor hqlExecutor = new HqlExecutor() { - @Override - public Query getQuery(Session s) { - return s.createQuery( "from Student s left join s.enrolments e left join e.course c order by s.studentNumber" ) - .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP ); + /* + return s.createCriteria( Student.class, "s" ) + .createAlias( "s.enrolments", "e", CriteriaSpecification.LEFT_JOIN ) + .createAlias( "e.course", "c", CriteriaSpecification.LEFT_JOIN ) + .setResultTransformer( CriteriaSpecification.ALIAS_TO_ENTITY_MAP ) + .addOrder( Order.asc( "s.studentNumber") ); + */ } }; ResultChecker checker = results -> { - List resultList = ( List ) results; + List resultList = (List) results; assertEquals( 2, resultList.size() ); - Map yogiMap = ( Map ) resultList.get( 0 ); + Map yogiMap = (Map) resultList.get( 0 ); assertEquals( 3, yogiMap.size() ); - Map shermanMap = ( Map ) resultList.get( 1 ); + Map shermanMap = (Map) resultList.get( 1 ); assertEquals( 3, shermanMap.size() ); assertEquals( yogiExpected, yogiMap.get( "s" ) ); assertEquals( yogiEnrolmentExpected, yogiMap.get( "e" ) ); @@ -258,56 +273,62 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu assertEquals( shermanExpected, shermanMap.get( "s" ) ); assertEquals( shermanEnrolmentExpected, shermanMap.get( "e" ) ); assertEquals( courseExpected, shermanMap.get( "c" ) ); - assertSame( ( ( Map ) resultList.get( 0 ) ).get( "c" ), shermanMap.get( "c" ) ); + assertSame( ( (Map) resultList.get( 0 ) ).get( "c" ), shermanMap.get( "c" ) ); }; - runTest( hqlExecutor, criteriaExecutor, checker, false ); + runTest( criteriaExecutor, checker, false ); } @Test + @FailureExpected(jiraKey = "N/A", message = "Using Transformers.ALIAS_TO_ENTITY_MAP with no projection") public void testAliasToEntityMapNoProjectionMultiAndNullList() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { @Override - protected JpaCriteriaQuery getCriteria(Session s) { + protected JpaCriteriaQuery getCriteria(Session s) { final CriteriaBuilder builder = s.getSessionFactory().getCriteriaBuilder(); final JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery( Student.class ); final Root studentRoot = criteria.from( Student.class ); - studentRoot.join( "preferredCourse", JoinType.LEFT ); - studentRoot.join( "addresses", JoinType.LEFT ); + studentRoot.join( "preferredCourse", JoinType.LEFT ).alias( "p" ); + studentRoot.join( "addresses", JoinType.LEFT ).alias( "a" ); criteria.orderBy( builder.asc( studentRoot.get( "studentNumber" ) ) ); return criteria; - } - }; - HqlExecutor hqlExecutor = new HqlExecutor() { - @Override - public Query getQuery(Session s) { - return s.createQuery( "from Student s left join s.preferredCourse p left join s.addresses a order by s.studentNumber" ) - .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP ); + + /* + return s.createCriteria( Student.class, "s" ) + .createAlias( "s.preferredCourse", "p", CriteriaSpecification.LEFT_JOIN ) + .createAlias( "s.addresses", "a", CriteriaSpecification.LEFT_JOIN ) + .setResultTransformer( CriteriaSpecification.ALIAS_TO_ENTITY_MAP ) + .addOrder( Order.asc( "s.studentNumber" ) ); + */ } }; ResultChecker checker = results -> { - List resultList = ( List ) results; + List resultList = (List) results; assertEquals( 3, resultList.size() ); - Map yogiMap1 = ( Map ) resultList.get( 0 ); + Map yogiMap1 = (Map) resultList.get( 0 ); assertEquals( 3, yogiMap1.size() ); - Map yogiMap2 = ( Map ) resultList.get( 1 ); + Map yogiMap2 = (Map) resultList.get( 1 ); assertEquals( 3, yogiMap2.size() ); - Map shermanMap = ( Map ) resultList.get( 2 ); + Map shermanMap = (Map) resultList.get( 2 ); assertEquals( 3, shermanMap.size() ); assertEquals( yogiExpected, yogiMap1.get( "s" ) ); assertEquals( courseExpected, yogiMap1.get( "p" ) ); - Address yogiAddress1 = ( Address ) yogiMap1.get( "a" ); - assertEquals( yogiExpected.getAddresses().get( yogiAddress1.getAddressType() ), - yogiMap1.get( "a" )); + Address yogiAddress1 = (Address) yogiMap1.get( "a" ); + assertEquals( + yogiExpected.getAddresses().get( yogiAddress1.getAddressType() ), + yogiMap1.get( "a" ) + ); assertEquals( yogiExpected, yogiMap2.get( "s" ) ); assertEquals( courseExpected, yogiMap2.get( "p" ) ); - Address yogiAddress2 = ( Address ) yogiMap2.get( "a" ); - assertEquals( yogiExpected.getAddresses().get( yogiAddress2.getAddressType() ), - yogiMap2.get( "a" )); + Address yogiAddress2 = (Address) yogiMap2.get( "a" ); + assertEquals( + yogiExpected.getAddresses().get( yogiAddress2.getAddressType() ), + yogiMap2.get( "a" ) + ); assertSame( yogiMap1.get( "s" ), yogiMap2.get( "s" ) ); assertSame( yogiMap1.get( "p" ), yogiMap2.get( "p" ) ); assertFalse( yogiAddress1.getAddressType().equals( yogiAddress2.getAddressType() ) ); @@ -315,15 +336,27 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu assertEquals( shermanExpected.getPreferredCourse(), shermanMap.get( "p" ) ); assertNull( shermanMap.get( "a" ) ); }; - runTest( hqlExecutor, criteriaExecutor, checker, false ); + runTest( criteriaExecutor, checker, false ); } @Test + @FailureExpected(jiraKey = "N/A", message = "Using Transformers.ALIAS_TO_ENTITY_MAP with no projection") public void testAliasToEntityMapNoProjectionNullAndNonNullAliasList() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { @Override - protected JpaCriteriaQuery getCriteria(Session s) { - throw new NotYetImplementedFor6Exception( getClass() ); + protected JpaCriteriaQuery getCriteria(Session s) { + final CriteriaBuilder builder = s.getSessionFactory().getCriteriaBuilder(); + + final JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery( Student.class ); + + final Root studentRoot = criteria.from( Student.class ); + studentRoot.alias( "s" ); + studentRoot.join( "addresses", JoinType.LEFT ).alias( "a" ); + studentRoot.join( "preferredCourse", JoinType.INNER ); + + criteria.orderBy( builder.asc( studentRoot.get( "studentNumber" ) ) ); + return criteria; + // return s.createCriteria( Student.class, "s" ) // .createAlias( "s.addresses", "a", CriteriaSpecification.LEFT_JOIN ) // .setResultTransformer( CriteriaSpecification.ALIAS_TO_ENTITY_MAP ) @@ -331,100 +364,101 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // .addOrder( Order.asc( "s.studentNumber") ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - @Override - public Query getQuery(Session s) { - return s.createQuery( "from Student s left join s.addresses a left join s.preferredCourse order by s.studentNumber" ) - .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Map yogiMap1 = (Map) resultList.get( 0 ); + assertEquals( 2, yogiMap1.size() ); + Map yogiMap2 = (Map) resultList.get( 1 ); + assertEquals( 2, yogiMap2.size() ); + assertEquals( yogiExpected, yogiMap1.get( "s" ) ); + Address yogiAddress1 = (Address) yogiMap1.get( "a" ); + assertEquals( + yogiExpected.getAddresses().get( yogiAddress1.getAddressType() ), + yogiMap1.get( "a" ) + ); + assertEquals( yogiExpected, yogiMap2.get( "s" ) ); + Address yogiAddress2 = (Address) yogiMap2.get( "a" ); + assertEquals( + yogiExpected.getAddresses().get( yogiAddress2.getAddressType() ), + yogiMap2.get( "a" ) + ); + assertSame( yogiMap1.get( "s" ), yogiMap2.get( "s" ) ); + assertFalse( yogiAddress1.getAddressType().equals( yogiAddress2.getAddressType() ) ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - Map yogiMap1 = ( Map ) resultList.get( 0 ); - assertEquals( 2, yogiMap1.size() ); - Map yogiMap2 = ( Map ) resultList.get( 1 ); - assertEquals( 2, yogiMap2.size() ); - assertEquals( yogiExpected, yogiMap1.get( "s" ) ); - Address yogiAddress1 = ( Address ) yogiMap1.get( "a" ); - assertEquals( yogiExpected.getAddresses().get( yogiAddress1.getAddressType() ), - yogiMap1.get( "a" )); - assertEquals( yogiExpected, yogiMap2.get( "s" ) ); - Address yogiAddress2 = ( Address ) yogiMap2.get( "a" ); - assertEquals( yogiExpected.getAddresses().get( yogiAddress2.getAddressType() ), - yogiMap2.get( "a" )); - assertSame( yogiMap1.get( "s" ), yogiMap2.get( "s" ) ); - assertFalse( yogiAddress1.getAddressType().equals( yogiAddress2.getAddressType() ) ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, false ); + runTest( criteriaExecutor, checker, false ); } @Test public void testEntityWithNonLazyOneToManyUnique() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { + @Override + protected ResultTransformer getResultTransformer() { + return null; + } + + @Override protected JpaCriteriaQuery getCriteria(Session s) { // should use RootEntityTransformer by default CriteriaBuilder builder = s.getCriteriaBuilder(); JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery( Course.class ); criteria.from( Course.class ); return criteria; + // return s.createCriteria( Course.class ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "from Course" ); - } + ResultChecker checker = results -> { + assertTrue( results instanceof Course ); + assertEquals( courseExpected, results ); + assertTrue( Hibernate.isInitialized( courseExpected.getCourseMeetings() ) ); + assertEquals( courseExpected.getCourseMeetings(), courseExpected.getCourseMeetings() ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - assertTrue( results instanceof Course ); - assertEquals( courseExpected, results ); - assertTrue( Hibernate.isInitialized( courseExpected.getCourseMeetings() ) ); - assertEquals( courseExpected.getCourseMeetings(), courseExpected.getCourseMeetings() ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, true ); + runTest( criteriaExecutor, checker, true ); } @Test public void testEntityWithNonLazyManyToOneList() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { + @Override + protected ResultTransformer getResultTransformer() { + return null; + } + + @Override protected JpaCriteriaQuery getCriteria(Session s) { CriteriaBuilder builder = s.getCriteriaBuilder(); - JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery( CourseMeeting.class ); + JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery( + CourseMeeting.class ); JpaRoot root = criteria.from( CourseMeeting.class ); - criteria.orderBy( builder.asc( root.get( "id" ).get("day") ) ); + criteria.orderBy( builder.asc( root.get( "id" ).get( "day" ) ) ); return criteria; // should use RootEntityTransformer by default // return s.createCriteria( CourseMeeting.class ) // .addOrder( Order.asc( "id.day" ) ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - protected Query getQuery(Session s) { - return s.createQuery( "from CourseMeeting order by id.day" ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + assertEquals( courseMeetingExpected1, resultList.get( 0 ) ); + assertEquals( courseMeetingExpected2, resultList.get( 1 ) ); + assertTrue( Hibernate.isInitialized( ( (CourseMeeting) resultList.get( 0 ) ).getCourse() ) ); + assertTrue( Hibernate.isInitialized( ( (CourseMeeting) resultList.get( 1 ) ).getCourse() ) ); + assertEquals( courseExpected, ( (CourseMeeting) resultList.get( 0 ) ).getCourse() ); + assertEquals( courseExpected, ( (CourseMeeting) resultList.get( 1 ) ).getCourse() ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - assertEquals( courseMeetingExpected1, resultList.get( 0 ) ); - assertEquals( courseMeetingExpected2, resultList.get( 1 ) ); - assertTrue( Hibernate.isInitialized( ((CourseMeeting) resultList.get( 0 )).getCourse() ) ); - assertTrue( Hibernate.isInitialized( ((CourseMeeting) resultList.get( 1 )).getCourse() ) ); - assertEquals( courseExpected, ((CourseMeeting) resultList.get( 0 )).getCourse() ); - assertEquals( courseExpected, ((CourseMeeting) resultList.get( 1 )).getCourse() ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, false ); + runTest( criteriaExecutor, checker, false ); } @Test public void testEntityWithLazyAssnUnique() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { + @Override + protected ResultTransformer getResultTransformer() { + return null; + } + + @Override protected JpaCriteriaQuery getCriteria(Session s) { // should use RootEntityTransformer by default CriteriaBuilder builder = s.getCriteriaBuilder(); @@ -432,34 +466,32 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu Root root = criteria.from( Student.class ); criteria.where( builder.equal( root.get( "studentNumber" ), shermanExpected.getStudentNumber() ) ); return criteria; + // return s.createCriteria( Student.class, "s" ) // .add( Restrictions.eq( "studentNumber", shermanExpected.getStudentNumber() ) ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "from Student s where s.studentNumber = :studentNumber" ) - .setParameter( "studentNumber", shermanExpected.getStudentNumber() ); - } + ResultChecker checker = results -> { + assertTrue( results instanceof Student ); + assertEquals( shermanExpected, results ); + assertNotNull( ( (Student) results ).getEnrolments() ); + assertFalse( Hibernate.isInitialized( ( (Student) results ).getEnrolments() ) ); + assertNull( ( (Student) results ).getPreferredCourse() ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - assertTrue( results instanceof Student ); - assertEquals( shermanExpected, results ); - assertNotNull( ( (Student) results ).getEnrolments() ); - assertFalse( Hibernate.isInitialized( ( (Student) results ).getEnrolments() ) ); - assertNull( ( (Student) results ).getPreferredCourse() ); - } - }; - - runTest( hqlExecutor, criteriaExecutor, checker, true ); + runTest( criteriaExecutor, checker, true ); } @Test - public void testEntityWithLazyAssnList() throws Exception { + public void testEntityWithLazyAsList() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { + @Override + protected ResultTransformer getResultTransformer() { + return null; + } + + @Override protected JpaCriteriaQuery getCriteria(Session s) { // should use RootEntityTransformer by default CriteriaBuilder builder = s.getCriteriaBuilder(); @@ -467,38 +499,38 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu JpaRoot root = criteria.from( Student.class ); criteria.orderBy( builder.asc( root.get( "studentNumber" ) ) ); return criteria; + // return s.createCriteria( Student.class ) // .addOrder( Order.asc( "studentNumber" ) ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "from Student order by studentNumber" ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + assertEquals( yogiExpected, resultList.get( 0 ) ); + assertEquals( shermanExpected, resultList.get( 1 ) ); + assertNotNull( ( (Student) resultList.get( 0 ) ).getEnrolments() ); + assertNotNull( ( (Student) resultList.get( 0 ) ).getPreferredCourse() ); + assertNotNull( ( (Student) resultList.get( 1 ) ).getEnrolments() ); + assertNull( ( (Student) resultList.get( 1 ) ).getPreferredCourse() ); + assertFalse( Hibernate.isInitialized( ( (Student) resultList.get( 0 ) ).getEnrolments() ) ); + assertFalse( Hibernate.isInitialized( ( (Student) resultList.get( 0 ) ).getPreferredCourse() ) ); + assertFalse( Hibernate.isInitialized( ( (Student) resultList.get( 1 ) ).getEnrolments() ) ); + assertNull( ( (Student) resultList.get( 1 ) ).getPreferredCourse() ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - assertEquals( yogiExpected, resultList.get( 0 ) ); - assertEquals( shermanExpected, resultList.get( 1 ) ); - assertNotNull( ((Student) resultList.get( 0 )).getEnrolments() ); - assertNotNull( ( ( Student ) resultList.get( 0 ) ).getPreferredCourse() ); - assertNotNull( ( ( Student ) resultList.get( 1 ) ).getEnrolments() ); - assertNull( ( ( Student ) resultList.get( 1 ) ).getPreferredCourse() ); - assertFalse( Hibernate.isInitialized( ( ( Student ) resultList.get( 0 ) ).getEnrolments() ) ); - assertFalse( Hibernate.isInitialized( ( ( Student ) resultList.get( 0 ) ).getPreferredCourse() ) ); - assertFalse( Hibernate.isInitialized( ( ( Student ) resultList.get( 1 ) ).getEnrolments() ) ); - assertNull( ( ( Student ) resultList.get( 1 ) ).getPreferredCourse() ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, false ); + runTest( criteriaExecutor, checker, false ); } @Test public void testEntityWithUnaliasedJoinFetchedLazyOneToManySingleElementList() throws Exception { // unaliased CriteriaExecutor criteriaExecutorUnaliased = new CriteriaExecutor() { + @Override + protected ResultTransformer getResultTransformer() { + return null; + } + + @Override protected JpaCriteriaQuery getCriteria(Session s) { // should use RootEntityTransformer by default CriteriaBuilder builder = s.getCriteriaBuilder(); @@ -507,324 +539,156 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu root.fetch( "enrolments", JoinType.LEFT ); criteria.orderBy( builder.asc( root.get( "studentNumber" ) ) ); return criteria; + // return s.createCriteria( Student.class, "s" ) // .setFetchMode( "enrolments", FetchMode.JOIN ) // .addOrder( Order.asc( "s.studentNumber" ) ); } }; - HqlExecutor hqlExecutorUnaliased = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "from Student s left join fetch s.enrolments order by s.studentNumber" ); + + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + assertEquals( yogiExpected, resultList.get( 0 ) ); + assertEquals( shermanExpected, resultList.get( 1 ) ); + assertNotNull( ( (Student) resultList.get( 0 ) ).getEnrolments() ); + assertNotNull( ( (Student) resultList.get( 1 ) ).getEnrolments() ); + if ( areDynamicNonLazyAssociationsChecked() ) { + assertTrue( Hibernate.isInitialized( ( (Student) resultList.get( 0 ) ).getEnrolments() ) ); + assertEquals( yogiExpected.getEnrolments(), ( (Student) resultList.get( 0 ) ).getEnrolments() ); + assertTrue( Hibernate.isInitialized( ( (Student) resultList.get( 1 ) ).getEnrolments() ) ); + assertEquals( shermanExpected.getEnrolments(), ( (Student) resultList.get( 1 ) ).getEnrolments() ); } }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - assertEquals( yogiExpected, resultList.get( 0 ) ); - assertEquals( shermanExpected, resultList.get( 1 ) ); - assertNotNull( ( ( Student ) resultList.get( 0 ) ).getEnrolments() ); - assertNotNull( ( ( Student ) resultList.get( 1 ) ).getEnrolments() ); - if ( areDynamicNonLazyAssociationsChecked() ) { - assertTrue( Hibernate.isInitialized( ( ( Student ) resultList.get( 0 ) ).getEnrolments() ) ); - assertEquals( yogiExpected.getEnrolments(), ( ( Student ) resultList.get( 0 ) ).getEnrolments() ); - assertTrue( Hibernate.isInitialized( ( ( Student ) resultList.get( 1 ) ).getEnrolments() ) ); - assertEquals( shermanExpected.getEnrolments(), ( ( Student ) resultList.get( 1 ) ).getEnrolments() ); - } - } - }; - - runTest( hqlExecutorUnaliased, criteriaExecutorUnaliased, checker, false); + runTest( criteriaExecutorUnaliased, checker, false ); } @Test public void testJoinWithFetchJoinListCriteria() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { + @Override + protected ResultTransformer getResultTransformer() { + return null; + } + + @Override protected JpaCriteriaQuery getCriteria(Session s) { CriteriaBuilder builder = s.getCriteriaBuilder(); JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery( Student.class ); JpaRoot root = criteria.from( Student.class ); root.join( "preferredCourse", JoinType.LEFT ); - root.fetch( "enrolments" , JoinType.LEFT); + root.fetch( "enrolments", JoinType.LEFT ); criteria.orderBy( builder.asc( root.get( "studentNumber" ) ) ); return criteria; + // return s.createCriteria( Student.class, "s" ) // .createAlias( "s.preferredCourse", "pc", Criteria.LEFT_JOIN ) // .setFetchMode( "enrolments", FetchMode.JOIN ) // .addOrder( Order.asc( "s.studentNumber") ); } }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - assertEquals( yogiExpected, resultList.get( 0 ) ); - // The following fails for criteria due to HHH-3524 - //assertEquals( yogiExpected.getPreferredCourse(), ( ( Student ) resultList.get( 0 ) ).getPreferredCourse() ); - assertEquals( yogiExpected.getPreferredCourse().getCourseCode(), - ( ( Student ) resultList.get( 0 ) ).getPreferredCourse().getCourseCode() ); - assertEquals( shermanExpected, resultList.get( 1 ) ); - assertNull( ( ( Student ) resultList.get( 1 ) ).getPreferredCourse() ); - if ( areDynamicNonLazyAssociationsChecked() ) { - assertTrue( Hibernate.isInitialized( ( ( Student ) resultList.get( 0 ) ).getEnrolments() ) ); - assertEquals( yogiExpected.getEnrolments(), ( ( Student ) resultList.get( 0 ) ).getEnrolments() ); - assertTrue( Hibernate.isInitialized( ( ( Student ) resultList.get( 1 ) ).getEnrolments() ) ); - assertEquals( shermanExpected.getEnrolments(), ( ( ( Student ) resultList.get( 1 ) ).getEnrolments() ) ); - } - } - }; - runTest( null, criteriaExecutor, checker, false ); - } - - @Test - public void testJoinWithFetchJoinListHql() throws Exception { - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( - "from Student s left join fetch s.enrolments left join s.preferredCourse order by s.studentNumber" - ); - } - }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - Object[] yogiObjects = ( Object[] ) resultList.get( 0 ); - assertEquals( yogiExpected, yogiObjects[ 0 ] ); - assertEquals( yogiExpected.getPreferredCourse(), yogiObjects[ 1 ] ); - Object[] shermanObjects = ( Object[] ) resultList.get( 1 ); - assertEquals( shermanExpected, shermanObjects[ 0 ] ); - assertNull( shermanObjects[1] ); - assertNull( ((Student) shermanObjects[0]).getPreferredCourse() ); - if ( areDynamicNonLazyAssociationsChecked() ) { - assertTrue( Hibernate.isInitialized( ( ( Student ) yogiObjects[ 0 ] ).getEnrolments() ) ); - assertEquals( yogiExpected.getEnrolments(), ( ( Student ) yogiObjects[ 0 ] ).getEnrolments() ); - assertTrue( Hibernate.isInitialized( ( ( Student ) shermanObjects[ 0 ] ).getEnrolments() ) ); - assertEquals( shermanExpected.getEnrolments(), ( ( ( Student ) shermanObjects[ 0 ] ).getEnrolments() ) ); - } - } - }; - runTest( hqlExecutor, null, checker, false ); - } - - @Test - public void testJoinWithFetchJoinWithOwnerAndPropProjectedList() throws Exception { - HqlExecutor hqlSelectNewMapExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select s, s.name from Student s left join fetch s.enrolments left join s.preferredCourse order by s.studentNumber" ); - } - }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - Object[] yogiObjects = ( Object[] ) resultList.get( 0 ); - assertEquals( yogiExpected, yogiObjects[ 0 ] ); - assertEquals( yogiExpected.getName(), yogiObjects[ 1 ] ); - Object[] shermanObjects = ( Object[] ) resultList.get( 1 ); - assertEquals( shermanExpected, shermanObjects[0] ); - assertEquals( shermanExpected.getName(), shermanObjects[1] ); - if ( areDynamicNonLazyAssociationsChecked() ) { - assertTrue( Hibernate.isInitialized( ( ( Student ) yogiObjects[ 0 ] ).getEnrolments() ) ); - assertEquals( yogiExpected.getEnrolments(), ( ( Student ) yogiObjects[ 0 ] ).getEnrolments() ); - assertTrue( Hibernate.isInitialized( ( ( Student ) shermanObjects[ 0 ] ).getEnrolments() ) ); - assertEquals( shermanExpected.getEnrolments(), ( ( ( Student ) shermanObjects[ 0 ] ).getEnrolments() ) ); - } - } - }; - runTest( hqlSelectNewMapExecutor, null, checker, false ); - } - - @Test - public void testJoinWithFetchJoinWithPropAndOwnerProjectedList() throws Exception { - HqlExecutor hqlSelectNewMapExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select s.name, s from Student s left join fetch s.enrolments left join s.preferredCourse order by s.studentNumber" ); - } - }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - Object[] yogiObjects = ( Object[] ) resultList.get( 0 ); - assertEquals( yogiExpected.getName(), yogiObjects[ 0 ] ); - assertEquals( yogiExpected, yogiObjects[ 1 ] ); - Object[] shermanObjects = ( Object[] ) resultList.get( 1 ); - assertEquals( shermanExpected.getName(), shermanObjects[ 0 ] ); - assertEquals( shermanExpected, shermanObjects[1] ); - if ( areDynamicNonLazyAssociationsChecked() ) { - assertTrue( Hibernate.isInitialized( ( ( Student ) yogiObjects[ 1 ] ).getEnrolments() ) ); - assertEquals( yogiExpected.getEnrolments(), ( ( Student ) yogiObjects[ 1 ] ).getEnrolments() ); - assertTrue( Hibernate.isInitialized( ( ( Student ) shermanObjects[ 1 ] ).getEnrolments() ) ); - assertEquals( shermanExpected.getEnrolments(), ( ( ( Student ) shermanObjects[ 1 ] ).getEnrolments() ) ); - } - } - }; - runTest( hqlSelectNewMapExecutor, null, checker, false ); - } - - @Test - public void testJoinWithFetchJoinWithOwnerAndAliasedJoinedProjectedListHql() throws Exception { - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select s, pc from Student s left join fetch s.enrolments left join s.preferredCourse pc order by s.studentNumber" ); - } - }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - Object[] yogiObjects = ( Object[] ) resultList.get( 0 ); - assertEquals( yogiExpected, yogiObjects[ 0 ] ); + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + assertEquals( yogiExpected, resultList.get( 0 ) ); + // The following fails for criteria due to HHH-3524 + //assertEquals( yogiExpected.getPreferredCourse(), ( ( Student ) resultList.get( 0 ) ).getPreferredCourse() ); + assertEquals( + yogiExpected.getPreferredCourse().getCourseCode(), + ( (Student) resultList.get( 0 ) ).getPreferredCourse().getCourseCode() + ); + assertEquals( shermanExpected, resultList.get( 1 ) ); + assertNull( ( (Student) resultList.get( 1 ) ).getPreferredCourse() ); + if ( areDynamicNonLazyAssociationsChecked() ) { + assertTrue( Hibernate.isInitialized( ( (Student) resultList.get( 0 ) ).getEnrolments() ) ); + assertEquals( yogiExpected.getEnrolments(), ( (Student) resultList.get( 0 ) ).getEnrolments() ); + assertTrue( Hibernate.isInitialized( ( (Student) resultList.get( 1 ) ).getEnrolments() ) ); assertEquals( - yogiExpected.getPreferredCourse().getCourseCode(), - ( ( Course ) yogiObjects[ 1 ] ).getCourseCode() - ); - Object[] shermanObjects = ( Object[] ) resultList.get( 1 ); - assertEquals( shermanExpected, shermanObjects[ 0 ] ); - assertNull( shermanObjects[1] ); - if ( areDynamicNonLazyAssociationsChecked() ) { - assertEquals( yogiExpected.getPreferredCourse(), yogiObjects[ 1 ] ); - assertTrue( Hibernate.isInitialized( ( ( Student ) yogiObjects[ 0 ] ).getEnrolments() ) ); - assertEquals( yogiExpected.getEnrolments(), ( ( Student ) yogiObjects[ 0 ] ).getEnrolments() ); - assertTrue( Hibernate.isInitialized( ( ( Student ) shermanObjects[ 0 ] ).getEnrolments() ) ); - assertEquals( shermanExpected.getEnrolments(), ( ( ( Student ) shermanObjects[ 0 ] ).getEnrolments() ) ); - } - } - }; - runTest( hqlExecutor, null, checker, false ); - } - - @Test - public void testJoinWithFetchJoinWithAliasedJoinedAndOwnerProjectedListHql() throws Exception { - HqlExecutor hqlSelectNewMapExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( - "select pc, s from Student s left join fetch s.enrolments left join s.preferredCourse pc order by s.studentNumber" + shermanExpected.getEnrolments(), + ( ( (Student) resultList.get( 1 ) ).getEnrolments() ) ); } }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - Object[] yogiObjects = ( Object[] ) resultList.get( 0 ); - assertEquals( yogiExpected, yogiObjects[ 1 ] ); - assertEquals( - yogiExpected.getPreferredCourse().getCourseCode(), - ((Course) yogiObjects[0]).getCourseCode() - ); - Object[] shermanObjects = ( Object[] ) resultList.get( 1 ); - assertEquals( shermanExpected, shermanObjects[1] ); - assertNull( shermanObjects[0] ); - if ( areDynamicNonLazyAssociationsChecked() ) { - assertEquals( yogiExpected.getPreferredCourse(), yogiObjects[ 0 ] ); - assertTrue( Hibernate.isInitialized( ( ( Student ) yogiObjects[ 1 ] ).getEnrolments() ) ); - assertEquals( yogiExpected.getEnrolments(), ( ( Student ) yogiObjects[ 1 ] ).getEnrolments() ); - assertTrue( Hibernate.isInitialized( ( ( Student ) shermanObjects[ 1 ] ).getEnrolments() ) ); - assertEquals( shermanExpected.getEnrolments(), ( ( ( Student ) shermanObjects[ 1 ] ).getEnrolments() ) ); - } - } - }; - runTest( hqlSelectNewMapExecutor, null, checker, false ); - } - - @Test - public void testEntityWithAliasedJoinFetchedLazyOneToManySingleElementListHql() throws Exception { - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "from Student s left join fetch s.enrolments e order by s.studentNumber" ); - } - }; - - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - assertEquals( yogiExpected, resultList.get( 0 ) ); - assertEquals( - yogiExpected.getPreferredCourse().getCourseCode(), - ( ( Student ) resultList.get( 0 ) ).getPreferredCourse().getCourseCode() - ); - assertEquals( shermanExpected, resultList.get( 1 ) ); - assertNull( ( ( Student ) resultList.get( 1 ) ).getPreferredCourse() ); - if ( areDynamicNonLazyAssociationsChecked() ) { - assertTrue( Hibernate.isInitialized( ( ( Student ) resultList.get( 0 ) ).getEnrolments() ) ); - assertEquals( yogiExpected.getEnrolments(), ( ( Student ) resultList.get( 0 ) ).getEnrolments() ); - assertTrue( Hibernate.isInitialized( ( ( Student ) resultList.get( 1 ) ).getEnrolments() ) ); - assertEquals( shermanExpected.getEnrolments(), ( ( ( Student ) resultList.get( 1 ) ).getEnrolments() ) ); - } - } - }; - - runTest( hqlExecutor, null, checker, false); + runTest( criteriaExecutor, checker, false ); } @Test public void testEntityWithSelectFetchedLazyOneToManySingleElementListCriteria() throws Exception { CriteriaExecutor criteriaExecutorUnaliased = new CriteriaExecutor() { + @Override + protected ResultTransformer getResultTransformer() { + return null; + } + + @Override protected JpaCriteriaQuery getCriteria(Session s) { - // should use RootEntityTransformer by default CriteriaBuilder builder = s.getCriteriaBuilder(); JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery( Student.class ); JpaRoot root = criteria.from( Student.class ); root.join( "enrolments" ); criteria.orderBy( builder.asc( root.get( "studentNumber" ) ) ); return criteria; + // return s.createCriteria( Student.class, "s" ) // .setFetchMode( "enrolments", FetchMode.SELECT ) // .addOrder( Order.asc( "s.studentNumber" ) ); } }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - assertEquals( yogiExpected, resultList.get( 0 ) ); - assertEquals( shermanExpected, resultList.get( 1 ) ); - assertNotNull( ((Student) resultList.get( 0 )).getEnrolments() ); - assertFalse( Hibernate.isInitialized( ((Student) resultList.get( 0 )).getEnrolments() ) ); - assertNotNull( ( ( Student ) resultList.get( 1 ) ).getEnrolments() ); - assertFalse( Hibernate.isInitialized( ( ( Student ) resultList.get( 1 ) ).getEnrolments() ) ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + assertEquals( yogiExpected, resultList.get( 0 ) ); + assertEquals( shermanExpected, resultList.get( 1 ) ); + assertNotNull( ( (Student) resultList.get( 0 ) ).getEnrolments() ); + assertFalse( Hibernate.isInitialized( ( (Student) resultList.get( 0 ) ).getEnrolments() ) ); + assertNotNull( ( (Student) resultList.get( 1 ) ).getEnrolments() ); + assertFalse( Hibernate.isInitialized( ( (Student) resultList.get( 1 ) ).getEnrolments() ) ); }; - runTest( null, criteriaExecutorUnaliased, checker, false); + runTest( criteriaExecutorUnaliased, checker, false ); } @Test public void testEntityWithJoinFetchedLazyOneToManyMultiAndNullElementList() throws Exception { //unaliased CriteriaExecutor criteriaExecutorUnaliased = new CriteriaExecutor() { + + @Override + protected ResultTransformer getResultTransformer() { + return null; + } + + @Override protected JpaCriteriaQuery getCriteria(Session s) { // should use RootEntityTransformer by default CriteriaBuilder builder = s.getCriteriaBuilder(); JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery( Student.class ); JpaRoot root = criteria.from( Student.class ); root.fetch( "addresses", JoinType.LEFT ); + criteria.orderBy( builder.asc( root.get( "studentNumber" ) ) ); return criteria; + // return s.createCriteria( Student.class, "s" ) // .setFetchMode( "addresses", FetchMode.JOIN ) // .addOrder( Order.asc( "s.studentNumber") ); } }; - HqlExecutor hqlExecutorUnaliased = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "from Student s left join fetch s.addresses order by s.studentNumber" ); - } - }; // //aliased // CriteriaExecutor criteriaExecutorAliased1 = new CriteriaExecutor() { +// @Override // protected JpaCriteriaQuery getCriteria(Session s) { // // should use RootEntityTransformer by default // CriteriaBuilder builder = s.getCriteriaBuilder(); // JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery( Student.class ); // JpaRoot root = criteria.from( Student.class ); +// root.fetch( "addresses", JoinType.LEFT ); +// criteria.orderBy( builder.asc( root.get( "studentNumber" ) ) ); // +// return criteria; //// return s.createCriteria( Student.class, "s" ) //// .createAlias( "s.addresses", "a", Criteria.LEFT_JOIN ) //// .setFetchMode( "addresses", FetchMode.JOIN ) @@ -834,158 +698,175 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // CriteriaExecutor criteriaExecutorAliased2 = new CriteriaExecutor() { // protected JpaCriteriaQuery getCriteria(Session s) { // // should use RootEntityTransformer by default -// return s.createCriteria( Student.class, "s" ) -// .createAlias( "s.addresses", "a", Criteria.LEFT_JOIN ) -// .setFetchMode( "a", FetchMode.JOIN ) -// .addOrder( Order.asc( "s.studentNumber") ); +//// return s.createCriteria( Student.class, "s" ) +//// .createAlias( "s.addresses", "a", Criteria.LEFT_JOIN ) +//// .setFetchMode( "a", FetchMode.JOIN ) +//// .addOrder( Order.asc( "s.studentNumber") ); // } // }; // CriteriaExecutor criteriaExecutorAliased3 = new CriteriaExecutor() { // protected JpaCriteriaQuery getCriteria(Session s) { // // should use RootEntityTransformer by default -// return s.createCriteria( Student.class, "s" ) -// .createCriteria( "s.addresses", "a", Criteria.LEFT_JOIN ) -// .setFetchMode( "addresses", FetchMode.JOIN ) -// .addOrder( Order.asc( "s.studentNumber") ); +//// return s.createCriteria( Student.class, "s" ) +//// .createCriteria( "s.addresses", "a", Criteria.LEFT_JOIN ) +//// .setFetchMode( "addresses", FetchMode.JOIN ) +//// .addOrder( Order.asc( "s.studentNumber") ); // } // }; // CriteriaExecutor criteriaExecutorAliased4 = new CriteriaExecutor() { // protected JpaCriteriaQuery getCriteria(Session s) { // // should use RootEntityTransformer by default -// return s.createCriteria( Student.class, "s" ) -// .createCriteria( "s.addresses", "a", Criteria.LEFT_JOIN ) -// .setFetchMode( "a", FetchMode.JOIN ) -// .addOrder( Order.asc( "s.studentNumber") ); +//// return s.createCriteria( Student.class, "s" ) +//// .createCriteria( "s.addresses", "a", Criteria.LEFT_JOIN ) +//// .setFetchMode( "a", FetchMode.JOIN ) +//// .addOrder( Order.asc( "s.studentNumber") ); // } // }; - HqlExecutor hqlExecutorAliased = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "from Student s left join fetch s.addresses a order by s.studentNumber" ); - } - }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 3, resultList.size() ); - assertEquals( yogiExpected, resultList.get( 0 ) ); - assertSame( resultList.get( 0 ), resultList.get( 1 ) ); - assertEquals( shermanExpected, resultList.get( 2 ) ); - assertNotNull( ( ( Student ) resultList.get( 0 ) ).getAddresses() ); - assertNotNull( ( ( Student ) resultList.get( 1 ) ).getAddresses() ); - assertNotNull( ( ( Student ) resultList.get( 2 ) ).getAddresses() ); - if ( areDynamicNonLazyAssociationsChecked() ) { - assertTrue( Hibernate.isInitialized( ( ( Student ) resultList.get( 0 ) ).getAddresses() ) ); - assertEquals( yogiExpected.getAddresses(), ( ( Student ) resultList.get( 0 ) ).getAddresses() ); - assertTrue( ( ( Student ) resultList.get( 2 ) ).getAddresses().isEmpty() ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + assertEquals( yogiExpected, resultList.get( 0 ) ); + assertEquals( shermanExpected, resultList.get( 1 ) ); + assertNotNull( ( (Student) resultList.get( 0 ) ).getAddresses() ); + assertNotNull( ( (Student) resultList.get( 1 ) ).getAddresses() ); + if ( areDynamicNonLazyAssociationsChecked() ) { + assertTrue( Hibernate.isInitialized( ( (Student) resultList.get( 0 ) ).getAddresses() ) ); + assertEquals( yogiExpected.getAddresses(), ( (Student) resultList.get( 0 ) ).getAddresses() ); + assertTrue( ( (Student) resultList.get( 1 ) ).getAddresses().isEmpty() ); } }; - runTest( hqlExecutorUnaliased, criteriaExecutorUnaliased, checker, false ); - runTest( hqlExecutorAliased, null, checker, false ); -// runTest( null, criteriaExecutorAliased2, checker, false ); -// runTest( null, criteriaExecutorAliased3, checker, false ); -// runTest( null, criteriaExecutorAliased4, checker, false ); + runTest( criteriaExecutorUnaliased, checker, false ); +// runTest( criteriaExecutorAliased2, checker, false ); +// runTest( criteriaExecutorAliased3, checker, false ); +// runTest( criteriaExecutorAliased4, checker, false ); } @Test public void testEntityWithJoinFetchedLazyManyToOneList() throws Exception { // unaliased CriteriaExecutor criteriaExecutorUnaliased = new CriteriaExecutor() { + @Override + protected ResultTransformer getResultTransformer() { + // should use RootEntityTransformer by default + return null; + } + + @Override protected JpaCriteriaQuery getCriteria(Session s) { // should use RootEntityTransformer by default CriteriaBuilder builder = s.getCriteriaBuilder(); JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery( Student.class ); + JpaRoot root = criteria.from( Student.class ); root.fetch( "preferredCourse", JoinType.LEFT ); + criteria.orderBy( builder.asc( root.get( "studentNumber" ) ) ); return criteria; + // return s.createCriteria( Student.class, "s" ) // .setFetchMode( "preferredCourse", FetchMode.JOIN ) // .addOrder( Order.asc( "s.studentNumber") ); } }; - HqlExecutor hqlExecutorUnaliased = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "from Student s left join fetch s.preferredCourse order by s.studentNumber" ); - } - }; // aliased // CriteriaExecutor criteriaExecutorAliased1 = new CriteriaExecutor() { -// protected JpaCriteriaQuery getCriteria(Session s) { +// @Override +// protected ResultTransformer getResultTransformer() { // // should use RootEntityTransformer by default -// return s.createCriteria( Student.class, "s" ) -// .createAlias( "s.preferredCourse", "pCourse", Criteria.LEFT_JOIN ) -// .setFetchMode( "preferredCourse", FetchMode.JOIN ) -// .addOrder( Order.asc( "s.studentNumber") ); +// return null; +// } +// +// @Override +// protected JpaCriteriaQuery getCriteria(Session s) { +// CriteriaBuilder builder = s.getCriteriaBuilder(); +// JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery( Student.class ); +// +// JpaRoot root = criteria.from( Student.class ); +// root.join( "preferredCourse" ).alias( "pCourse" ); +// root.fetch( "pCourse", JoinType.LEFT ); +// +// criteria.orderBy( builder.asc( root.get( "studentNumber" ) ) ); +// return criteria; +// // should use RootEntityTransformer by default +//// return s.createCriteria( Student.class, "s" ) +//// .createAlias( "s.preferredCourse", "pCourse", Criteria.LEFT_JOIN ) +//// .setFetchMode( "preferredCourse", FetchMode.JOIN ) +//// .addOrder( Order.asc( "s.studentNumber") ); // } // }; // CriteriaExecutor criteriaExecutorAliased2 = new CriteriaExecutor() { // protected JpaCriteriaQuery getCriteria(Session s) { // // should use RootEntityTransformer by default -// return s.createCriteria( Student.class, "s" ) -// .createAlias( "s.preferredCourse", "pCourse", Criteria.LEFT_JOIN ) -// .setFetchMode( "pCourse", FetchMode.JOIN ) -// .addOrder( Order.asc( "s.studentNumber") ); +//// return s.createCriteria( Student.class, "s" ) +//// .createAlias( "s.preferredCourse", "pCourse", Criteria.LEFT_JOIN ) +//// .setFetchMode( "pCourse", FetchMode.JOIN ) +//// .addOrder( Order.asc( "s.studentNumber") ); // } // }; // CriteriaExecutor criteriaExecutorAliased3 = new CriteriaExecutor() { // protected JpaCriteriaQuery getCriteria(Session s) { // // should use RootEntityTransformer by default -// return s.createCriteria( Student.class, "s" ) -// .createCriteria( "s.preferredCourse", "pCourse", Criteria.LEFT_JOIN ) -// .setFetchMode( "preferredCourse", FetchMode.JOIN ) -// .addOrder( Order.asc( "s.studentNumber") ); +//// return s.createCriteria( Student.class, "s" ) +//// .createCriteria( "s.preferredCourse", "pCourse", Criteria.LEFT_JOIN ) +//// .setFetchMode( "preferredCourse", FetchMode.JOIN ) +//// .addOrder( Order.asc( "s.studentNumber") ); // } // }; // CriteriaExecutor criteriaExecutorAliased4 = new CriteriaExecutor() { // protected JpaCriteriaQuery getCriteria(Session s) { // // should use RootEntityTransformer by default -// return s.createCriteria( Student.class, "s" ) -// .createCriteria( "s.preferredCourse", "pCourse", Criteria.LEFT_JOIN ) -// .setFetchMode( "pCourse", FetchMode.JOIN ) -// .addOrder( Order.asc( "s.studentNumber") ); +//// return s.createCriteria( Student.class, "s" ) +//// .createCriteria( "s.preferredCourse", "pCourse", Criteria.LEFT_JOIN ) +//// .setFetchMode( "pCourse", FetchMode.JOIN ) +//// .addOrder( Order.asc( "s.studentNumber") ); // } // }; - HqlExecutor hqlExecutorAliased = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "from Student s left join fetch s.preferredCourse pCourse order by s.studentNumber" ); - } - }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - assertEquals( yogiExpected, resultList.get( 0 ) ); - assertEquals( shermanExpected, resultList.get( 1 ) ); - assertEquals( yogiExpected.getPreferredCourse().getCourseCode(), - ( ( Student ) resultList.get( 0 ) ).getPreferredCourse().getCourseCode() ); - assertNull( ((Student) resultList.get( 1 )).getPreferredCourse() ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + assertEquals( yogiExpected, resultList.get( 0 ) ); + assertEquals( shermanExpected, resultList.get( 1 ) ); + assertEquals( + yogiExpected.getPreferredCourse().getCourseCode(), + ( (Student) resultList.get( 0 ) ).getPreferredCourse().getCourseCode() + ); + assertNull( ( (Student) resultList.get( 1 ) ).getPreferredCourse() ); }; - runTest( hqlExecutorUnaliased, criteriaExecutorUnaliased, checker, false ); - runTest( hqlExecutorAliased, null, checker, false ); -// runTest( null, criteriaExecutorAliased2, checker, false ); -// runTest( null, criteriaExecutorAliased3, checker, false ); -// runTest( null, criteriaExecutorAliased4, checker, false ); + runTest( criteriaExecutorUnaliased, checker, false ); +// runTest( criteriaExecutorAliased2, checker, false ); +// runTest( criteriaExecutorAliased3, checker, false ); +// runTest( criteriaExecutorAliased4, checker, false ); } @Test public void testEntityWithJoinFetchedLazyManyToOneUsingProjectionList() throws Exception { // unaliased CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { + @Override + protected ResultTransformer getResultTransformer() { + return null; + } + + @Override protected JpaCriteriaQuery getCriteria(Session s) { - // should use RootEntityTransformer by default CriteriaBuilder builder = s.getCriteriaBuilder(); - JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery( Object.class ); + JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery( Object[].class ); Root root = criteria.from( Enrolment.class ); - Fetch student = root.fetch( "student", JoinType.LEFT ); - student.fetch( "preferredCourse", JoinType.LEFT ); - criteria.orderBy( builder.asc( ((Join)student).get( "studentNumber" ) ) ); - criteria.multiselect( ((Join)student).get( "name" ), root.get("student") ); + +// Fetch student = root.fetch( "student", JoinType.LEFT ); +// student.fetch( "preferredCourse", JoinType.LEFT ); + + criteria.multiselect( + root.get( "student" ).get( "name" ).alias( "name" ), + root.get( "student" ).alias( "student" ) + ); + + criteria.orderBy( builder.asc( root.get( "student" ).get( "studentNumber" ) ) ); return criteria; +// // return s.createCriteria( Enrolment.class, "e" ) // .createAlias( "e.student", "s", Criteria.LEFT_JOIN ) // .setFetchMode( "student", FetchMode.JOIN ) @@ -998,49 +879,48 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // .addOrder( Order.asc( "s.studentNumber") ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( - "select s.name, s from Enrolment e left join e.student s left join fetch s.preferredCourse order by s.studentNumber" - ); - } - }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - Object[] yogiObjects = ( Object[] ) resultList.get( 0 ); - Object[] shermanObjects = ( Object[] ) resultList.get( 1 ); - assertEquals( yogiExpected.getName(), yogiObjects[ 0 ] ); - assertEquals( shermanExpected.getName(), shermanObjects[ 0 ] ); + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Object[] yogiObjects = (Object[]) resultList.get( 0 ); + Object[] shermanObjects = (Object[]) resultList.get( 1 ); + assertEquals( yogiExpected.getName(), yogiObjects[0] ); + assertEquals( shermanExpected.getName(), shermanObjects[0] ); + // The following fails for criteria due to HHH-1425 + // assertEquals( yogiExpected, yogiObjects[ 1 ] ); + // assertEquals( shermanExpected, shermanObjects[ 1 ] ); + assertEquals( yogiExpected.getStudentNumber(), ( (Student) yogiObjects[1] ).getStudentNumber() ); + assertEquals( shermanExpected.getStudentNumber(), ( (Student) shermanObjects[1] ).getStudentNumber() ); + if ( areDynamicNonLazyAssociationsChecked() ) { // The following fails for criteria due to HHH-1425 - // assertEquals( yogiExpected, yogiObjects[ 1 ] ); - // assertEquals( shermanExpected, shermanObjects[ 1 ] ); - assertEquals( yogiExpected.getStudentNumber(), ( ( Student ) yogiObjects[ 1 ] ).getStudentNumber() ); - assertEquals( shermanExpected.getStudentNumber(), ( ( Student ) shermanObjects[ 1 ] ).getStudentNumber() ); - if ( areDynamicNonLazyAssociationsChecked() ) { - // The following fails for criteria due to HHH-1425 - //assertTrue( Hibernate.isInitialized( ( ( Student ) yogiObjects[ 1 ] ).getPreferredCourse() ) ); - //assertEquals( yogiExpected.getPreferredCourse(), ( ( Student ) yogiObjects[ 1 ] ).getPreferredCourse() ); - //assertTrue( Hibernate.isInitialized( ( ( Student ) shermanObjects[ 1 ] ).getPreferredCourse() ) ); - //assertEquals( shermanExpected.getPreferredCourse(), ( ( Student ) shermanObjects[ 1 ] ).getPreferredCourse() ); - } + //assertTrue( Hibernate.isInitialized( ( ( Student ) yogiObjects[ 1 ] ).getPreferredCourse() ) ); + //assertEquals( yogiExpected.getPreferredCourse(), ( ( Student ) yogiObjects[ 1 ] ).getPreferredCourse() ); + //assertTrue( Hibernate.isInitialized( ( ( Student ) shermanObjects[ 1 ] ).getPreferredCourse() ) ); + //assertEquals( shermanExpected.getPreferredCourse(), ( ( Student ) shermanObjects[ 1 ] ).getPreferredCourse() ); } }; - runTest( hqlExecutor, criteriaExecutor, checker, false ); + runTest( criteriaExecutor, checker, false ); } @Test public void testEntityWithJoinedLazyOneToManySingleElementListCriteria() throws Exception { CriteriaExecutor criteriaExecutorUnaliased = new CriteriaExecutor() { + + @Override + protected ResultTransformer getResultTransformer() { + return RootEntityResultTransformer.INSTANCE; + } + + @Override protected JpaCriteriaQuery getCriteria(Session s) { - // should use RootEntityTransformer by default CriteriaBuilder builder = s.getCriteriaBuilder(); + JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery( Student.class ); Root root = criteria.from( Student.class ); - root.join( "enrolments", JoinType.LEFT ); + root.fetch( "enrolments", JoinType.LEFT ); criteria.orderBy( builder.asc( root.get( "studentNumber" ) ) ); return criteria; + // return s.createCriteria( Student.class, "s" ) // .createCriteria( "s.enrolments", Criteria.LEFT_JOIN ) // .addOrder( Order.asc( "s.studentNumber") ); @@ -1049,49 +929,54 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // CriteriaExecutor criteriaExecutorAliased1 = new CriteriaExecutor() { // protected JpaCriteriaQuery getCriteria(Session s) { // // should use RootEntityTransformer by default -// return s.createCriteria( Student.class, "s" ) -// .createCriteria( "s.enrolments", "e", Criteria.LEFT_JOIN ) -// .addOrder( Order.asc( "s.studentNumber") ); +//// return s.createCriteria( Student.class, "s" ) +//// .createCriteria( "s.enrolments", "e", Criteria.LEFT_JOIN ) +//// .addOrder( Order.asc( "s.studentNumber") ); // } // }; // CriteriaExecutor criteriaExecutorAliased2 = new CriteriaExecutor() { // protected JpaCriteriaQuery getCriteria(Session s) { // // should use RootEntityTransformer by default -// return s.createCriteria( Student.class, "s" ) -// .createAlias( "s.enrolments", "e", Criteria.LEFT_JOIN ) -// .addOrder( Order.asc( "s.studentNumber") ); +//// return s.createCriteria( Student.class, "s" ) +//// .createAlias( "s.enrolments", "e", Criteria.LEFT_JOIN ) +//// .addOrder( Order.asc( "s.studentNumber") ); // } // }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - assertEquals( yogiExpected, resultList.get( 0 ) ); - assertEquals( shermanExpected, resultList.get( 1 ) ); - assertNotNull( ( ( Student ) resultList.get( 0 ) ).getEnrolments() ); - assertNotNull( ( ( Student ) resultList.get( 1 ) ).getEnrolments() ); - if ( areDynamicNonLazyAssociationsChecked() ) { - assertTrue( Hibernate.isInitialized( ( ( Student ) resultList.get( 0 ) ).getEnrolments() ) ); - assertEquals( yogiExpected.getEnrolments(), ( ( Student ) resultList.get( 0 ) ).getEnrolments() ); - assertTrue( Hibernate.isInitialized( ( ( Student ) resultList.get( 1 ) ).getEnrolments() ) ); - assertEquals( shermanExpected.getEnrolments(), ( ( Student ) resultList.get( 1 ) ).getEnrolments() ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + assertEquals( yogiExpected, resultList.get( 0 ) ); + assertEquals( shermanExpected, resultList.get( 1 ) ); + assertNotNull( ( (Student) resultList.get( 0 ) ).getEnrolments() ); + assertNotNull( ( (Student) resultList.get( 1 ) ).getEnrolments() ); + if ( areDynamicNonLazyAssociationsChecked() ) { + assertTrue( Hibernate.isInitialized( ( (Student) resultList.get( 0 ) ).getEnrolments() ) ); + assertEquals( yogiExpected.getEnrolments(), ( (Student) resultList.get( 0 ) ).getEnrolments() ); + assertTrue( Hibernate.isInitialized( ( (Student) resultList.get( 1 ) ).getEnrolments() ) ); + assertEquals( shermanExpected.getEnrolments(), ( (Student) resultList.get( 1 ) ).getEnrolments() ); } }; - runTest( null, criteriaExecutorUnaliased, checker, false ); -// runTest( null, criteriaExecutorAliased1, checker, false ); -// runTest( null, criteriaExecutorAliased2, checker, false ); + runTest( criteriaExecutorUnaliased, checker, false ); +// runTest( criteriaExecutorAliased1, checker, false ); +// runTest( criteriaExecutorAliased2, checker, false ); } @Test public void testEntityWithJoinedLazyOneToManyMultiAndNullListCriteria() throws Exception { CriteriaExecutor criteriaExecutorUnaliased = new CriteriaExecutor() { + + @Override + protected ResultTransformer getResultTransformer() throws Exception { + return null; + } + + @Override protected JpaCriteriaQuery getCriteria(Session s) { // should use RootEntityTransformer by default CriteriaBuilder builder = s.getCriteriaBuilder(); JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery( Student.class ); Root root = criteria.from( Student.class ); - root.join( "addresses", JoinType.LEFT ); + root.fetch( "addresses", JoinType.LEFT ); criteria.orderBy( builder.asc( root.get( "studentNumber" ) ) ); return criteria; // return s.createCriteria( Student.class, "s" ) @@ -1102,46 +987,48 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // CriteriaExecutor criteriaExecutorAliased1 = new CriteriaExecutor() { // protected JpaCriteriaQuery getCriteria(Session s) { // // should use RootEntityTransformer by default -// return s.createCriteria( Student.class, "s" ) -// .createCriteria( "s.addresses", "a", Criteria.LEFT_JOIN ) -// .addOrder( Order.asc( "s.studentNumber") ); +//// return s.createCriteria( Student.class, "s" ) +//// .createCriteria( "s.addresses", "a", Criteria.LEFT_JOIN ) +//// .addOrder( Order.asc( "s.studentNumber") ); // } // }; // CriteriaExecutor criteriaExecutorAliased2 = new CriteriaExecutor() { // protected JpaCriteriaQuery getCriteria(Session s) { // // should use RootEntityTransformer by default -// return s.createCriteria( Student.class, "s" ) -// .createAlias( "s.addresses", "a", Criteria.LEFT_JOIN ) -// .addOrder( Order.asc( "s.studentNumber") ); +//// return s.createCriteria( Student.class, "s" ) +//// .createAlias( "s.addresses", "a", Criteria.LEFT_JOIN ) +//// .addOrder( Order.asc( "s.studentNumber") ); // } // }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 3, resultList.size() ); - assertEquals( yogiExpected, resultList.get( 0 ) ); - assertSame( resultList.get( 0 ), resultList.get( 1 ) ); - assertEquals( shermanExpected, resultList.get( 2 ) ); - assertNotNull( ( ( Student ) resultList.get( 0 ) ).getAddresses() ); - assertNotNull( ( ( Student ) resultList.get( 2 ) ).getAddresses() ); - assertNotNull( ( ( Student ) resultList.get( 1 ) ).getAddresses() ); - if ( areDynamicNonLazyAssociationsChecked() ) { - assertTrue( Hibernate.isInitialized( ( ( Student ) resultList.get( 0 ) ).getAddresses() ) ); - assertEquals( yogiExpected.getAddresses(), ( ( Student ) resultList.get( 0 ) ).getAddresses() ); - assertTrue( ( ( Student ) resultList.get( 2 ) ).getAddresses().isEmpty() ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + assertEquals( yogiExpected, resultList.get( 0 ) ); + assertEquals( shermanExpected, resultList.get( 1 ) ); + assertNotNull( ( (Student) resultList.get( 0 ) ).getAddresses() ); + assertNotNull( ( (Student) resultList.get( 1 ) ).getAddresses() ); + if ( areDynamicNonLazyAssociationsChecked() ) { + assertTrue( Hibernate.isInitialized( ( (Student) resultList.get( 0 ) ).getAddresses() ) ); + assertEquals( yogiExpected.getAddresses(), ( (Student) resultList.get( 0 ) ).getAddresses() ); + assertTrue( ( (Student) resultList.get( 1 ) ).getAddresses().isEmpty() ); } }; - runTest( null, criteriaExecutorUnaliased, checker, false ); -// runTest( null, criteriaExecutorAliased1, checker, false ); -// runTest( null, criteriaExecutorAliased2, checker, false ); + runTest( criteriaExecutorUnaliased, checker, false ); +// runTest( criteriaExecutorAliased1, checker, false ); +// runTest( criteriaExecutorAliased2, checker, false ); } @Test public void testEntityWithJoinedLazyManyToOneListCriteria() throws Exception { CriteriaExecutor criteriaExecutorUnaliased = new CriteriaExecutor() { + + @Override + protected ResultTransformer getResultTransformer() throws Exception { + return null; + } + + @Override protected JpaCriteriaQuery getCriteria(Session s) { - // should use RootEntityTransformer by default CriteriaBuilder builder = s.getCriteriaBuilder(); JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery( Student.class ); Root root = criteria.from( Student.class ); @@ -1156,172 +1043,98 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // CriteriaExecutor criteriaExecutorAliased1 = new CriteriaExecutor() { // protected JpaCriteriaQuery getCriteria(Session s) { // // should use RootEntityTransformer by default -// return s.createCriteria( Student.class, "s" ) -// .createCriteria( "s.preferredCourse", "p", Criteria.LEFT_JOIN ) -// .addOrder( Order.asc( "s.studentNumber") ); +//// return s.createCriteria( Student.class, "s" ) +//// .createCriteria( "s.preferredCourse", "p", Criteria.LEFT_JOIN ) +//// .addOrder( Order.asc( "s.studentNumber") ); // } // }; // CriteriaExecutor criteriaExecutorAliased2 = new CriteriaExecutor() { // protected JpaCriteriaQuery getCriteria(Session s) { // // should use RootEntityTransformer by default -// return s.createCriteria( Student.class, "s" ) -// .createAlias( "s.preferredCourse", "p", Criteria.LEFT_JOIN ) -// .addOrder( Order.asc( "s.studentNumber") ); +//// return s.createCriteria( Student.class, "s" ) +//// .createAlias( "s.preferredCourse", "p", Criteria.LEFT_JOIN ) +//// .addOrder( Order.asc( "s.studentNumber") ); // } // }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - assertEquals( yogiExpected, resultList.get( 0 ) ); - assertEquals( shermanExpected, resultList.get( 1 ) ); - assertEquals( yogiExpected.getPreferredCourse().getCourseCode(), - ( ( Student ) resultList.get( 0 ) ).getPreferredCourse().getCourseCode() ); - assertNull( ( ( Student ) resultList.get( 1 ) ).getPreferredCourse() ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + assertEquals( yogiExpected, resultList.get( 0 ) ); + assertEquals( shermanExpected, resultList.get( 1 ) ); + assertEquals( + yogiExpected.getPreferredCourse().getCourseCode(), + ( (Student) resultList.get( 0 ) ).getPreferredCourse().getCourseCode() + ); + assertNull( ( (Student) resultList.get( 1 ) ).getPreferredCourse() ); }; - runTest( null, criteriaExecutorUnaliased, checker, false ); -// runTest( null, criteriaExecutorAliased1, checker, false ); -// runTest( null, criteriaExecutorAliased2, checker, false ); + runTest( criteriaExecutorUnaliased, checker, false ); +// runTest( criteriaExecutorAliased1, checker, false ); +// runTest( criteriaExecutorAliased2, checker, false ); } - @Test - public void testEntityWithJoinedLazyOneToManySingleElementListHql() throws Exception { - HqlExecutor hqlExecutorUnaliased = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "from Student s left join s.enrolments order by s.studentNumber" ); - } - }; - HqlExecutor hqlExecutorAliased = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "from Student s left join s.enrolments e order by s.studentNumber" ); - } - }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - assertTrue( resultList.get( 0 ) instanceof Object[] ); - Object[] yogiObjects = ( Object[] ) resultList.get( 0 ); - assertEquals( yogiExpected, yogiObjects[ 0 ] ); - assertEquals( yogiEnrolmentExpected, yogiObjects[ 1 ] ); - assertTrue( resultList.get( 0 ) instanceof Object[] ); - Object[] shermanObjects = ( Object[] ) resultList.get( 1 ); - assertEquals( shermanExpected, shermanObjects[ 0 ] ); - assertEquals( shermanEnrolmentExpected, shermanObjects[ 1 ] ); - } - }; - runTest( hqlExecutorUnaliased, null, checker, false ); - runTest( hqlExecutorAliased, null, checker, false ); - } - - @Test - public void testEntityWithJoinedLazyOneToManyMultiAndNullListHql() throws Exception { - HqlExecutor hqlExecutorUnaliased = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "from Student s left join s.addresses order by s.studentNumber" ); - } - }; - HqlExecutor hqlExecutorAliased = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "from Student s left join s.addresses a order by s.studentNumber" ); - } - }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 3, resultList.size() ); - assertTrue( resultList.get( 0 ) instanceof Object[] ); - Object[] yogiObjects1 = ( Object[] ) resultList.get( 0 ); - assertEquals( yogiExpected, yogiObjects1[ 0 ] ); - Address address1 = ( Address ) yogiObjects1[ 1 ]; - assertEquals( yogiExpected.getAddresses().get( address1.getAddressType() ), address1 ); - Object[] yogiObjects2 = ( Object[] ) resultList.get( 1 ); - assertSame( yogiObjects1[ 0 ], yogiObjects2[ 0 ] ); - Address address2 = ( Address ) yogiObjects2[ 1 ]; - assertEquals( yogiExpected.getAddresses().get( address2.getAddressType() ), address2 ); - assertFalse( address1.getAddressType().equals( address2.getAddressType() ) ); - Object[] shermanObjects = ( Object[] ) resultList.get( 2 ); - assertEquals( shermanExpected, shermanObjects[ 0 ] ); - assertNull( shermanObjects[ 1 ] ); - } - }; - runTest( hqlExecutorUnaliased, null, checker, false ); - runTest( hqlExecutorAliased, null, checker, false ); - } - - @Test - public void testEntityWithJoinedLazyManyToOneListHql() throws Exception { - HqlExecutor hqlExecutorUnaliased = new HqlExecutor() { - protected Query getQuery(Session s) { - // should use RootEntityTransformer by default - return s.createQuery( "from Student s left join s.preferredCourse order by s.studentNumber" ); - } - }; - HqlExecutor hqlExecutorAliased = new HqlExecutor() { - protected Query getQuery(Session s) { - // should use RootEntityTransformer by default - return s.createQuery( "from Student s left join s.preferredCourse p order by s.studentNumber" ); - } - }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - Object[] yogiObjects = ( Object[] ) resultList.get( 0 ); - assertEquals( yogiExpected, yogiObjects[ 0 ] ); - assertEquals( yogiExpected.getPreferredCourse(), yogiObjects[ 1 ] ); - Object[] shermanObjects = ( Object[] ) resultList.get( 1 ); - assertEquals( shermanExpected, shermanObjects[ 0 ] ); - assertNull( shermanObjects[ 1 ] ); - } - }; - runTest( hqlExecutorUnaliased, null, checker, false ); - runTest( hqlExecutorAliased, null, checker, false ); - } @Test public void testAliasToEntityMapOneProjectionList() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { + @Override protected JpaCriteriaQuery getCriteria(Session s) { - throw new NotYetImplementedFor6Exception( getClass() ); + CriteriaBuilder builder = s.getCriteriaBuilder(); + JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery(); + Root root = criteria.from( Enrolment.class ); + criteria.select( root.get( "student" ).alias( "student" ) ); + + criteria.orderBy( builder.asc( root.get( "studentNumber" ) ) ); + return criteria; + // return s.createCriteria( Enrolment.class, "e" ) // .setProjection( Projections.property( "e.student" ).as( "student" ) ) // .addOrder( Order.asc( "e.studentNumber") ) // .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select e.student as student from Enrolment e order by e.studentNumber" ) - .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Map yogiMap = (Map) resultList.get( 0 ); + Map shermanMap = (Map) resultList.get( 1 ); + assertEquals( 1, yogiMap.size() ); + assertEquals( 1, shermanMap.size() ); + // TODO: following are initialized for hql and uninitialied for criteria; why? + // assertFalse( Hibernate.isInitialized( yogiMap.get( "student" ) ) ); + // assertFalse( Hibernate.isInitialized( shermanMap.get( "student" ) ) ); + assertTrue( yogiMap.get( "student" ) instanceof Student ); + assertTrue( shermanMap.get( "student" ) instanceof Student ); + assertEquals( + yogiExpected.getStudentNumber(), + ( (Student) yogiMap.get( "student" ) ).getStudentNumber() + ); + assertEquals( + shermanExpected.getStudentNumber(), + ( (Student) shermanMap.get( "student" ) ).getStudentNumber() + ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - Map yogiMap = ( Map ) resultList.get( 0 ); - Map shermanMap = ( Map ) resultList.get( 1 ); - assertEquals( 1, yogiMap.size() ); - assertEquals( 1, shermanMap.size() ); - // TODO: following are initialized for hql and uninitialied for criteria; why? - // assertFalse( Hibernate.isInitialized( yogiMap.get( "student" ) ) ); - // assertFalse( Hibernate.isInitialized( shermanMap.get( "student" ) ) ); - assertTrue( yogiMap.get( "student" ) instanceof Student ); - assertTrue( shermanMap.get( "student" ) instanceof Student ); - assertEquals( yogiExpected.getStudentNumber(), ( ( Student ) yogiMap.get( "student" ) ).getStudentNumber() ); - assertEquals( shermanExpected.getStudentNumber(), ( ( Student ) shermanMap.get( "student" ) ).getStudentNumber() ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, false); + runTest( criteriaExecutor, checker, false ); } @Test public void testAliasToEntityMapMultiProjectionList() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { + @Override protected JpaCriteriaQuery getCriteria(Session s) { - throw new NotYetImplementedFor6Exception( getClass() ); + CriteriaBuilder builder = s.getCriteriaBuilder(); + JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery(); + final JpaRoot root = criteria.from( Enrolment.class ); + + criteria.multiselect( + root.get( "student" ).alias( "student" ), + root.get( "semester" ).alias( "semester" ), + root.get( "year" ).alias( "year" ), + root.get( "course" ).alias( "course" ) + ); + + criteria.orderBy( builder.asc( root.get( "studentNumber" ) ) ); + return criteria; + // return s.createCriteria( Enrolment.class, "e" ) // .setProjection( // Projections.projectionList() @@ -1334,43 +1147,54 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select e.student as student, e.semester as semester, e.year as year, e.course as course from Enrolment e order by e.studentNumber" ) - .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Map yogiMap = (Map) resultList.get( 0 ); + Map shermanMap = (Map) resultList.get( 1 ); + assertEquals( 4, yogiMap.size() ); + assertEquals( 4, shermanMap.size() ); + assertTrue( yogiMap.get( "student" ) instanceof Student ); + assertTrue( shermanMap.get( "student" ) instanceof Student ); + // TODO: following are initialized for hql and uninitialied for criteria; why? + // assertFalse( Hibernate.isInitialized( yogiMap.get( "student" ) ) ); + // assertFalse( Hibernate.isInitialized( shermanMap.get( "student" ) ) ); + assertEquals( + yogiExpected.getStudentNumber(), + ( (Student) yogiMap.get( "student" ) ).getStudentNumber() + ); + assertEquals( + shermanExpected.getStudentNumber(), + ( (Student) shermanMap.get( "student" ) ).getStudentNumber() + ); + assertEquals( yogiEnrolmentExpected.getSemester(), yogiMap.get( "semester" ) ); + assertEquals( yogiEnrolmentExpected.getYear(), yogiMap.get( "year" ) ); + assertEquals( courseExpected, yogiMap.get( "course" ) ); + assertEquals( shermanEnrolmentExpected.getSemester(), shermanMap.get( "semester" ) ); + assertEquals( shermanEnrolmentExpected.getYear(), shermanMap.get( "year" ) ); + assertEquals( courseExpected, shermanMap.get( "course" ) ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - Map yogiMap = ( Map ) resultList.get( 0 ); - Map shermanMap = ( Map ) resultList.get( 1 ); - assertEquals( 4, yogiMap.size() ); - assertEquals( 4, shermanMap.size() ); - assertTrue( yogiMap.get( "student" ) instanceof Student ); - assertTrue( shermanMap.get( "student" ) instanceof Student ); - // TODO: following are initialized for hql and uninitialied for criteria; why? - // assertFalse( Hibernate.isInitialized( yogiMap.get( "student" ) ) ); - // assertFalse( Hibernate.isInitialized( shermanMap.get( "student" ) ) ); - assertEquals( yogiExpected.getStudentNumber(), ( ( Student ) yogiMap.get( "student" ) ).getStudentNumber() ); - assertEquals( shermanExpected.getStudentNumber(), ( ( Student ) shermanMap.get( "student" ) ).getStudentNumber() ); - assertEquals( yogiEnrolmentExpected.getSemester(), yogiMap.get( "semester" ) ); - assertEquals( yogiEnrolmentExpected.getYear(), yogiMap.get( "year" ) ); - assertEquals( courseExpected, yogiMap.get( "course" ) ); - assertEquals( shermanEnrolmentExpected.getSemester(), shermanMap.get( "semester" ) ); - assertEquals( shermanEnrolmentExpected.getYear(), shermanMap.get( "year" ) ); - assertEquals( courseExpected, shermanMap.get( "course" ) ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, false ); + runTest( criteriaExecutor, checker, false ); } @Test public void testAliasToEntityMapMultiProjectionWithNullAliasList() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { + @Override protected JpaCriteriaQuery getCriteria(Session s) { - throw new NotYetImplementedFor6Exception( ); + CriteriaBuilder builder = s.getCriteriaBuilder(); + JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery(); + final JpaRoot root = criteria.from( Enrolment.class ); + + criteria.multiselect( + root.get( "student" ).alias( "student" ), + root.get( "semester" ), + root.get( "year" ), + root.get( "course" ).alias( "course" ) + ); + criteria.orderBy( builder.asc( root.get( "studentNumber" ) ) ); + return criteria; + // return s.createCriteria( Enrolment.class, "e" ) // .setProjection( // Projections.projectionList() @@ -1383,40 +1207,47 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select e.student as student, e.semester, e.year, e.course as course from Enrolment e order by e.studentNumber" ) - .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Map yogiMap = (Map) resultList.get( 0 ); + Map shermanMap = (Map) resultList.get( 1 ); + // TODO: following are initialized for hql and uninitialied for criteria; why? + // assertFalse( Hibernate.isInitialized( yogiMap.get( "student" ) ) ); + // assertFalse( Hibernate.isInitialized( shermanMap.get( "student" ) ) ); + assertTrue( yogiMap.get( "student" ) instanceof Student ); + assertEquals( + yogiExpected.getStudentNumber(), + ( (Student) yogiMap.get( "student" ) ).getStudentNumber() + ); + assertEquals( + shermanExpected.getStudentNumber(), + ( (Student) shermanMap.get( "student" ) ).getStudentNumber() + ); + assertNull( yogiMap.get( "semester" ) ); + assertNull( yogiMap.get( "year" ) ); + assertEquals( courseExpected, yogiMap.get( "course" ) ); + assertNull( shermanMap.get( "semester" ) ); + assertNull( shermanMap.get( "year" ) ); + assertEquals( courseExpected, shermanMap.get( "course" ) ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - Map yogiMap = ( Map ) resultList.get( 0 ); - Map shermanMap = ( Map ) resultList.get( 1 ); - // TODO: following are initialized for hql and uninitialied for criteria; why? - // assertFalse( Hibernate.isInitialized( yogiMap.get( "student" ) ) ); - // assertFalse( Hibernate.isInitialized( shermanMap.get( "student" ) ) ); - assertTrue( yogiMap.get( "student" ) instanceof Student ); - assertEquals( yogiExpected.getStudentNumber(), ( ( Student ) yogiMap.get( "student" ) ).getStudentNumber() ); - assertEquals( shermanExpected.getStudentNumber(), ( ( Student ) shermanMap.get( "student" ) ).getStudentNumber() ); - assertNull( yogiMap.get( "semester" ) ); - assertNull( yogiMap.get( "year" ) ); - assertEquals( courseExpected, yogiMap.get( "course" ) ); - assertNull( shermanMap.get( "semester" ) ); - assertNull( shermanMap.get( "year" ) ); - assertEquals( courseExpected, shermanMap.get( "course" ) ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, false ); + runTest( criteriaExecutor, checker, false ); } @Test public void testAliasToEntityMapMultiAggregatedPropProjectionSingleResult() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { + @Override protected JpaCriteriaQuery getCriteria(Session s) { - throw new NotYetImplementedFor6Exception( getClass() ); + CriteriaBuilder builder = s.getCriteriaBuilder(); + JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery(); + final JpaRoot root = criteria.from( Enrolment.class ); + criteria.multiselect( + builder.min( root.get( "studentNumber" ) ).alias( "minStudentNumber" ), + builder.max( root.get( "studentNumber" ) ).alias( "maxStudentNumber" ) + ); + return criteria; + // return s.createCriteria( Enrolment.class ) // .setProjection( // Projections.projectionList() @@ -1426,35 +1257,35 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( - "select min( e.studentNumber ) as minStudentNumber, max( e.studentNumber ) as maxStudentNumber from Enrolment e" ) - .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP ); - } + ResultChecker checker = results -> { + assertTrue( results instanceof Map ); + Map resultMap = (Map) results; + assertEquals( 2, resultMap.size() ); + assertEquals( yogiExpected.getStudentNumber(), resultMap.get( "minStudentNumber" ) ); + assertEquals( shermanExpected.getStudentNumber(), resultMap.get( "maxStudentNumber" ) ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - assertTrue( results instanceof Map ); - Map resultMap = ( Map ) results; - assertEquals( 2, resultMap.size() ); - assertEquals( yogiExpected.getStudentNumber(), resultMap.get( "minStudentNumber" ) ); - assertEquals( shermanExpected.getStudentNumber(), resultMap.get( "maxStudentNumber" ) ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, true ); + runTest( criteriaExecutor, checker, true ); } @Test public void testOneNonEntityProjectionUnique() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { + @Override + protected ResultTransformer getResultTransformer() { + return null; + } + + @Override protected JpaCriteriaQuery getCriteria(Session s) { // should use PassThroughTransformer by default CriteriaBuilder builder = s.getCriteriaBuilder(); - JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery( ); + JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery(); Root root = criteria.from( Enrolment.class ); criteria.select( root.get( "semester" ) ); - criteria.where( builder.equal( root.get( "studentNumber" ), shermanEnrolmentExpected.getStudentNumber() ) ); + criteria.where( builder.equal( + root.get( "studentNumber" ), + shermanEnrolmentExpected.getStudentNumber() + ) ); return criteria; // return s.createCriteria( Enrolment.class, "e" ) @@ -1462,28 +1293,26 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // .add( Restrictions.eq( "e.studentNumber", shermanEnrolmentExpected.getStudentNumber() ) ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select e.semester from Enrolment e where e.studentNumber = :studentNumber" ) - .setParameter( "studentNumber", shermanEnrolmentExpected.getStudentNumber() ); - } + ResultChecker checker = results -> { + assertTrue( results instanceof Short ); + assertEquals( shermanEnrolmentExpected.getSemester(), results ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - assertTrue( results instanceof Short ); - assertEquals( Short.valueOf( shermanEnrolmentExpected.getSemester() ), results ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, true ); + runTest( criteriaExecutor, checker, true ); } @Test public void testOneNonEntityProjectionList() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { + @Override + protected ResultTransformer getResultTransformer() { + return null; + } + + @Override protected JpaCriteriaQuery getCriteria(Session s) { // should use PassThroughTransformer by default CriteriaBuilder builder = s.getCriteriaBuilder(); - JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery( ); + JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery(); Root root = criteria.from( Enrolment.class ); criteria.select( root.get( "semester" ) ); criteria.orderBy( builder.asc( root.get( "studentNumber" ) ) ); @@ -1493,55 +1322,24 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // .addOrder( Order.asc( "e.studentNumber") ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select e.semester from Enrolment e order by e.studentNumber" ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + assertEquals( yogiEnrolmentExpected.getSemester(), resultList.get( 0 ) ); + assertEquals( shermanEnrolmentExpected.getSemester(), resultList.get( 1 ) ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - assertEquals( yogiEnrolmentExpected.getSemester(), resultList.get( 0 ) ); - assertEquals( shermanEnrolmentExpected.getSemester(), resultList.get( 1 ) ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, false ); - } - - @Test - public void testListElementsProjectionList() throws Exception { - /* - CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { - protected Criteria getCriteria(Session s) { - // should use PassThroughTransformer by default - return s.createCriteria( Student.class, "s" ) - .createCriteria( "s.secretCodes" ) - .setProjection( Projections.property( "s.secretCodes" ) ) - .addOrder( Order.asc( "s.studentNumber") ); - } - }; - */ - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select elements(s.secretCodes) from Student s" ); - } - }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 3, resultList.size() ); - assertTrue( resultList.contains( yogiExpected.getSecretCodes().get( 0 ) ) ); - assertTrue( resultList.contains( shermanExpected.getSecretCodes().get( 0 ) ) ); - assertTrue( resultList.contains( shermanExpected.getSecretCodes().get( 1 ) ) ); - } - }; - runTest( hqlExecutor, null, checker, false ); + runTest( criteriaExecutor, checker, false ); } @Test public void testOneEntityProjectionUnique() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { + @Override + protected ResultTransformer getResultTransformer() { + return null; + } + + @Override protected JpaCriteriaQuery getCriteria(Session s) { CriteriaBuilder builder = s.getCriteriaBuilder(); JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery(); @@ -1549,8 +1347,8 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu criteria.select( root.get( "student" ) ); criteria.where( builder.equal( root.get( "studentNumber" ), - Long.valueOf( yogiExpected.getStudentNumber() ) - )); + yogiExpected.getStudentNumber() + ) ); return criteria; // should use PassThroughTransformer by default @@ -1559,28 +1357,23 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // .add( Restrictions.eq( "studentNumber", Long.valueOf( yogiExpected.getStudentNumber() ) ) ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select e.student from Enrolment e where e.studentNumber = :studentNumber" ) - .setParameter( "studentNumber", Long.valueOf( yogiExpected.getStudentNumber() ) ); - } + ResultChecker checker = results -> { + assertTrue( results instanceof Student ); + Student student = (Student) results; + // TODO: following is initialized for hql and uninitialied for criteria; why? + //assertFalse( Hibernate.isInitialized( student ) ); + assertEquals( yogiExpected.getStudentNumber(), student.getStudentNumber() ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - assertTrue( results instanceof Student ); - Student student = ( Student ) results; - // TODO: following is initialized for hql and uninitialied for criteria; why? - //assertFalse( Hibernate.isInitialized( student ) ); - assertEquals( yogiExpected.getStudentNumber(), student.getStudentNumber() ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, true ); + runTest( criteriaExecutor, checker, true ); } @Test + @FailureExpected(jiraKey = "HHH-3345", message = "HQL query using 'select new' and 'join fetch'") + public void testOneEntityProjectionList() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { // should use PassThroughTransformer by default + @Override protected JpaCriteriaQuery getCriteria(Session s) { CriteriaBuilder builder = s.getCriteriaBuilder(); JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery(); @@ -1593,32 +1386,34 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // .addOrder( Order.asc( "e.studentNumber") ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select e.student from Enrolment e order by e.studentNumber" ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + // TODO: following is initialized for hql and uninitialied for criteria; why? + //assertFalse( Hibernate.isInitialized( resultList.get( 0 ) ) ); + //assertFalse( Hibernate.isInitialized( resultList.get( 1 ) ) ); + assertEquals( yogiExpected.getStudentNumber(), ( (Student) resultList.get( 0 ) ).getStudentNumber() ); + assertEquals( + shermanExpected.getStudentNumber(), + ( (Student) resultList.get( 1 ) ).getStudentNumber() + ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - // TODO: following is initialized for hql and uninitialied for criteria; why? - //assertFalse( Hibernate.isInitialized( resultList.get( 0 ) ) ); - //assertFalse( Hibernate.isInitialized( resultList.get( 1 ) ) ); - assertEquals( yogiExpected.getStudentNumber(), ( ( Student ) resultList.get( 0 ) ).getStudentNumber() ); - assertEquals( shermanExpected.getStudentNumber(), ( ( Student ) resultList.get( 1 ) ).getStudentNumber() ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, false ); + runTest( criteriaExecutor, checker, false ); } @Test public void testMultiEntityProjectionUnique() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { + @Override + protected ResultTransformer getResultTransformer() { + return null; + } + + @Override protected JpaCriteriaQuery getCriteria(Session s) { // should use PassThroughTransformer by default CriteriaBuilder builder = s.getCriteriaBuilder(); - JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery(); + JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery( Object[].class ); Root root = criteria.from( Enrolment.class ); criteria.multiselect( root.get( "student" ), @@ -1628,8 +1423,8 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu ); criteria.where( builder.equal( root.get( "studentNumber" ), - Long.valueOf( shermanEnrolmentExpected.getStudentNumber() ) - )); + shermanEnrolmentExpected.getStudentNumber() + ) ); return criteria; // return s.createCriteria( Enrolment.class ) // .setProjection( @@ -1642,50 +1437,46 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // .add( Restrictions.eq( "studentNumber", Long.valueOf( shermanEnrolmentExpected.getStudentNumber() ) ) ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( - "select e.student, e.semester, e.year, e.course from Enrolment e where e.studentNumber = :studentNumber" ) - .setParameter( "studentNumber", shermanEnrolmentExpected.getStudentNumber() ); - } + ResultChecker checker = results -> { + assertTrue( results instanceof Object[] ); + Object shermanObjects[] = (Object[]) results; + assertEquals( 4, shermanObjects.length ); + assertNotNull( shermanObjects[0] ); + assertTrue( shermanObjects[0] instanceof Student ); + // TODO: following is initialized for hql and uninitialied for criteria; why? + //assertFalse( Hibernate.isInitialized( shermanObjects[ 0 ] ) ); + assertEquals( shermanEnrolmentExpected.getSemester(), ( (Short) shermanObjects[1] ).shortValue() ); + assertEquals( shermanEnrolmentExpected.getYear(), ( (Short) shermanObjects[2] ).shortValue() ); + assertTrue( !( shermanObjects[3] instanceof HibernateProxy ) ); + assertTrue( shermanObjects[3] instanceof Course ); + assertEquals( courseExpected, shermanObjects[3] ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - assertTrue( results instanceof Object[] ); - Object shermanObjects[] = ( Object [] ) results; - assertEquals( 4, shermanObjects.length ); - assertNotNull( shermanObjects[ 0 ] ); - assertTrue( shermanObjects[ 0 ] instanceof Student ); - // TODO: following is initialized for hql and uninitialied for criteria; why? - //assertFalse( Hibernate.isInitialized( shermanObjects[ 0 ] ) ); - assertEquals( shermanEnrolmentExpected.getSemester(), ( (Short) shermanObjects[ 1 ] ).shortValue() ); - assertEquals( shermanEnrolmentExpected.getYear(), ( (Short) shermanObjects[ 2 ] ).shortValue() ); - assertTrue( ! ( shermanObjects[ 3 ] instanceof HibernateProxy ) ); - assertTrue( shermanObjects[ 3 ] instanceof Course ); - assertEquals( courseExpected, shermanObjects[ 3 ] ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, true ); + runTest( criteriaExecutor, checker, true ); } @Test public void testMultiEntityProjectionList() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { + @Override + protected ResultTransformer getResultTransformer() { + return null; + } + + @Override protected JpaCriteriaQuery getCriteria(Session s) { // should use PassThroughTransformer by default CriteriaBuilder builder = s.getCriteriaBuilder(); - JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery(); + JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery( Object[].class ); Root root = criteria.from( Enrolment.class ); + criteria.multiselect( root.get( "student" ), root.get( "semester" ), root.get( "year" ), root.get( "course" ) ); - criteria.where( builder.equal( - root.get( "studentNumber" ), - Long.valueOf( shermanEnrolmentExpected.getStudentNumber() ) - )); + + criteria.orderBy( builder.asc( root.get( "studentNumber" ) ) ); return criteria; // return s.createCriteria( Enrolment.class, "e" ) // .setProjection( @@ -1698,40 +1489,53 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // .addOrder( Order.asc( "e.studentNumber") ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select e.student, e.semester, e.year, e.course from Enrolment e order by e.studentNumber" ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Object[] yogiObjects = (Object[]) resultList.get( 0 ); + Object[] shermanObjects = (Object[]) resultList.get( 1 ); + assertEquals( 4, yogiObjects.length ); + // TODO: following is initialized for hql and uninitialied for criteria; why? + //assertFalse( Hibernate.isInitialized( yogiObjects[ 0 ] ) ); + //assertFalse( Hibernate.isInitialized( shermanObjects[ 0 ] ) ); + assertTrue( yogiObjects[0] instanceof Student ); + assertTrue( shermanObjects[0] instanceof Student ); + assertEquals( yogiEnrolmentExpected.getSemester(), ( (Short) yogiObjects[1] ).shortValue() ); + assertEquals( yogiEnrolmentExpected.getYear(), ( (Short) yogiObjects[2] ).shortValue() ); + assertEquals( courseExpected, yogiObjects[3] ); + assertEquals( shermanEnrolmentExpected.getSemester(), ( (Short) shermanObjects[1] ).shortValue() ); + assertEquals( shermanEnrolmentExpected.getYear(), ( (Short) shermanObjects[2] ).shortValue() ); + assertTrue( shermanObjects[3] instanceof Course ); + assertEquals( courseExpected, shermanObjects[3] ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - Object[] yogiObjects = ( Object[] ) resultList.get( 0 ); - Object[] shermanObjects = ( Object[] ) resultList.get( 1 ); - assertEquals( 4, yogiObjects.length ); - // TODO: following is initialized for hql and uninitialied for criteria; why? - //assertFalse( Hibernate.isInitialized( yogiObjects[ 0 ] ) ); - //assertFalse( Hibernate.isInitialized( shermanObjects[ 0 ] ) ); - assertTrue( yogiObjects[ 0 ] instanceof Student ); - assertTrue( shermanObjects[ 0 ] instanceof Student ); - assertEquals( yogiEnrolmentExpected.getSemester(), ( (Short) yogiObjects[ 1 ] ).shortValue() ); - assertEquals( yogiEnrolmentExpected.getYear(), ( (Short) yogiObjects[ 2 ] ).shortValue() ); - assertEquals( courseExpected, yogiObjects[ 3 ] ); - assertEquals( shermanEnrolmentExpected.getSemester(), ( (Short) shermanObjects[ 1 ] ).shortValue() ); - assertEquals( shermanEnrolmentExpected.getYear(), ( (Short) shermanObjects[ 2 ] ).shortValue() ); - assertTrue( shermanObjects[ 3 ] instanceof Course ); - assertEquals( courseExpected, shermanObjects[ 3 ] ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, false ); + runTest( criteriaExecutor, checker, false ); } @Test public void testMultiEntityProjectionAliasedList() throws Exception { -// CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { -// protected JpaCriteriaQuery getCriteria(Session s) { -// // should use PassThroughTransformer by default + CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { + @Override + protected ResultTransformer getResultTransformer() { + return null; + } + + @Override + protected JpaCriteriaQuery getCriteria(Session s) { + CriteriaBuilder builder = s.getCriteriaBuilder(); + JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery( Object[].class ); + Root root = criteria.from( Enrolment.class ); + + criteria.multiselect( + root.get( "student" ), + root.get( "semester" ), + root.get( "year" ), + root.get( "course" ) + ); + + criteria.orderBy( builder.asc( root.get( "studentNumber" ) ) ); + return criteria; + + // should use PassThroughTransformer by default // return s.createCriteria( Enrolment.class, "e" ) // .setProjection( // Projections.projectionList() @@ -1741,77 +1545,75 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // .add( Property.forName( "e.course" ).as( "c" ) ) // ) // .addOrder( Order.asc( "e.studentNumber") ); -// } -// }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select e.student as st, e.semester as sem, e.year as yr, e.course as c from Enrolment e order by e.studentNumber" ); } }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - Object[] yogiObjects = ( Object[] ) resultList.get( 0 ); - Object[] shermanObjects = ( Object[] ) resultList.get( 1 ); - assertEquals( 4, yogiObjects.length ); - // TODO: following is initialized for hql and uninitialied for criteria; why? - //assertFalse( Hibernate.isInitialized( yogiObjects[ 0 ] ) ); - //assertFalse( Hibernate.isInitialized( shermanObjects[ 0 ] ) ); - assertTrue( yogiObjects[ 0 ] instanceof Student ); - assertTrue( shermanObjects[ 0 ] instanceof Student ); - assertEquals( yogiEnrolmentExpected.getSemester(), ( (Short) yogiObjects[ 1 ] ).shortValue() ); - assertEquals( yogiEnrolmentExpected.getYear(), ( (Short) yogiObjects[ 2 ] ).shortValue() ); - assertEquals( courseExpected, yogiObjects[ 3 ] ); - assertEquals( shermanEnrolmentExpected.getSemester(), ( (Short) shermanObjects[ 1 ] ).shortValue() ); - assertEquals( shermanEnrolmentExpected.getYear(), ( (Short) shermanObjects[ 2 ] ).shortValue() ); - assertTrue( shermanObjects[ 3 ] instanceof Course ); - assertEquals( courseExpected, shermanObjects[ 3 ] ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Object[] yogiObjects = (Object[]) resultList.get( 0 ); + Object[] shermanObjects = (Object[]) resultList.get( 1 ); + assertEquals( 4, yogiObjects.length ); + // TODO: following is initialized for hql and uninitialied for criteria; why? + //assertFalse( Hibernate.isInitialized( yogiObjects[ 0 ] ) ); + //assertFalse( Hibernate.isInitialized( shermanObjects[ 0 ] ) ); + assertTrue( yogiObjects[0] instanceof Student ); + assertTrue( shermanObjects[0] instanceof Student ); + assertEquals( yogiEnrolmentExpected.getSemester(), ( (Short) yogiObjects[1] ).shortValue() ); + assertEquals( yogiEnrolmentExpected.getYear(), ( (Short) yogiObjects[2] ).shortValue() ); + assertEquals( courseExpected, yogiObjects[3] ); + assertEquals( shermanEnrolmentExpected.getSemester(), ( (Short) shermanObjects[1] ).shortValue() ); + assertEquals( shermanEnrolmentExpected.getYear(), ( (Short) shermanObjects[2] ).shortValue() ); + assertTrue( shermanObjects[3] instanceof Course ); + assertEquals( courseExpected, shermanObjects[3] ); }; - runTest( hqlExecutor, null, checker, false ); + runTest( criteriaExecutor, checker, false ); } @Test public void testSingleAggregatedPropProjectionSingleResult() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { + @Override + protected ResultTransformer getResultTransformer() { + return null; + } + + @Override protected JpaCriteriaQuery getCriteria(Session s) { CriteriaBuilder builder = s.getCriteriaBuilder(); JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery(); Root root = criteria.from( Enrolment.class ); - criteria.select( root.get( "studentNumber" ) ); + criteria.select( builder.min( root.get( "studentNumber" ) ) ); return criteria; // return s.createCriteria( Enrolment.class ) // .setProjection( Projections.min( "studentNumber" ) ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select min( e.studentNumber ) from Enrolment e" ); - } + ResultChecker checker = results -> { + assertTrue( results instanceof Long ); + assertEquals( yogiExpected.getStudentNumber(), results ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - assertTrue( results instanceof Long ); - assertEquals( Long.valueOf( yogiExpected.getStudentNumber() ), results ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, true ); + runTest( criteriaExecutor, checker, true ); } @Test public void testMultiAggregatedPropProjectionSingleResult() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { + @Override + protected ResultTransformer getResultTransformer() { + return null; + } + + @Override protected JpaCriteriaQuery getCriteria(Session s) { CriteriaBuilder builder = s.getCriteriaBuilder(); - JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery(); + JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery( Object[].class ); Root root = criteria.from( Enrolment.class ); criteria.multiselect( - builder.min( root.get( "studentNumber" ) ).alias( "minStudentNumber" ), - builder.min( root.get( "studentNumber" ) ).alias( "maxStudentNumber" ) - ); + builder.min( root.get( "studentNumber" ) ), + builder.max( root.get( "studentNumber" ) ) + ); return criteria; // return s.createCriteria( Enrolment.class ) @@ -1822,29 +1624,34 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( - "select min( e.studentNumber ) as minStudentNumber, max( e.studentNumber ) as maxStudentNumber from Enrolment e" ); - } + ResultChecker checker = results -> { + assertTrue( results instanceof Object[] ); + Object[] resultObjects = (Object[]) results; + assertEquals( yogiExpected.getStudentNumber(), resultObjects[0] ); + assertEquals( shermanExpected.getStudentNumber(), resultObjects[1] ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - assertTrue( results instanceof Object[] ); - Object[] resultObjects = ( Object[] ) results; - assertEquals( Long.valueOf( yogiExpected.getStudentNumber() ), resultObjects[ 0 ] ); - assertEquals( Long.valueOf( shermanExpected.getStudentNumber() ), resultObjects[ 1 ] ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, true ); + runTest( criteriaExecutor, checker, true ); } @Test public void testAliasToBeanDtoOneArgList() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { - protected JpaCriteriaQuery getCriteria(Session s) { + @Override + protected ResultTransformer getResultTransformer() { + return Transformers.aliasToBean( StudentDTO.class ); + } - throw new NotYetImplementedFor6Exception( getClass() ); + @Override + protected JpaCriteriaQuery getCriteria(Session s) { + CriteriaBuilder builder = s.getCriteriaBuilder(); + JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery(); + Root root = criteria.from( Enrolment.class ); + + criteria.select( + root.get( "student" ).get( "name" ).alias( "studentName" ) + ); + criteria.orderBy( builder.asc( root.get( "student" ).get( "studentNumber" ) ) ); + return criteria; // return s.createCriteria( Enrolment.class, "e" ) // .createAlias( "e.student", "st" ) @@ -1854,33 +1661,39 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // .setResultTransformer( Transformers.aliasToBean( StudentDTO.class ) ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select st.name as studentName from Student st order by st.studentNumber" ) - .setResultTransformer( Transformers.aliasToBean( StudentDTO.class ) ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + StudentDTO dto = (StudentDTO) resultList.get( 0 ); + assertNull( dto.getDescription() ); + assertEquals( yogiExpected.getName(), dto.getName() ); + dto = (StudentDTO) resultList.get( 1 ); + assertNull( dto.getDescription() ); + assertEquals( shermanExpected.getName(), dto.getName() ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - StudentDTO dto = ( StudentDTO ) resultList.get( 0 ); - assertNull( dto.getDescription() ); - assertEquals( yogiExpected.getName(), dto.getName() ); - dto = ( StudentDTO ) resultList.get( 1 ); - assertNull( dto.getDescription() ); - assertEquals( shermanExpected.getName(), dto.getName() ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, false ); + runTest( criteriaExecutor, checker, false ); } @Test public void testAliasToBeanDtoMultiArgList() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { - protected JpaCriteriaQuery getCriteria(Session s) { - throw new NotYetImplementedFor6Exception( getClass() ); + @Override + protected ResultTransformer getResultTransformer() { + return Transformers.aliasToBean( StudentDTO.class ); + } + + @Override + protected JpaCriteriaQuery getCriteria(Session s) { + CriteriaBuilder builder = s.getCriteriaBuilder(); + JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery(); + Root root = criteria.from( Enrolment.class ); + final Path student = root.get( "student" ); + criteria.multiselect( + student.get( "name" ).alias( "studentName" ), + root.get( "course" ).get( "description" ).alias( "courseDescription" ) + ); + return criteria; // return s.createCriteria( Enrolment.class, "e" ) // .createAlias( "e.student", "st" ) // .createAlias( "e.course", "co" ) @@ -1893,40 +1706,39 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // .setResultTransformer( Transformers.aliasToBean( StudentDTO.class ) ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select st.name as studentName, co.description as courseDescription from Enrolment e join e.student st join e.course co order by e.studentNumber" ) - .setResultTransformer( Transformers.aliasToBean( StudentDTO.class ) ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + StudentDTO dto = (StudentDTO) resultList.get( 0 ); + assertEquals( courseExpected.getDescription(), dto.getDescription() ); + assertEquals( yogiExpected.getName(), dto.getName() ); + dto = (StudentDTO) resultList.get( 1 ); + assertEquals( courseExpected.getDescription(), dto.getDescription() ); + assertEquals( shermanExpected.getName(), dto.getName() ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - StudentDTO dto = ( StudentDTO ) resultList.get( 0 ); - assertEquals( courseExpected.getDescription(), dto.getDescription() ); - assertEquals( yogiExpected.getName(), dto.getName() ); - dto = ( StudentDTO ) resultList.get( 1 ); - assertEquals( courseExpected.getDescription(), dto.getDescription() ); - assertEquals( shermanExpected.getName(), dto.getName() ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, false ); + runTest( criteriaExecutor, checker, false ); } @Test public void testMultiProjectionListThenApplyAliasToBean() throws Exception { + CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { + @Override + protected ResultTransformer getResultTransformer() { + return null; + } + + @Override protected JpaCriteriaQuery getCriteria(Session s) { CriteriaBuilder builder = s.getCriteriaBuilder(); - JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery(); + JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery( Object[].class ); Root root = criteria.from( Enrolment.class ); - Join student = root.join( "student",JoinType.INNER ); - Join course = root.join( "course", JoinType.INNER ); + criteria.multiselect( - student.get( "name" ), - course.get( "description" ) + root.get( "student" ).get( "name" ), + root.get( "course" ).get( "description" ) ); + criteria.orderBy( builder.asc( root.get( "studentNumber" ) ) ); return criteria; @@ -1941,83 +1753,86 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // .addOrder( Order.asc( "e.studentNumber" ) ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select st.name as studentName, co.description as courseDescription from Enrolment e join e.student st join e.course co order by e.studentNumber" ); + ResultChecker checker = results -> { + List resultList = (List) results; + ResultTransformer transformer = Transformers.aliasToBean( StudentDTO.class ); + String[] aliases = new String[] { "studentName", "courseDescription" }; + for ( int i = 0; i < resultList.size(); i++ ) { + resultList.set( + i, + transformer.transformTuple( (Object[]) resultList.get( i ), aliases ) + ); } - }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - ResultTransformer transformer = Transformers.aliasToBean( StudentDTO.class ); - String[] aliases = new String[] { "studentName", "courseDescription" }; - for ( int i = 0 ; i < resultList.size(); i++ ) { - resultList.set( - i, - transformer.transformTuple( ( Object[] ) resultList.get( i ), aliases ) - ); - } - assertEquals( 2, resultList.size() ); - StudentDTO dto = ( StudentDTO ) resultList.get( 0 ); - assertEquals( courseExpected.getDescription(), dto.getDescription() ); - assertEquals( yogiExpected.getName(), dto.getName() ); - dto = ( StudentDTO ) resultList.get( 1 ); - assertEquals( courseExpected.getDescription(), dto.getDescription() ); - assertEquals( shermanExpected.getName(), dto.getName() ); - } + assertEquals( 2, resultList.size() ); + StudentDTO dto = (StudentDTO) resultList.get( 0 ); + assertEquals( courseExpected.getDescription(), dto.getDescription() ); + assertEquals( yogiExpected.getName(), dto.getName() ); + dto = (StudentDTO) resultList.get( 1 ); + assertEquals( courseExpected.getDescription(), dto.getDescription() ); + assertEquals( shermanExpected.getName(), dto.getName() ); }; - runTest( hqlExecutor, criteriaExecutor, checker, false ); + runTest( criteriaExecutor, checker, false ); } - @Test - public void testAliasToBeanDtoLiteralArgList() throws Exception { - CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { - protected JpaCriteriaQuery getCriteria(Session s) { - throw new NotYetImplementedFor6Exception( getClass() ); -// return s.createCriteria( Enrolment.class, "e" ) -// .createAlias( "e.student", "st" ) -// .createAlias( "e.course", "co" ) -// .setProjection( -// Projections.projectionList() -// .add( Property.forName( "st.name" ).as( "studentName" ) ) -// .add( Projections.sqlProjection( -// "'lame description' as courseDescription", -// new String[] { "courseDescription" }, -// new Type[] { StandardBasicTypes.STRING } -// ) -// ) -// ) -// .addOrder( Order.asc( "e.studentNumber" ) ) -// .setResultTransformer( Transformers.aliasToBean( StudentDTO.class ) ); - } - }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select st.name as studentName, 'lame description' as courseDescription from Enrolment e join e.student st join e.course co order by e.studentNumber" ) - .setResultTransformer( Transformers.aliasToBean( StudentDTO.class ) ); - } - }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - StudentDTO dto = ( StudentDTO ) resultList.get( 0 ); - assertEquals( "lame description", dto.getDescription() ); - assertEquals( yogiExpected.getName(), dto.getName() ); - dto = ( StudentDTO ) resultList.get( 1 ); - assertEquals( "lame description", dto.getDescription() ); - assertEquals( shermanExpected.getName(), dto.getName() ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, false ); - } +// @Test +// public void testAliasToBeanDtoLiteralArgList() throws Exception { +// CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { +// protected JpaCriteriaQuery getCriteria(Session s) { +// +//// return s.createCriteria( Enrolment.class, "e" ) +//// .createAlias( "e.student", "st" ) +//// .createAlias( "e.course", "co" ) +//// .setProjection( +//// Projections.projectionList() +//// .add( Property.forName( "st.name" ).as( "studentName" ) ) +//// .add( Projections.sqlProjection( +//// "'lame description' as courseDescription", +//// new String[] { "courseDescription" }, +//// new Type[] { StandardBasicTypes.STRING } +//// ) +//// ) +//// ) +//// .addOrder( Order.asc( "e.studentNumber" ) ) +//// .setResultTransformer( Transformers.aliasToBean( StudentDTO.class ) ); +// } +// }; +// ResultChecker checker = results -> { +// List resultList = (List) results; +// assertEquals( 2, resultList.size() ); +// StudentDTO dto = (StudentDTO) resultList.get( 0 ); +// assertEquals( "lame description", dto.getDescription() ); +// assertEquals( yogiExpected.getName(), dto.getName() ); +// dto = (StudentDTO) resultList.get( 1 ); +// assertEquals( "lame description", dto.getDescription() ); +// assertEquals( shermanExpected.getName(), dto.getName() ); +// }; +// runTest( criteriaExecutor, checker, false ); +// } @Test public void testAliasToBeanDtoWithNullAliasList() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { + @Override + protected ResultTransformer getResultTransformer() { + return Transformers.aliasToBean( StudentDTO.class ); + } + + @Override protected JpaCriteriaQuery getCriteria(Session s) { - throw new NotYetImplementedFor6Exception( getClass() ); + CriteriaBuilder builder = s.getCriteriaBuilder(); + JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery(); + Root root = criteria.from( Enrolment.class ); + + criteria.multiselect( + root.get( "student" ).get( "name" ).alias( "studentName" ), + root.get( "student" ).get( "studentNumber" ), + root.get( "course" ).get( "description" ).alias( "courseDescription" ) + ); + + criteria.orderBy( builder.asc( root.get( "studentNumber" ) ) ); + return criteria; + // return s.createCriteria( Enrolment.class, "e" ) // .createAlias( "e.student", "st" ) // .createAlias( "e.course", "co" ) @@ -2031,100 +1846,127 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // .setResultTransformer( Transformers.aliasToBean( StudentDTO.class ) ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select st.name as studentName, co.description as courseDescription from Enrolment e join e.student st join e.course co order by e.studentNumber" ) - .setResultTransformer( Transformers.aliasToBean( StudentDTO.class ) ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + StudentDTO dto = (StudentDTO) resultList.get( 0 ); + assertEquals( courseExpected.getDescription(), dto.getDescription() ); + assertEquals( yogiExpected.getName(), dto.getName() ); + dto = (StudentDTO) resultList.get( 1 ); + assertEquals( courseExpected.getDescription(), dto.getDescription() ); + assertEquals( shermanExpected.getName(), dto.getName() ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - StudentDTO dto = ( StudentDTO ) resultList.get( 0 ); - assertEquals( courseExpected.getDescription(), dto.getDescription() ); - assertEquals( yogiExpected.getName(), dto.getName() ); - dto = ( StudentDTO ) resultList.get( 1 ); - assertEquals( courseExpected.getDescription(), dto.getDescription() ); - assertEquals( shermanExpected.getName(), dto.getName() ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, false ); + runTest( criteriaExecutor, checker, false ); } @Test public void testOneSelectNewNoAliasesList() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { - protected JpaCriteriaQuery getCriteria(Session s) throws Exception { - throw new NotYetImplementedFor6Exception( ); + + @Override + protected ResultTransformer getResultTransformer() throws Exception { + return new AliasToBeanConstructorResultTransformer( getConstructor() ); + } + + @Override + protected JpaCriteriaQuery getCriteria(Session s) { + CriteriaBuilder builder = s.getCriteriaBuilder(); + JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery(); + Root root = criteria.from( Student.class ); + + criteria.select( root.get( "name" ) ); + + criteria.orderBy( builder.asc( root.get( "studentNumber" ) ) ); + return criteria; + // return s.createCriteria( Student.class, "s" ) // .setProjection( Projections.property( "s.name" ) ) // .addOrder( Order.asc( "s.studentNumber" ) ) // .setResultTransformer( new AliasToBeanConstructorResultTransformer( getConstructor() ) ); } + private Constructor getConstructor() throws NoSuchMethodException { return StudentDTO.class.getConstructor( PersonName.class ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select new org.hibernate.test.querycache.StudentDTO(s.name) from Student s order by s.studentNumber" ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + StudentDTO yogi = (StudentDTO) resultList.get( 0 ); + assertNull( yogi.getDescription() ); + assertEquals( yogiExpected.getName(), yogi.getName() ); + StudentDTO sherman = (StudentDTO) resultList.get( 1 ); + assertEquals( shermanExpected.getName(), sherman.getName() ); + assertNull( sherman.getDescription() ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - StudentDTO yogi = ( StudentDTO ) resultList.get( 0 ); - assertNull( yogi.getDescription() ); - assertEquals( yogiExpected.getName(), yogi.getName() ); - StudentDTO sherman = ( StudentDTO ) resultList.get( 1 ); - assertEquals( shermanExpected.getName(), sherman.getName() ); - assertNull( sherman.getDescription() ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, false ); + runTest( criteriaExecutor, checker, false ); } @Test public void testOneSelectNewAliasesList() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { - protected JpaCriteriaQuery getCriteria(Session s) throws Exception { - throw new NotYetImplementedFor6Exception( getClass() ); + + @Override + protected ResultTransformer getResultTransformer() throws Exception { + return new AliasToBeanConstructorResultTransformer( getConstructor() ); + } + + @Override + protected JpaCriteriaQuery getCriteria(Session s) { + CriteriaBuilder builder = s.getCriteriaBuilder(); + JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery(); + Root root = criteria.from( Student.class ); + + criteria.select( root.get( "name" ) ); + + criteria.orderBy( builder.asc( root.get( "studentNumber" ) ) ); + return criteria; + // return s.createCriteria( Student.class, "s" ) // .setProjection( Projections.property( "s.name" ).as( "name" )) // .addOrder( Order.asc( "s.studentNumber" ) ) // .setResultTransformer( new AliasToBeanConstructorResultTransformer( getConstructor() ) ); } + private Constructor getConstructor() throws NoSuchMethodException { return StudentDTO.class.getConstructor( PersonName.class ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select new org.hibernate.test.querycache.StudentDTO(s.name) from Student s order by s.studentNumber" ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + StudentDTO yogi = (StudentDTO) resultList.get( 0 ); + assertNull( yogi.getDescription() ); + assertEquals( yogiExpected.getName(), yogi.getName() ); + StudentDTO sherman = (StudentDTO) resultList.get( 1 ); + assertEquals( shermanExpected.getName(), sherman.getName() ); + assertNull( sherman.getDescription() ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - StudentDTO yogi = ( StudentDTO ) resultList.get( 0 ); - assertNull( yogi.getDescription() ); - assertEquals( yogiExpected.getName(), yogi.getName() ); - StudentDTO sherman = ( StudentDTO ) resultList.get( 1 ); - assertEquals( shermanExpected.getName(), sherman.getName() ); - assertNull( sherman.getDescription() ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, false ); + runTest( criteriaExecutor, checker, false ); } @Test - public void testMultiSelectNewList() throws Exception{ + public void testMultiSelectNewList() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { - protected JpaCriteriaQuery getCriteria(Session s) throws Exception { - throw new NotYetImplementedFor6Exception( getClass() ); + @Override + protected ResultTransformer getResultTransformer() throws Exception { + return new AliasToBeanConstructorResultTransformer( getConstructor() ); + } + + @Override + protected JpaCriteriaQuery getCriteria(Session s) { + CriteriaBuilder builder = s.getCriteriaBuilder(); + JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery(); + Root root = criteria.from( Student.class ); + + criteria.multiselect( + root.get( "studentNumber" ).alias( "studentNumber" ), + root.get( "name" ).alias( "name" ) + ); + + criteria.orderBy( builder.asc( root.get( "studentNumber" ) ) ); + return criteria; + // return s.createCriteria( Student.class, "s" ) // .setProjection( // Projections.projectionList() @@ -2134,35 +1976,46 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // .addOrder( Order.asc( "s.studentNumber" ) ) // .setResultTransformer( new AliasToBeanConstructorResultTransformer( getConstructor() ) ); } + private Constructor getConstructor() throws NoSuchMethodException { - return Student.class.getConstructor( long.class, PersonName.class ); + return Student.class.getConstructor( long.class, PersonName.class ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select new Student(s.studentNumber, s.name) from Student s order by s.studentNumber" ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Student yogi = (Student) resultList.get( 0 ); + assertEquals( yogiExpected.getStudentNumber(), yogi.getStudentNumber() ); + assertEquals( yogiExpected.getName(), yogi.getName() ); + Student sherman = (Student) resultList.get( 1 ); + assertEquals( shermanExpected.getStudentNumber(), sherman.getStudentNumber() ); + assertEquals( shermanExpected.getName(), sherman.getName() ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - Student yogi = ( Student ) resultList.get( 0 ); - assertEquals( yogiExpected.getStudentNumber(), yogi.getStudentNumber() ); - assertEquals( yogiExpected.getName(), yogi.getName() ); - Student sherman = ( Student ) resultList.get( 1 ); - assertEquals( shermanExpected.getStudentNumber(), sherman.getStudentNumber() ); - assertEquals( shermanExpected.getName(), sherman.getName() ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, false ); + runTest( criteriaExecutor, checker, false ); } @Test public void testMultiSelectNewWithLiteralList() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { - protected JpaCriteriaQuery getCriteria(Session s) throws Exception { - throw new NotYetImplementedFor6Exception( getClass() ); + @Override + protected ResultTransformer getResultTransformer() throws Exception { + return new AliasToBeanConstructorResultTransformer( getConstructor() ); + } + + @Override + protected JpaCriteriaQuery getCriteria(Session s) { + CriteriaBuilder builder = s.getCriteriaBuilder(); + JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery( ); + Root root = criteria.from( Student.class ); + + criteria.multiselect( + builder.literal( 555 ).alias( "studentNumber" ), + root.get( "name" ).alias( "name" ) + ); + + criteria.orderBy( builder.asc( root.get( "studentNumber" ) ) ); + return criteria; + // return s.createCriteria( Student.class, "s" ) // .setProjection( // Projections.projectionList() @@ -2172,36 +2025,46 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // .addOrder( Order.asc( "s.studentNumber" ) ) // .setResultTransformer( new AliasToBeanConstructorResultTransformer( getConstructor() ) ); } + private Constructor getConstructor() throws NoSuchMethodException { return Student.class.getConstructor( long.class, PersonName.class ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select new Student(555L, s.name) from Student s order by s.studentNumber" ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Student yogi = (Student) resultList.get( 0 ); + assertEquals( 555L, yogi.getStudentNumber() ); + assertEquals( yogiExpected.getName(), yogi.getName() ); + Student sherman = (Student) resultList.get( 1 ); + assertEquals( 555L, sherman.getStudentNumber() ); + assertEquals( shermanExpected.getName(), sherman.getName() ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - Student yogi = ( Student ) resultList.get( 0 ); - assertEquals( 555L, yogi.getStudentNumber() ); - assertEquals( yogiExpected.getName(), yogi.getName() ); - Student sherman = ( Student ) resultList.get( 1 ); - assertEquals( 555L, sherman.getStudentNumber() ); - assertEquals( shermanExpected.getName(), sherman.getName() ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, false ); + runTest( criteriaExecutor, checker, false ); } @Test public void testMultiSelectNewListList() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { + @Override + protected ResultTransformer getResultTransformer() { + return Transformers.TO_LIST; + } + + @Override protected JpaCriteriaQuery getCriteria(Session s) { - throw new NotYetImplementedFor6Exception( getClass() ); + CriteriaBuilder builder = s.getCriteriaBuilder(); + JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery(); + Root root = criteria.from( Student.class ); + + criteria.multiselect( + root.get( "studentNumber" ).alias( "studentNumber" ), + root.get( "name" ).alias( "name" ) + ); + criteria.orderBy( builder.asc( root.get( "studentNumber" ) ) ); + return criteria; + // return s.createCriteria( Student.class, "s" ) // .setProjection( // Projections.projectionList() @@ -2212,31 +2075,35 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // .setResultTransformer( Transformers.TO_LIST ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select new list(s.studentNumber, s.name) from Student s order by s.studentNumber" ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + List yogiList = (List) resultList.get( 0 ); + assertEquals( yogiExpected.getStudentNumber(), yogiList.get( 0 ) ); + assertEquals( yogiExpected.getName(), yogiList.get( 1 ) ); + List shermanList = (List) resultList.get( 1 ); + assertEquals( shermanExpected.getStudentNumber(), shermanList.get( 0 ) ); + assertEquals( shermanExpected.getName(), shermanList.get( 1 ) ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - List yogiList = ( List ) resultList.get( 0 ); - assertEquals( yogiExpected.getStudentNumber(), yogiList.get( 0 ) ); - assertEquals( yogiExpected.getName(), yogiList.get( 1 ) ); - List shermanList = ( List ) resultList.get( 1 ); - assertEquals( shermanExpected.getStudentNumber(), shermanList.get( 0 ) ); - assertEquals( shermanExpected.getName(), shermanList.get( 1 ) ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, false ); + runTest( criteriaExecutor, checker, false ); } @Test public void testMultiSelectNewMapUsingAliasesList() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { + @Override protected JpaCriteriaQuery getCriteria(Session s) { - throw new NotYetImplementedFor6Exception( getClass() ); + CriteriaBuilder builder = s.getCriteriaBuilder(); + JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery(); + Root root = criteria.from( Student.class ); + + criteria.multiselect( + root.get( "studentNumber" ).alias( "sNumber" ), + root.get( "name" ).alias( "sName" ) + ); + + criteria.orderBy( builder.asc( root.get( "studentNumber" ) ) ); + return criteria; // return s.createCriteria( Student.class, "s" ) // .setProjection( @@ -2248,31 +2115,35 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select new map(s.studentNumber as sNumber, s.name as sName) from Student s order by s.studentNumber" ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Map yogiMap = (Map) resultList.get( 0 ); + assertEquals( yogiExpected.getStudentNumber(), yogiMap.get( "sNumber" ) ); + assertEquals( yogiExpected.getName(), yogiMap.get( "sName" ) ); + Map shermanMap = (Map) resultList.get( 1 ); + assertEquals( shermanExpected.getStudentNumber(), shermanMap.get( "sNumber" ) ); + assertEquals( shermanExpected.getName(), shermanMap.get( "sName" ) ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - Map yogiMap = ( Map ) resultList.get( 0 ); - assertEquals( yogiExpected.getStudentNumber(), yogiMap.get( "sNumber" ) ); - assertEquals( yogiExpected.getName(), yogiMap.get( "sName" ) ); - Map shermanMap = ( Map ) resultList.get( 1 ); - assertEquals( shermanExpected.getStudentNumber(), shermanMap.get( "sNumber" ) ); - assertEquals( shermanExpected.getName(), shermanMap.get( "sName" ) ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, false ); + runTest( criteriaExecutor, checker, false ); } @Test public void testMultiSelectNewMapUsingAliasesWithFetchJoinList() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { + @Override protected JpaCriteriaQuery getCriteria(Session s) { - throw new NotYetImplementedFor6Exception( getClass() ); + CriteriaBuilder builder = s.getCriteriaBuilder(); + JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery(); + Root root = criteria.from( Student.class ); + final Selection studentAlias = root.alias( "s" ); + final Selection pcAlias = root.join( "preferredCourse", JoinType.LEFT ).alias( "pc" ); + root.fetch( "enrolments", JoinType.LEFT ); + + criteria.multiselect( studentAlias, pcAlias ); + + criteria.orderBy( builder.asc( root.get( "studentNumber" ) ) ); + return criteria; // return s.createCriteria( Student.class, "s" ) // .createAlias( "s.preferredCourse", "pc", Criteria.LEFT_JOIN ) @@ -2281,107 +2152,44 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP ); } }; - HqlExecutor hqlSelectNewMapExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select new map(s as s, pc as pc) from Student s left join s.preferredCourse pc left join fetch s.enrolments order by s.studentNumber" ); - } - }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - Map yogiMap = ( Map ) resultList.get( 0 ); - assertEquals( yogiExpected, yogiMap.get( "s" ) ); - assertEquals( yogiExpected.getPreferredCourse(), yogiMap.get( "pc" ) ); - Map shermanMap = ( Map ) resultList.get( 1 ); - assertEquals( shermanExpected, shermanMap.get( "s" ) ); - assertNull( shermanMap.get( "pc" ) ); - if ( areDynamicNonLazyAssociationsChecked() ) { - assertTrue( Hibernate.isInitialized( ( ( Student ) yogiMap.get( "s" ) ).getEnrolments() ) ); - assertEquals( yogiExpected.getEnrolments(), ( ( Student ) yogiMap.get( "s" ) ).getEnrolments() ); - assertTrue( Hibernate.isInitialized( ( ( Student ) shermanMap.get( "s" ) ).getEnrolments() ) ); - assertEquals( shermanExpected.getEnrolments(), ( ( ( Student ) shermanMap.get( "s" ) ).getEnrolments() ) ); - } - } - }; - runTest( hqlSelectNewMapExecutor, criteriaExecutor, checker, false ); - } - - @Test - public void testMultiSelectAliasToEntityMapUsingAliasesWithFetchJoinList() throws Exception { - CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { - protected JpaCriteriaQuery getCriteria(Session s) { - throw new NotYetImplementedFor6Exception( getClass() ); - -// return s.createCriteria( Student.class, "s" ) -// .createAlias( "s.preferredCourse", "pc", Criteria.LEFT_JOIN ) -// .setFetchMode( "enrolments", FetchMode.JOIN ) -// .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP ); - } - }; - HqlExecutor hqlAliasToEntityMapExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select s as s, pc as pc from Student s left join s.preferredCourse pc left join fetch s.enrolments order by s.studentNumber" ) - .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP ); - } - }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - Map yogiMap = ( Map ) resultList.get( 0 ); - assertEquals( yogiExpected, yogiMap.get( "s" ) ); + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Map yogiMap = (Map) resultList.get( 0 ); + assertEquals( yogiExpected, yogiMap.get( "s" ) ); + assertEquals( yogiExpected.getPreferredCourse(), yogiMap.get( "pc" ) ); + Map shermanMap = (Map) resultList.get( 1 ); + assertEquals( shermanExpected, shermanMap.get( "s" ) ); + assertNull( shermanMap.get( "pc" ) ); + if ( areDynamicNonLazyAssociationsChecked() ) { + assertTrue( Hibernate.isInitialized( ( (Student) yogiMap.get( "s" ) ).getEnrolments() ) ); + assertEquals( yogiExpected.getEnrolments(), ( (Student) yogiMap.get( "s" ) ).getEnrolments() ); + assertTrue( Hibernate.isInitialized( ( (Student) shermanMap.get( "s" ) ).getEnrolments() ) ); assertEquals( - yogiExpected.getPreferredCourse().getCourseCode(), - ( ( Course ) yogiMap.get( "pc" ) ).getCourseCode() + shermanExpected.getEnrolments(), + ( ( (Student) shermanMap.get( "s" ) ).getEnrolments() ) ); - Map shermanMap = ( Map ) resultList.get( 1 ); - assertEquals( shermanExpected, shermanMap.get( "s" ) ); - assertNull( shermanMap.get( "pc" ) ); - if ( areDynamicNonLazyAssociationsChecked() ) { - assertEquals( yogiExpected.getPreferredCourse(), yogiMap.get( "pc" ) ); - assertTrue( Hibernate.isInitialized( ( ( Student ) yogiMap.get( "s" ) ).getEnrolments() ) ); - assertEquals( yogiExpected.getEnrolments(), ( ( Student ) yogiMap.get( "s" ) ).getEnrolments() ); - assertTrue( Hibernate.isInitialized( ( ( Student ) shermanMap.get( "s" ) ).getEnrolments() ) ); - assertEquals( shermanExpected.getEnrolments(), ( ( ( Student ) shermanMap.get( "s" ) ).getEnrolments() ) ); - } } }; - runTest( hqlAliasToEntityMapExecutor, null, checker, false ); - } - - @Test - public void testMultiSelectUsingImplicitJoinWithFetchJoinListHql() throws Exception { - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select s as s, s.preferredCourse as pc from Student s left join fetch s.enrolments" ); - } - }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - assertTrue( results instanceof Object[] ); - Object[] yogiObjects = ( Object[] ) results; - assertEquals( 2, yogiObjects.length ); - assertEquals( yogiExpected, yogiObjects[ 0 ] ); - assertEquals( - yogiExpected.getPreferredCourse().getCourseCode(), - ( ( Course ) yogiObjects[ 1 ] ).getCourseCode() - ); - if ( areDynamicNonLazyAssociationsChecked() ) { - assertEquals( yogiExpected.getPreferredCourse(), yogiObjects[ 1 ] ); - assertTrue( Hibernate.isInitialized( ( ( Student ) yogiObjects[ 0 ] ).getEnrolments() ) ); - assertEquals( yogiExpected.getEnrolments(), ( ( Student ) yogiObjects[ 0 ] ).getEnrolments() ); - } - } - }; - runTest( hqlExecutor, null, checker, true ); + runTest( criteriaExecutor, checker, false ); } @Test public void testSelectNewMapUsingAliasesList() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { + @Override protected JpaCriteriaQuery getCriteria(Session s) { - throw new NotYetImplementedFor6Exception( getClass() ); + CriteriaBuilder builder = s.getCriteriaBuilder(); + JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery(); + Root root = criteria.from( Student.class ); + + criteria.multiselect( + root.get( "studentNumber" ).alias( "sNumber" ), + root.get( "name" ).alias( "sName" ) + ); + + criteria.orderBy( builder.asc( root.get( "studentNumber" ) ) ); + return criteria; // return s.createCriteria( Student.class, "s" ) // .setProjection( @@ -2393,31 +2201,43 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select new map(s.studentNumber as sNumber, s.name as sName) from Student s order by s.studentNumber" ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Map yogiMap = (Map) resultList.get( 0 ); + assertEquals( yogiExpected.getStudentNumber(), yogiMap.get( "sNumber" ) ); + assertEquals( yogiExpected.getName(), yogiMap.get( "sName" ) ); + Map shermanMap = (Map) resultList.get( 1 ); + assertEquals( shermanExpected.getStudentNumber(), shermanMap.get( "sNumber" ) ); + assertEquals( shermanExpected.getName(), shermanMap.get( "sName" ) ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - Map yogiMap = ( Map ) resultList.get( 0 ); - assertEquals( yogiExpected.getStudentNumber(), yogiMap.get( "sNumber" ) ); - assertEquals( yogiExpected.getName(), yogiMap.get( "sName" ) ); - Map shermanMap = ( Map ) resultList.get( 1 ); - assertEquals( shermanExpected.getStudentNumber(), shermanMap.get( "sNumber" ) ); - assertEquals( shermanExpected.getName(), shermanMap.get( "sName" ) ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, false ); + runTest( criteriaExecutor, checker, false ); } @Test public void testSelectNewEntityConstructorList() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { + @Override + protected ResultTransformer getResultTransformer() { + return new AliasToBeanConstructorResultTransformer( getConstructor() ); + } + + @Override protected JpaCriteriaQuery getCriteria(Session s) { - throw new NotYetImplementedFor6Exception( getClass() ); + + CriteriaBuilder builder = s.getCriteriaBuilder(); + JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery(); + Root root = criteria.from( Student.class ); + + criteria.multiselect( + root.get( "studentNumber" ).alias( "sNumber" ), + root.get( "name" ).alias( "name" ) + ); + + criteria.orderBy( builder.asc( root.get( "studentNumber" ) ) ); + return criteria; + + // return s.createCriteria( Student.class, "s" ) // .setProjection( // Projections.projectionList() @@ -2427,37 +2247,40 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // .addOrder( Order.asc( "s.studentNumber" ) ) // .setResultTransformer( new AliasToBeanConstructorResultTransformer( getConstructor() ) ); } + private Constructor getConstructor() { Type studentNametype = sessionFactory() .getEntityPersister( Student.class.getName() ) .getPropertyType( "name" ); - return ReflectHelper.getConstructor( Student.class, new Type[] {StandardBasicTypes.LONG, studentNametype} ); + return ReflectHelper.getConstructor( + Student.class, + new Type[] { StandardBasicTypes.LONG, studentNametype } + ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select new Student(s.studentNumber, s.name) from Student s order by s.studentNumber" ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + Student yogi = (Student) resultList.get( 0 ); + assertEquals( yogiExpected.getStudentNumber(), yogi.getStudentNumber() ); + assertEquals( yogiExpected.getName(), yogi.getName() ); + Student sherman = (Student) resultList.get( 1 ); + assertEquals( shermanExpected.getStudentNumber(), sherman.getStudentNumber() ); + assertEquals( shermanExpected.getName(), sherman.getName() ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - Student yogi = ( Student ) resultList.get( 0 ); - assertEquals( yogiExpected.getStudentNumber(), yogi.getStudentNumber() ); - assertEquals( yogiExpected.getName(), yogi.getName() ); - Student sherman = ( Student ) resultList.get( 1 ); - assertEquals( shermanExpected.getStudentNumber(), sherman.getStudentNumber() ); - assertEquals( shermanExpected.getName(), sherman.getName() ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, false ); + runTest( criteriaExecutor, checker, false ); } @Test public void testMapKeyList() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { + @Override + protected ResultTransformer getResultTransformer() { + return null; + } + + @Override protected JpaCriteriaQuery getCriteria(Session s) { CriteriaBuilder builder = s.getCriteriaBuilder(); JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery(); @@ -2471,443 +2294,102 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu // .setProjection( Projections.property( "a.addressType" ) ); } }; - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select key(s.addresses) from Student s" ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + assertTrue( resultList.contains( "home" ) ); + assertTrue( resultList.contains( "work" ) ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - assertTrue( resultList.contains( "home" ) ); - assertTrue( resultList.contains( "work" ) ); - } - }; - runTest( hqlExecutor, criteriaExecutor, checker, false ); - } - - @Test - public void testMapValueList() throws Exception { - /* - CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { - protected Criteria getCriteria(Session s) { - return s.createCriteria( Student.class, "s" ) - .createAlias( "s.addresses", "a" ) - .setProjection( Projections.property( "s.addresses" )); - } - }; - */ - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select value(s.addresses) from Student s" ); - } - }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - assertTrue( resultList.contains( yogiExpected.getAddresses().get( "home" ) ) ); - assertTrue( resultList.contains( yogiExpected.getAddresses().get( "work" ) ) ); - } - }; - runTest( hqlExecutor, null, checker, false ); - } - - @Test - public void testMapEntryList() throws Exception { - /* - CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { - protected Criteria getCriteria(Session s) { - return s.createCriteria( Student.class, "s" ) - .createAlias( "s.addresses", "a" ) - .setProjection( - Projections.projectionList() - .add( Projections.property( "a.addressType" ) ) - .add( Projections.property( "s.addresses" ).as( "a" ) ); - ) - } - }; - */ - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select entry(s.addresses) from Student s" ); - } - }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - Iterator it=resultList.iterator(); - assertTrue( resultList.get( 0 ) instanceof Map.Entry ); - Map.Entry entry = ( Map.Entry ) it.next(); - if ( "home".equals( entry.getKey() ) ) { - assertTrue( yogiExpected.getAddresses().get( "home" ).equals( entry.getValue() ) ); - entry = ( Map.Entry ) it.next(); - assertTrue( yogiExpected.getAddresses().get( "work" ).equals( entry.getValue() ) ); - } - else { - assertTrue( "work".equals( entry.getKey() ) ); - assertTrue( yogiExpected.getAddresses().get( "work" ).equals( entry.getValue() ) ); - entry = ( Map.Entry ) it.next(); - assertTrue( yogiExpected.getAddresses().get( "home" ).equals( entry.getValue() ) ); - } - } - }; - runTest( hqlExecutor, null, checker, false ); + runTest( criteriaExecutor, checker, false ); } @Test public void testMapElementsList() throws Exception { - /* CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { - protected Criteria getCriteria(Session s) { - return s.createCriteria( Student.class, "s" ) - .createAlias( "s.addresses", "a", Criteria.INNER_JOIN ) - .setProjection( Projections.property( "s.addresses" ) ); + @Override + protected ResultTransformer getResultTransformer() { + return null; + } + + @Override + protected JpaCriteriaQuery getCriteria(Session s) { + + CriteriaBuilder builder = s.getCriteriaBuilder(); + JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery(); + Root root = criteria.from( Student.class ); + + root.join( "addresses", JoinType.INNER ); + + criteria.select( root.get( "addresses" ) ); + /* + s.createCriteria( Student.class, "s" ) + .createAlias( "s.addresses", "a", Criteria.INNER_JOIN ) + .setProjection( Projections.property( "s.addresses" ) ); + */ + return criteria; } }; - */ - HqlExecutor hqlExecutor = new HqlExecutor() { - public Query getQuery(Session s) { - return s.createQuery( "select elements(a) from Student s inner join s.addresses a" ); - } + ResultChecker checker = results -> { + List resultList = (List) results; + assertEquals( 2, resultList.size() ); + assertTrue( resultList.contains( yogiExpected.getAddresses().get( "home" ) ) ); + assertTrue( resultList.contains( yogiExpected.getAddresses().get( "work" ) ) ); }; - ResultChecker checker = new ResultChecker() { - public void check(Object results) { - List resultList = ( List ) results; - assertEquals( 2, resultList.size() ); - assertTrue( resultList.contains( yogiExpected.getAddresses().get( "home" ) ) ); - assertTrue( resultList.contains( yogiExpected.getAddresses().get( "work" ) ) ); - } - }; - runTest( hqlExecutor, null, checker, false ); + runTest( criteriaExecutor, checker, false ); } - protected void runTest(HqlExecutor hqlExecutor, CriteriaExecutor criteriaExecutor, ResultChecker checker, boolean isSingleResult) - throws Exception { + private boolean isQueryCacheGetEnabled() { + return getQueryCacheMode() == CacheMode.NORMAL || + getQueryCacheMode() == CacheMode.GET; + } + + private boolean isQueryCachePutEnabled() { + return getQueryCacheMode() == CacheMode.NORMAL || + getQueryCacheMode() == CacheMode.PUT; + } + + protected void runTest(QueryExecutor queryExecutor, ResultChecker resultChecker, boolean isSingleResult) + throws Exception { createData(); try { - if ( criteriaExecutor != null ) { - runTest( criteriaExecutor, checker, isSingleResult ); - } - if ( hqlExecutor != null ) { - runTest( hqlExecutor, checker, isSingleResult ); - } + clearCache(); + clearStatistics(); + + Object results = queryExecutor.execute( isSingleResult ); + + assertHitCount( 0 ); + assertMissCount( isQueryCacheGetEnabled() ? 1 : 0 ); + assertPutCount( isQueryCachePutEnabled() ? 1 : 0 ); + clearStatistics(); + + resultChecker.check( results ); + + // check again to make sure nothing got initialized while checking results; + assertHitCount( 0 ); + assertMissCount( 0 ); + assertPutCount( 0 ); + clearStatistics(); + + results = queryExecutor.execute( isSingleResult ); + + assertHitCount( isQueryCacheGetEnabled() ? 1 : 0 ); + assertMissCount( 0 ); + assertPutCount( !isQueryCacheGetEnabled() && isQueryCachePutEnabled() ? 1 : 0 ); + clearStatistics(); + + resultChecker.check( results ); + + // check again to make sure nothing got initialized while checking results; + assertHitCount( 0 ); + assertMissCount( 0 ); + assertPutCount( 0 ); + clearStatistics(); } finally { deleteData(); } } - private boolean isQueryCacheGetEnabled() { - return getQueryCacheMode() == CacheMode.NORMAL || - getQueryCacheMode() == CacheMode.GET; - } - - private boolean isQueryCachePutEnabled() { - return getQueryCacheMode() == CacheMode.NORMAL || - getQueryCacheMode() == CacheMode.PUT; - } - - protected void runTest(QueryExecutor queryExecutor, ResultChecker resultChecker, boolean isSingleResult) throws Exception{ - clearCache(); - clearStatistics(); - - Object results = queryExecutor.execute( isSingleResult ); - - assertHitCount( 0 ); - assertMissCount( isQueryCacheGetEnabled() ? 1 : 0 ); - assertPutCount( isQueryCachePutEnabled() ? 1 : 0 ); - clearStatistics(); - - resultChecker.check( results ); - - // check again to make sure nothing got initialized while checking results; - assertHitCount( 0 ); - assertMissCount( 0 ); - assertPutCount( 0 ); - clearStatistics(); - - results = queryExecutor.execute( isSingleResult ); - - assertHitCount( isQueryCacheGetEnabled() ? 1 : 0 ); - assertMissCount( 0 ); - assertPutCount( ! isQueryCacheGetEnabled() && isQueryCachePutEnabled() ? 1 : 0 ); - clearStatistics(); - - resultChecker.check( results ); - - // check again to make sure nothing got initialized while checking results; - assertHitCount( 0 ); - assertMissCount( 0 ); - assertPutCount( 0 ); - clearStatistics(); - } - -// private void multiPropProjectionNoTransformerDynNonLazy(CacheMode sessionCacheMode, -// boolean isCacheableQuery) { -// Session s = openSession(); -// s.setCacheMode( sessionCacheMode ); -// Transaction t = s.beginTransaction(); -// List resultList = s.createCriteria( Enrolment.class ) -// .setCacheable( isCacheableQuery ) -// .setFetchMode( "student", FetchMode.JOIN ) -// .setProjection( -// Projections.projectionList() -// .add( Property.forName( "student" ), "student" ) -// .add( Property.forName( "semester" ), "semester" ) -// .add( Property.forName( "year" ), "year" ) -// .add( Property.forName( "course" ), "course" ) -// ) -// .addOrder( Order.asc( "studentNumber") ) -// .list(); -// t.commit(); -// s.close(); -// -// assertEquals( 2, resultList.size() ); -// Object[] yogiObjects = ( Object[] ) resultList.get( 0 ); -// Object[] shermanObjects = ( Object[] ) resultList.get( 1 ); -// assertEquals( 4, yogiObjects.length ); -// assertTrue( yogiObjects[ 0 ] instanceof Student ); -// assertTrue( Hibernate.isInitialized( yogiObjects[ 0 ] ) ); -// assertEquals( yogiEnrolmentExpected.getSemester(), ( (Short) yogiObjects[ 1 ] ).shortValue() ); -// assertEquals( yogiEnrolmentExpected.getYear(), ( (Short) yogiObjects[ 2 ] ).shortValue() ); -// assertEquals( courseExpected, yogiObjects[ 3 ] ); -// assertTrue( shermanObjects[ 0 ] instanceof Student ); -// assertTrue( Hibernate.isInitialized( shermanObjects[ 0 ] ) ); -// assertEquals( shermanEnrolmentExpected.getSemester(), ( (Short) shermanObjects[ 1 ] ).shortValue() ); -// assertEquals( shermanEnrolmentExpected.getYear(), ( (Short) shermanObjects[ 2 ] ).shortValue() ); -// assertTrue( ! ( shermanObjects[ 3 ] instanceof HibernateProxy ) ); -// assertTrue( shermanObjects[ 3 ] instanceof Course ); -// assertEquals( courseExpected, shermanObjects[ 3 ] ); -// } - -/* - { - - assertEquals( 2, resultList.size() ); - Object[] yogiObjects = ( Object[] ) resultList.get( 0 ); - Object[] shermanObjects = ( Object[] ) resultList.get( 1 ); - assertEquals( 4, yogiObjects.length ); - assertEquals( yogiExpected, ( Student ) yogiObjects[ 0 ] ); - assertEquals( yogiEnrolmentExpected.getSemester(), ( (Short) yogiObjects[ 1 ] ).shortValue() ); - assertEquals( yogiEnrolmentExpected.getYear(), ( (Short) yogiObjects[ 2 ] ).shortValue() ); - assertEquals( courseExpected, yogiObjects[ 3 ] ); - assertEquals( shermanExpected, ( Student ) shermanObjects[ 0 ] ); - assertEquals( shermanEnrolmentExpected.getSemester(), ( (Short) shermanObjects[ 1 ] ).shortValue() ); - assertEquals( shermanEnrolmentExpected.getYear(), ( (Short) shermanObjects[ 2 ] ).shortValue() ); - assertEquals( courseExpected, shermanObjects[ 3 ] ); - - } - -*/ -/* - private void executeProperty() { - resultList = s.createCriteria( Student.class ) - .setCacheable( true ) - .setProjection( - Projections.projectionList() - .add( Projections.id().as( "studentNumber" ) ) - .add( Property.forName( "name" ), "name" ) - .add( Property.forName( "cityState" ), "cityState" ) - .add( Property.forName( "preferredCourse" ), "preferredCourse" ) - ) - .list(); - assertEquals( 2, resultList.size() ); - for ( Iterator it = resultList.iterator(); it.hasNext(); ) { - Object[] objects = ( Object[] ) it.next(); - assertEquals( 4, objects.length ); - assertTrue( objects[0] instanceof Long ); - assertTrue( objects[1] instanceof String ); - if ( "yogiExpected King".equals( objects[1] ) ) { - assertTrue( objects[2] instanceof Name ); - assertTrue( objects[3] instanceof Course ); - } - else { - assertNull( objects[2] ); - assertNull( objects[3] ); - } - } - - Object[] aResult = ( Object[] ) s.createCriteria( Student.class ) - .setCacheable( true ) - .add( Restrictions.idEq( new Long( 667 ) ) ) - .setProjection( - Projections.projectionList() - .add( Projections.id().as( "studentNumber" ) ) - .add( Property.forName( "name" ), "name" ) - .add( Property.forName( "cityState" ), "cityState" ) - .add( Property.forName( "preferredCourse" ), "preferredCourse" ) - ) - .uniqueResult(); - assertNotNull( aResult ); - assertEquals( 4, aResult.length ); - assertTrue( aResult[0] instanceof Long ); - assertTrue( aResult[1] instanceof String ); - assertTrue( aResult[2] instanceof Name ); - assertTrue( aResult[3] instanceof Course ); - - Long count = ( Long ) s.createCriteria( Enrolment.class ) - .setCacheable( true ) - .setProjection( Property.forName( "studentNumber" ).count().setDistinct() ) - .uniqueResult(); - assertEquals( count, new Long( 2 ) ); - - Object object = s.createCriteria( Enrolment.class ) - .setCacheable( true ) - .setProjection( - Projections.projectionList() - .add( Property.forName( "studentNumber" ).count() ) - .add( Property.forName( "studentNumber" ).max() ) - .add( Property.forName( "studentNumber" ).min() ) - .add( Property.forName( "studentNumber" ).avg() ) - ) - .uniqueResult(); - Object[] result = ( Object[] ) object; - - assertEquals( new Long( 2 ), result[0] ); - assertEquals( new Long( 667 ), result[1] ); - assertEquals( new Long( 101 ), result[2] ); - assertEquals( 384.0, ( ( Double ) result[3] ).doubleValue(), 0.01 ); - - - s.createCriteria( Enrolment.class ) - .setCacheable( true ) - .add( Property.forName( "studentNumber" ).gt( new Long( 665 ) ) ) - .add( Property.forName( "studentNumber" ).lt( new Long( 668 ) ) ) - .add( Property.forName( "courseCode" ).like( "HIB", MatchMode.START ) ) - .add( Property.forName( "year" ).eq( new Short( ( short ) 1999 ) ) ) - .addOrder( Property.forName( "studentNumber" ).asc() ) - .uniqueResult(); - - List resultWithMaps = s.createCriteria( Enrolment.class ) - .setCacheable( true ) - .setProjection( - Projections.projectionList() - .add( Property.forName( "studentNumber" ).as( "stNumber" ) ) - .add( Property.forName( "courseCode" ).as( "cCode" ) ) - ) - .add( Property.forName( "studentNumber" ).gt( new Long( 665 ) ) ) - .add( Property.forName( "studentNumber" ).lt( new Long( 668 ) ) ) - .addOrder( Property.forName( "studentNumber" ).asc() ) - .setResultTransformer( Criteria.ALIAS_TO_ENTITY_MAP ) - .list(); - - assertEquals( 1, resultWithMaps.size() ); - Map m1 = ( Map ) resultWithMaps.get( 0 ); - - assertEquals( new Long( 667 ), m1.get( "stNumber" ) ); - assertEquals( courseExpected.getCourseCode(), m1.get( "cCode" ) ); - - resultWithMaps = s.createCriteria( Enrolment.class ) - .setCacheable( true ) - .setProjection( Property.forName( "studentNumber" ).as( "stNumber" ) ) - .addOrder( Order.desc( "stNumber" ) ) - .setResultTransformer( Criteria.ALIAS_TO_ENTITY_MAP ) - .list(); - - assertEquals( 2, resultWithMaps.size() ); - Map m0 = ( Map ) resultWithMaps.get( 0 ); - m1 = ( Map ) resultWithMaps.get( 1 ); - - assertEquals( new Long( 101 ), m1.get( "stNumber" ) ); - assertEquals( new Long( 667 ), m0.get( "stNumber" ) ); - - List resultWithAliasedBean = s.createCriteria( Enrolment.class ) - .setCacheable( true ) - .createAlias( "student", "st" ) - .createAlias( "courseExpected", "co" ) - .setProjection( - Projections.projectionList() - .add( Property.forName( "st.name" ).as( "studentName" ) ) - .add( Property.forName( "co.description" ).as( "courseDescription" ) ) - ) - .addOrder( Order.desc( "studentName" ) ) - .setResultTransformer( Transformers.aliasToBean( StudentDTO.class ) ) - .list(); - - assertEquals( 2, resultWithAliasedBean.size() ); - - StudentDTO dto = ( StudentDTO ) resultWithAliasedBean.get( 0 ); - assertNotNull( dto.getDescription() ); - assertNotNull( dto.getName() ); - - CourseMeeting courseMeetingDto = ( CourseMeeting ) s.createCriteria( CourseMeeting.class ) - .setCacheable( true ) - .setProjection( - Projections.projectionList() - .add( Property.forName( "id" ).as( "id" ) ) - .add( Property.forName( "courseExpected" ).as( "courseExpected" ) ) - ) - .addOrder( Order.desc( "id" ) ) - .setResultTransformer( Transformers.aliasToBean( CourseMeeting.class ) ) - .uniqueResult(); - - assertNotNull( courseMeetingDto.getId() ); - assertEquals( courseExpected.getCourseCode(), courseMeetingDto.getId().getCourseCode() ); - assertEquals( "Monday", courseMeetingDto.getId().getDay() ); - assertEquals( "1313 Mockingbird Lane", courseMeetingDto.getId().getLocation() ); - assertEquals( 1, courseMeetingDto.getId().getPeriod() ); - assertEquals( courseExpected.getDescription(), courseMeetingDto.getCourse().getDescription() ); - - s.createCriteria( Student.class ) - .setCacheable( true ) - .add( Restrictions.like( "name", "yogiExpected", MatchMode.START ) ) - .addOrder( Order.asc( "name" ) ) - .createCriteria( "enrolments", "e" ) - .addOrder( Order.desc( "year" ) ) - .addOrder( Order.desc( "semester" ) ) - .createCriteria( "courseExpected", "c" ) - .addOrder( Order.asc( "description" ) ) - .setProjection( - Projections.projectionList() - .add( Property.forName( "this.name" ) ) - .add( Property.forName( "e.year" ) ) - .add( Property.forName( "e.semester" ) ) - .add( Property.forName( "c.courseCode" ) ) - .add( Property.forName( "c.description" ) ) - ) - .uniqueResult(); - - Projection p1 = Projections.projectionList() - .add( Property.forName( "studentNumber" ).count() ) - .add( Property.forName( "studentNumber" ).max() ) - .add( Projections.rowCount() ); - - Projection p2 = Projections.projectionList() - .add( Property.forName( "studentNumber" ).min() ) - .add( Property.forName( "studentNumber" ).avg() ) - .add( - Projections.sqlProjection( - "1 as constOne, count(*) as countStar", - new String[] { "constOne", "countStar" }, - new Type[] { Hibernate.INTEGER, Hibernate.INTEGER } - ) - ); - - Object[] array = ( Object[] ) s.createCriteria( Enrolment.class ) - .setCacheable( true ) - .setProjection( Projections.projectionList().add( p1 ).add( p2 ) ) - .uniqueResult(); - - assertEquals( array.length, 7 ); - - List list = s.createCriteria( Enrolment.class ) - .setCacheable( true ) - .createAlias( "student", "st" ) - .createAlias( "courseExpected", "co" ) - .setProjection( - Projections.projectionList() - .add( Property.forName( "co.courseCode" ).group() ) - .add( Property.forName( "st.studentNumber" ).count().setDistinct() ) - .add( Property.forName( "year" ).group() ) - ) - .list(); - - assertEquals( list.size(), 2 ); - } -*/ protected void clearCache() { sessionFactory().getCache().evictQueryRegions(); } @@ -2917,7 +2399,7 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu } protected void assertEntityFetchCount(int expected) { - int actual = ( int ) sessionFactory().getStatistics().getEntityFetchCount(); + int actual = (int) sessionFactory().getStatistics().getEntityFetchCount(); assertEquals( expected, actual ); } @@ -2927,32 +2409,32 @@ public abstract class AbstractQueryCacheResultTransformerTest extends BaseCoreFu } protected void assertHitCount(int expected) { - int actual = ( int ) sessionFactory().getStatistics().getQueryCacheHitCount(); + int actual = (int) sessionFactory().getStatistics().getQueryCacheHitCount(); assertEquals( expected, actual ); } protected void assertMissCount(int expected) { - int actual = ( int ) sessionFactory().getStatistics().getQueryCacheMissCount(); + int actual = (int) sessionFactory().getStatistics().getQueryCacheMissCount(); assertEquals( expected, actual ); } protected void assertPutCount(int expected) { - int actual = ( int ) sessionFactory().getStatistics().getQueryCachePutCount(); + int actual = (int) sessionFactory().getStatistics().getQueryCachePutCount(); assertEquals( expected, actual ); } protected void assertInsertCount(int expected) { - int inserts = ( int ) sessionFactory().getStatistics().getEntityInsertCount(); + int inserts = (int) sessionFactory().getStatistics().getEntityInsertCount(); assertEquals( "unexpected insert count", expected, inserts ); } protected void assertUpdateCount(int expected) { - int updates = ( int ) sessionFactory().getStatistics().getEntityUpdateCount(); + int updates = (int) sessionFactory().getStatistics().getEntityUpdateCount(); assertEquals( "unexpected update counts", expected, updates ); } protected void assertDeleteCount(int expected) { - int deletes = ( int ) sessionFactory().getStatistics().getEntityDeleteCount(); + int deletes = (int) sessionFactory().getStatistics().getEntityDeleteCount(); assertEquals( "unexpected delete counts", expected, deletes ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/test/querycache/CriteriaQueryCacheIgnoreResultTransformerTest.java b/hibernate-core/src/test/java/org/hibernate/test/querycache/CriteriaQueryCacheIgnoreResultTransformerTest.java index 9c123a7188..d663e1a6af 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/querycache/CriteriaQueryCacheIgnoreResultTransformerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/querycache/CriteriaQueryCacheIgnoreResultTransformerTest.java @@ -17,17 +17,4 @@ public class CriteriaQueryCacheIgnoreResultTransformerTest extends AbstractQuery return CacheMode.IGNORE; } - @Override - protected void runTest(HqlExecutor hqlExecutor, CriteriaExecutor criteriaExecutor, ResultChecker checker, boolean isSingleResult) - throws Exception { - createData(); - try { - if ( criteriaExecutor != null ) { - runTest( criteriaExecutor, checker, isSingleResult ); - } - } - finally { - deleteData(); - } - } } diff --git a/hibernate-core/src/test/java/org/hibernate/test/querycache/QueryCacheTest.java b/hibernate-core/src/test/java/org/hibernate/test/querycache/QueryCacheTest.java index e87a93ef3a..502afdc7ea 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/querycache/QueryCacheTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/querycache/QueryCacheTest.java @@ -1,789 +1,108 @@ -/* - * 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 . - */ package org.hibernate.test.querycache; -import java.io.Serializable; -import java.util.ArrayList; import java.util.List; -import java.util.Map; -import java.util.concurrent.Callable; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; - -import org.hibernate.EmptyInterceptor; import org.hibernate.Hibernate; -import org.hibernate.query.NativeQuery; -import org.hibernate.query.Query; -import org.hibernate.Session; -import org.hibernate.SessionBuilder; -import org.hibernate.Transaction; import org.hibernate.cfg.AvailableSettings; -import org.hibernate.stat.EntityStatistics; +import org.hibernate.orm.test.querycache.CompositeKey; +import org.hibernate.orm.test.querycache.EntityWithCompositeKey; +import org.hibernate.orm.test.querycache.EntityWithStringCompositeKey; +import org.hibernate.orm.test.querycache.Item; +import org.hibernate.orm.test.querycache.StringCompositeKey; import org.hibernate.stat.QueryStatistics; -import org.hibernate.stat.spi.StatisticsImplementor; -import org.hibernate.transform.Transformers; -import org.hibernate.type.Type; -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; -import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -/** - * @author Gavin King - * @author Brett Meyer - */ -public class QueryCacheTest extends BaseNonConfigCoreFunctionalTestCase { - - private static final CompositeKey PK = new CompositeKey(1, 2); - private static final ExecutorService executor = Executors.newFixedThreadPool(4); - - @Override - public String[] getMappings() { - return new String[] { "querycache/Item.hbm.xml" }; - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { +@DomainModel( + xmlMappings = "org/hibernate/orm/test/querycache/Item.hbm.xml", + annotatedClasses = { CompositeKey.class, EntityWithCompositeKey.class, StringCompositeKey.class, - EntityWithStringCompositeKey.class - }; - } - - @Override - protected void addSettings(Map settings) { - settings.put( AvailableSettings.USE_QUERY_CACHE, "true" ); - settings.put( AvailableSettings.CACHE_REGION_PREFIX, "foo" ); - settings.put( AvailableSettings.USE_SECOND_LEVEL_CACHE, "true" ); - settings.put( AvailableSettings.GENERATE_STATISTICS, "true" ); - } - - @Override - protected void shutDown() { - super.shutDown(); - executor.shutdown(); - } - - @Override - protected boolean isCleanupTestDataRequired() { - return true; - } - - @Override - protected String getCacheConcurrencyStrategy() { - return "nonstrict-read-write"; - } - - @Test - @TestForIssue( jiraKey = "HHH-5426" ) - public void testInvalidationFromBulkHQL() { - sessionFactory().getCache().evictQueryRegions(); - sessionFactory().getStatistics().clear(); - - Session s = openSession(); - List list = new ArrayList(); - s.beginTransaction(); - for (int i = 0; i < 3; i++) { - Item a = new Item(); - a.setName("a" + i); - a.setDescription("a" + i); - list.add(a); - s.persist(a); + EntityWithStringCompositeKey.class + }, + concurrencyStrategy = "nonstrict-read-write" +) +@SessionFactory(generateStatistics = true) +@ServiceRegistry( + settings = { + @Setting(name = AvailableSettings.USE_QUERY_CACHE, value = "true"), + @Setting(name = AvailableSettings.CACHE_REGION_PREFIX, value = "foo"), + @Setting(name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "true") } - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - String queryString = "select count(*) from Item"; - // this query will hit the database and create the cache - Long result = (Long) s.createQuery(queryString).setCacheable(true).uniqueResult(); - assertEquals(3, result.intValue()); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - String updateString = "delete from Item"; - s.createQuery(updateString).executeUpdate(); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - // and this one SHOULD not be served by the cache - Number result2 = (Number) s.createQuery(queryString).setCacheable(true).uniqueResult(); - assertEquals(0, result2.intValue()); - s.getTransaction().commit(); - s.close(); - } +) +public class QueryCacheTest { + /* + All the other tests of QueryCacheTest have been already moved into org.hibernate.orm test paxkage + */ @Test - @TestForIssue( jiraKey = "JBPAPP-4224" ) - public void testHitCacheInSameSession() { - sessionFactory().getCache().evictQueryRegions(); - sessionFactory().getStatistics().clear(); - Session s = openSession(); - List list = new ArrayList(); - s.beginTransaction(); - for ( int i = 0; i < 3; i++ ) { - Item a = new Item(); - a.setName( "a" + i ); - a.setDescription( "a" + i ); - list.add( a ); - s.persist( a ); - } - s.getTransaction().commit(); - -// s.close(); -// s=openSession(); - - s.beginTransaction(); - String queryString = "from Item"; - // this query will hit the database and create the cache - s.createQuery( queryString ).setCacheable( true ).list(); - s.getTransaction().commit(); - - s.beginTransaction(); - //and this one SHOULD served by the cache - s.createQuery( queryString ).setCacheable( true ).list(); - s.getTransaction().commit(); - QueryStatistics qs = s.getSessionFactory().getStatistics().getQueryStatistics( queryString ); - assertEquals( 1, qs.getCacheHitCount() ); - assertEquals( 1, qs.getCachePutCount() ); - s.close(); - s = openSession(); - s.beginTransaction(); - for(Object obj:list){ - s.delete( obj ); - } - s.getTransaction().commit(); - s.close(); - - } - - private static final String queryString = "from Item i where i.name='widget'"; - - @Test - public void testQueryCacheInvalidation() throws Exception { - sessionFactory().getCache().evictQueryRegions(); - - final StatisticsImplementor statistics = sessionFactory().getStatistics(); - statistics.clear(); - - final String queryString = "from Item i where i.name='widget'"; - - final QueryStatistics qs = statistics.getQueryStatistics( queryString ); - final EntityStatistics es = statistics.getEntityStatistics( Item.class.getName() ); - - Session s = openSession(); - Transaction t = s.beginTransaction(); - s.createQuery( queryString ).setCacheable(true).list(); - Item i = new Item(); - i.setName("widget"); - i.setDescription("A really top-quality, full-featured widget."); - s.save(i); - t.commit(); - s.close(); - - // hit -> 0 - // miss -> 1 - // put -> 1 - - assertEquals( es.getInsertCount(), 1 ); - assertEquals( es.getUpdateCount(), 0 ); - - assertEquals( statistics.getQueryCacheHitCount(), 0 ); - assertEquals( qs.getCacheHitCount(), 0 ); - - assertEquals( statistics.getQueryCacheMissCount(), 1 ); - assertEquals( qs.getCacheMissCount(), 1); - - assertEquals( statistics.getQueryCachePutCount(), 1 ); - assertEquals( qs.getCachePutCount(), 1); - - assertEquals( statistics.getQueryExecutionCount(), 1 ); - assertEquals( qs.getExecutionCount(), 1 ); - - assertEquals( statistics.getEntityFetchCount(), 0 ); - - - Thread.sleep(200); - - s = openSession(); - t = s.beginTransaction(); - List result = s.createQuery( queryString ).setCacheable(true).list(); - assertEquals( result.size(), 1 ); - t.commit(); - s.close(); - - // hit -> 0 - // miss -> 2 - // put -> 2 - - assertEquals( es.getInsertCount(), 1 ); - assertEquals( es.getUpdateCount(), 0 ); - - assertEquals( statistics.getQueryCacheHitCount(), 0 ); - assertEquals( qs.getCacheHitCount(), 0 ); - - assertEquals( statistics.getQueryCacheMissCount(), 2 ); - assertEquals( qs.getCacheMissCount(), 2 ); - - assertEquals( statistics.getQueryCachePutCount(), 2 ); - assertEquals( qs.getCachePutCount(), 2 ); - - assertEquals( statistics.getQueryExecutionCount(), 2 ); - assertEquals( qs.getExecutionCount(), 2 ); - - assertEquals( statistics.getEntityFetchCount(), 0 ); - - - s = openSession(); - t = s.beginTransaction(); - result = s.createQuery( queryString ).setCacheable(true).list(); - assertEquals( result.size(), 1 ); - t.commit(); - s.close(); - - // hit -> 1 - // miss -> 2 - // put -> 2 - - assertEquals( es.getInsertCount(), 1 ); - assertEquals( es.getUpdateCount(), 0 ); - - assertEquals( statistics.getQueryCacheHitCount(), 1 ); - assertEquals( qs.getCacheHitCount(), 1); - - assertEquals( statistics.getQueryCacheMissCount(), 2 ); - assertEquals( qs.getCacheMissCount(), 2 ); - - assertEquals( statistics.getQueryCachePutCount(), 2 ); - assertEquals( qs.getCachePutCount(), 2 ); - - assertEquals( statistics.getQueryExecutionCount(), 2 ); - assertEquals( qs.getExecutionCount(), 2 ); - - assertEquals( statistics.getEntityFetchCount(), 0 ); - - - assertEquals( qs.getCacheHitCount(), 1 ); - assertEquals( statistics.getEntityFetchCount(), 0 ); - - s = openSession(); - t = s.beginTransaction(); - result = s.createQuery( queryString ).setCacheable(true).list(); - assertEquals( result.size(), 1 ); - i = (Item) result.get(0); - assertTrue( Hibernate.isInitialized( i ) ); - assertTrue( s.contains( i ) ); - i.setName("Widget"); - s.flush(); - t.commit(); - s.close(); - - // hit -> 2 - // miss -> 2 - // put -> 2 - // - // + another invalidation - - assertEquals( es.getInsertCount(), 1 ); - assertEquals( es.getUpdateCount(), 1 ); - - assertEquals( statistics.getQueryCacheHitCount(), 2 ); - assertEquals( qs.getCacheHitCount(), 2 ); - - assertEquals( statistics.getQueryCacheMissCount(), 2 ); - assertEquals( qs.getCacheMissCount(), 2 ); - - assertEquals( statistics.getQueryCachePutCount(), 2 ); - assertEquals( qs.getCachePutCount(), 2 ); - - assertEquals( statistics.getQueryExecutionCount(), 2 ); - assertEquals( qs.getExecutionCount(), 2 ); - - assertEquals( statistics.getEntityFetchCount(), 0 ); - - - Thread.sleep(200); - - s = openSession(); - t = s.beginTransaction(); - result = s.createQuery( queryString ).setCacheable(true).list(); - i = (Item) s.get( Item.class, new Long(i.getId()) ); - - s.delete(i); - t.commit(); - s.close(); - - // hit -> 2 - // miss -> 3 - // put -> 3 - - - assertEquals( es.getInsertCount(), 1 ); - assertEquals( es.getUpdateCount(), 1 ); - - assertEquals( statistics.getQueryCacheHitCount(), 2 ); - assertEquals( qs.getCacheHitCount(), 2 ); - - assertEquals( statistics.getQueryCacheMissCount(), 3 ); - assertEquals( qs.getCacheMissCount(), 3 ); - - assertEquals( statistics.getQueryCachePutCount(), 3); - assertEquals( qs.getCachePutCount(), 3 ); - - assertEquals( statistics.getQueryExecutionCount(), 3); - assertEquals( qs.getExecutionCount(), 3 ); - - assertEquals( statistics.getEntityFetchCount(), 0 ); - assertEquals( es.getFetchCount(), 0 ); - - - assertEquals( qs.getCacheHitCount(), 2 ); - assertEquals( qs.getCacheMissCount(), 3 ); - assertEquals( qs.getCachePutCount(), 3 ); - assertEquals( qs.getExecutionCount(), 3 ); - assertEquals( es.getFetchCount(), 0 ); //check that it was being cached - - } - - @Test - @RequiresDialectFeature( - value = DialectChecks.CaseSensitiveCheck.class, - comment = "i.name='widget' should not match on case sensitive database." - ) - public void testCaseInsensitiveComparison() { - Session s = openSession(); - s.beginTransaction(); - Item i = new Item(); - i.setName( "Widget" ); - i.setDescription( "A really top-quality, full-featured widget." ); - s.save( i ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - List result = s.createQuery( queryString ).list(); - assertEquals(1, result.size()); - i = (Item) s.get( Item.class, new Long(i.getId()) ); - assertEquals( i.getName(), "Widget" ); - s.delete(i); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testQueryCacheFetch() throws Exception { - sessionFactory().getCache().evictQueryRegions(); - sessionFactory().getStatistics().clear(); + public void testQueryCacheFetch(SessionFactoryScope scope) throws Exception { + scope.getSessionFactory().getCache().evictQueryRegions(); + scope.getSessionFactory().getStatistics().clear(); // persist our 2 items. This saves them to the db, but also into the second level entity cache region - Session s = openSession(); - Transaction t = s.beginTransaction(); - Item i = new Item(); - i.setName("widget"); - i.setDescription("A really top-quality, full-featured widget."); - Item i2 = new Item(); - i2.setName("other widget"); - i2.setDescription("Another decent widget."); - s.persist(i); - s.persist(i2); - t.commit(); - s.close(); + scope.inTransaction( + session -> { + Item i = new Item(); + i.setName( "widget" ); + i.setDescription( "A really top-quality, full-featured widget." ); + Item i2 = new Item(); + i2.setName( "other widget" ); + i2.setDescription( "Another decent widget." ); + session.persist( i ); + session.persist( i2 ); + } + ); final String queryString = "from Item i where i.name like '%widget'"; - QueryStatistics qs = s.getSessionFactory().getStatistics().getQueryStatistics( queryString ); + QueryStatistics qs = scope.getSessionFactory().getStatistics().getQueryStatistics( queryString ); - Thread.sleep(200); + Thread.sleep( 200 ); // perform the cacheable query. this will execute the query (no query cache hit), but the Items will be // found in second level entity cache region - s = openSession(); - t = s.beginTransaction(); - List result = s.createQuery( queryString ).setCacheable( true ).list(); - assertEquals( result.size(), 2 ); - t.commit(); - s.close(); - assertEquals( qs.getCacheHitCount(), 0 ); - assertEquals( s.getSessionFactory().getStatistics().getEntityFetchCount(), 0 ); + scope.inTransaction( + session -> { + List result = session.createQuery( queryString ).setCacheable( true ).list(); + assertEquals( 2, result.size() ); + } + ); + assertEquals( 0, qs.getCacheHitCount() ); + assertEquals( 0, scope.getSessionFactory().getStatistics().getEntityFetchCount() ); // evict the Items from the second level entity cache region - sessionFactory().getCache().evictEntityRegion( Item.class ); + scope.getSessionFactory().getCache().evictEntityRegion( Item.class ); // now, perform the cacheable query again. this time we should not execute the query (query cache hit). // However, the Items will not be found in second level entity cache region this time (we evicted them above) // nor are they in associated with the session. - s = openSession(); - t = s.beginTransaction(); - result = s.createQuery( queryString ).setCacheable(true).list(); - assertEquals( result.size(), 2 ); - assertTrue( Hibernate.isInitialized( result.get(0) ) ); - assertTrue( Hibernate.isInitialized( result.get(1) ) ); - t.commit(); - s.close(); - - assertEquals( qs.getCacheHitCount(), 1 ); - assertEquals( s.getSessionFactory().getStatistics().getEntityFetchCount(), 1 ); - - s = openSession(); - t = s.beginTransaction(); - s.createQuery("delete Item").executeUpdate(); - t.commit(); - s.close(); - - } - - @Test - public void testProjectionCache() throws Exception { - sessionFactory().getCache().evictQueryRegions(); - sessionFactory().getStatistics().clear(); - - final String queryString = "select i.description as desc from Item i where i.name='widget'"; - - Session s = openSession(); - Transaction t = s.beginTransaction(); - s.createQuery( queryString ).setCacheable(true).list(); - Item i = new Item(); - i.setName("widget"); - i.setDescription("A really top-quality, full-featured widget."); - s.save(i); - t.commit(); - s.close(); - - QueryStatistics qs = s.getSessionFactory().getStatistics().getQueryStatistics( queryString ); - EntityStatistics es = s.getSessionFactory().getStatistics().getEntityStatistics( Item.class.getName() ); - - assertEquals( qs.getCacheHitCount(), 0 ); - assertEquals( qs.getCacheMissCount(), 1 ); - assertEquals( qs.getCachePutCount(), 1 ); - - Thread.sleep(200); - - s = openSession(); - t = s.beginTransaction(); - List result = s.createQuery( queryString ).setCacheable(true).list(); - assertEquals( result.size(), 1 ); - assertEquals( i.getDescription(), ( result.get( 0 ) ) ); - t.commit(); - s.close(); - - assertEquals( qs.getCacheHitCount(), 0 ); - assertEquals( qs.getCacheMissCount(), 2 ); - assertEquals( qs.getCachePutCount(), 2 ); - - s = openSession(); - t = s.beginTransaction(); - result = s.createQuery( queryString ).setCacheable(true).list(); - assertEquals( result.size(), 1 ); - assertEquals( i.getDescription(), result.get( 0 ) ); - t.commit(); - s.close(); - - assertEquals( qs.getCacheHitCount(), 1 ); - assertEquals( qs.getCacheMissCount(), 2 ); - assertEquals( qs.getCachePutCount(), 2 ); - - s = openSession(); - t = s.beginTransaction(); - result = s.createQuery( queryString ).setCacheable(true).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list(); - assertEquals( result.size(), 1 ); - Map m = (Map) result.get(0); - assertEquals( 1, m.size() ); - assertEquals( i.getDescription(), m.get( "desc" ) ); - t.commit(); - s.close(); - - assertEquals( "hit count should go up since data is not transformed until after it is cached", qs.getCacheHitCount(), 2 ); - assertEquals( qs.getCacheMissCount(), 2 ); - assertEquals( qs.getCachePutCount(), 2 ); - - s = openSession(); - t = s.beginTransaction(); - result = s.createQuery( queryString ).setCacheable(true).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list(); - assertEquals( result.size(), 1 ); - m = (Map) result.get(0); - assertEquals(1, m.size()); - assertEquals( i.getDescription(), m.get( "desc" ) ); - t.commit(); - s.close(); - - assertEquals( "hit count should go up since data is not transformed until after it is cachedr", qs.getCacheHitCount(), 3 ); - assertEquals( qs.getCacheMissCount(), 2 ); - assertEquals( qs.getCachePutCount(), 2 ); - - s = openSession(); - t = s.beginTransaction(); - result = s.createQuery( queryString ).setCacheable(true).list(); - assertEquals( result.size(), 1 ); - assertTrue( Hibernate.isInitialized( result.get(0) ) ); - i = (Item) s.get( Item.class, new Long(i.getId()) ); - i.setName("widget"); - i.setDescription("A middle-quality widget."); - t.commit(); - s.close(); - - assertEquals( qs.getCacheHitCount(), 4 ); - assertEquals( qs.getCacheMissCount(), 2 ); - assertEquals( qs.getCachePutCount(), 2 ); - - Thread.sleep(200); - - s = openSession(); - t = s.beginTransaction(); - result = s.createQuery( queryString ).setCacheable(true).list(); - assertEquals( result.size(), 1 ); - i = (Item) s.get( Item.class, new Long(i.getId()) ); - assertEquals( result.get(0), "A middle-quality widget." ); - - assertEquals( qs.getCacheHitCount(), 4 ); - assertEquals( qs.getCacheMissCount(), 3 ); - assertEquals( qs.getCachePutCount(), 3 ); - - s.delete(i); - t.commit(); - s.close(); - - assertEquals( qs.getCacheHitCount(), 4 ); - assertEquals( qs.getCacheMissCount(), 3 ); - assertEquals( qs.getCachePutCount(), 3 ); - assertEquals( qs.getExecutionCount(), 3 ); - assertEquals( es.getFetchCount(), 0 ); //check that it was being cached - } - - @Test - @TestForIssue( jiraKey = "HHH-4459" ) - public void testGetByCompositeId() { - Session s = openSession(); - s.beginTransaction(); - s.persist( new EntityWithCompositeKey( PK ) ); - Query query = s.createQuery( "FROM EntityWithCompositeKey e WHERE e.pk = :pk" ); - query.setCacheable( true ); - query.setParameter( "pk", PK ); - assertEquals(1, query.list().size( )); - s.getTransaction().rollback(); - s.close(); - - s = openSession(); - s.beginTransaction(); - EntityWithStringCompositeKey entity = new EntityWithStringCompositeKey(); - StringCompositeKey key = new StringCompositeKey(); - key.setAnalog( "foo1" ); - key.setDevice( "foo2" ); - key.setDeviceType( "foo3" ); - key.setSubstation( "foo4" ); - entity.setPk( key ); - s.persist( entity ); - CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); - CriteriaQuery criteria = criteriaBuilder.createQuery( EntityWithStringCompositeKey.class ); - Root root = criteria.from( EntityWithStringCompositeKey.class ); - criteria.where( criteriaBuilder.equal( root.get( "pk" ), key ) ); - s.createQuery( criteria ).setCacheable( true ); - - assertEquals( 1, s.createQuery( criteria ).list().size() ); -// Criteria c = s.createCriteria( -// EntityWithStringCompositeKey.class ).add( Restrictions.eq( -// "pk", key ) ); -// c.setCacheable( true ); -// assertEquals( 1, c.list().size() ); - s.getTransaction().rollback(); - s.close(); - } - - @Test - @TestForIssue( jiraKey = "HHH-3051" ) - public void testScalarSQLQuery() { - sessionFactory().getCache().evictQueryRegions(); - sessionFactory().getStatistics().clear(); - - Session s = openSession(); - s.beginTransaction(); - Item item = new Item(); - item.setName("fooName"); - item.setDescription("fooDescription"); - s.persist(item); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - - // Note: StandardQueryCache#put handles single results and multiple results differently. So, test both - // 1 and 2+ scalars. - - String sqlQuery = "select name, description from Items"; - NativeQuery query = s.createNativeQuery( sqlQuery); - query.setCacheable(true); - query.addScalar("name"); - query.addScalar("description"); - Object[] result1 = (Object[]) query.uniqueResult(); - assertNotNull( result1 ); - assertEquals( result1.length, 2 ); - assertEquals( result1[0], "fooName" ); - assertEquals( result1[1], "fooDescription" ); - - sqlQuery = "select name from Items"; - query = s.createNativeQuery(sqlQuery); - query.setCacheable(true); - query.addScalar("name"); - String result2 = (String) query.uniqueResult(); - assertNotNull( result2 ); - assertEquals( result2, "fooName" ); - - s.getTransaction().commit(); - s.close(); - } - -// @Test -// public void testGetByCompositeIdNoCache() { -// Query query = em.createQuery("FROM EntityWithCompositeKey e WHERE e.pk = :pk"); -// query.setParameter("pk", PK); -// assertEquals(1, query.getResultList().size()); -// } -// -// @Test -// public void testGetByEntityIself() { -// Query query = em.createQuery("FROM EntityWithCompositeKey e WHERE e = :ent"); -// query.setParameter("ent", new EntityWithCompositeKey(PK)); -// assertEquals(1, query.getResultList().size()); -// } - - @Test - @TestForIssue(jiraKey = "HHH-9962") - /* Test courtesy of Giambattista Bloisi */ - public void testDelayedLoad() throws InterruptedException, ExecutionException { - DelayLoadOperations interceptor = new DelayLoadOperations(); - final SessionBuilder sessionBuilder = sessionFactory().withOptions().interceptor(interceptor); - Item item1 = new Item(); - item1.setName("Item1"); - item1.setDescription("Washington"); - Session s1 = sessionBuilder.openSession(); - Transaction tx1 = s1.beginTransaction(); - s1.persist(item1); - tx1.commit(); - s1.close(); - - Item item2 = new Item(); - item2.setName("Item2"); - item2.setDescription("Chicago"); - Session s2 = sessionBuilder.openSession(); - Transaction tx2 = s2.beginTransaction(); - s2.persist(item2); - tx2.commit(); - s2.close(); - - interceptor.blockOnLoad(); - - Future fetchedItem = executor.submit(new Callable() { - public Item call() throws Exception { - return findByDescription(sessionBuilder, "Washington"); - } - }); - - // wait for the onLoad listener to be called - interceptor.waitOnLoad(); - - Session s3 = sessionBuilder.openSession(); - Transaction tx3 = s3.beginTransaction(); - item1.setDescription("New York"); - item2.setDescription("Washington"); - s3.update(item1); - s3.update(item2); - tx3.commit(); - s3.close(); - - interceptor.unblockOnLoad(); - - // the concurrent query was executed before the data was amended so - // let's expect "Item1" to be returned as living in Washington - Item fetched = fetchedItem.get(); - assertEquals("Item1", fetched.getName()); - - // Query again: now "Item2" is expected to live in Washington - fetched = findByDescription(sessionBuilder, "Washington"); - assertEquals("Item2", fetched.getName()); - } - - protected Item findByDescription(SessionBuilder sessionBuilder, final String description) { - Session s = sessionBuilder.openSession(); - try { - CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); - CriteriaQuery criteria = criteriaBuilder.createQuery( Item.class ); - Root root = criteria.from( Item.class ); - criteria.where( criteriaBuilder.equal( root.get( "description" ), description ) ); - - return s.createQuery( criteria ).setCacheable( true ).setReadOnly( true ).uniqueResult(); -// return (Item) s.createCriteria(Item.class) -// .setCacheable(true) -// .setReadOnly(true) -// .add(Restrictions.eq("description", description)) -// .uniqueResult(); - - } - finally { - s.close(); - } - } - - public class DelayLoadOperations extends EmptyInterceptor { - - private volatile CountDownLatch blockLatch; - private volatile CountDownLatch waitLatch; - - @Override - public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) { - // Synchronize load and update activities - try { - if (waitLatch != null) { - waitLatch.countDown(); + scope.inTransaction( + session -> { + List result = session.createQuery( queryString ).setCacheable( true ).list(); + assertEquals( 2, result.size() ); + assertTrue( Hibernate.isInitialized( result.get( 0 ) ) ); + assertTrue( Hibernate.isInitialized( result.get( 1 ) ) ); } - if (blockLatch != null) { - blockLatch.await(); - } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new RuntimeException(e); - } - return true; - } + ); - public void blockOnLoad() { - blockLatch = new CountDownLatch(1); - waitLatch = new CountDownLatch(1); - } + assertEquals( 1, qs.getCacheHitCount() ); + assertEquals( 1, scope.getSessionFactory().getStatistics().getEntityFetchCount() ); - public void waitOnLoad() throws InterruptedException { - waitLatch.await(); - } - - public void unblockOnLoad() { - if (blockLatch != null) { - blockLatch.countDown(); - } - } + scope.inTransaction( + session -> + session.createQuery( "delete Item" ).executeUpdate() + ); } + }