Search in sources :

Example 1 with Selection

use of jakarta.persistence.criteria.Selection in project hibernate-orm by hibernate.

the class TreatListJoinTest method testTreatJoin.

@Test
public void testTreatJoin() {
    EntityManager em = createEntityManager();
    try {
        final CriteriaBuilder cb = em.getCriteriaBuilder();
        final CriteriaQuery<Tuple> query = cb.createTupleQuery();
        final Root<TestEntity> testEntity = query.from(TestEntity.class);
        final List<Selection<?>> selections = new LinkedList();
        selections.add(testEntity.get("id"));
        final ListJoin<TestEntity, AbstractEntity> entities = testEntity.joinList("entities", JoinType.LEFT);
        entities.on(cb.equal(entities.get("entityType"), EntityA.class.getName()));
        final ListJoin<TestEntity, EntityA> joinEntityA = cb.treat(entities, EntityA.class);
        selections.add(joinEntityA.get("id"));
        selections.add(joinEntityA.get("valueA"));
        final ListJoin<TestEntity, AbstractEntity> entitiesB = testEntity.joinList("entities", JoinType.LEFT);
        entitiesB.on(cb.equal(entitiesB.get("entityType"), EntityB.class.getName()));
        final ListJoin<TestEntity, EntityB> joinEntityB = cb.treat(entitiesB, EntityB.class);
        selections.add(joinEntityB.get("id"));
        selections.add(joinEntityB.get("valueB"));
        query.multiselect(selections);
        final List<Tuple> resultList = em.createQuery(query).getResultList();
        assertThat(resultList.size(), is(10));
    } finally {
        em.close();
    }
}
Also used : CriteriaBuilder(jakarta.persistence.criteria.CriteriaBuilder) Selection(jakarta.persistence.criteria.Selection) LinkedList(java.util.LinkedList) EntityManager(jakarta.persistence.EntityManager) Tuple(jakarta.persistence.Tuple) Test(org.junit.Test)

Example 2 with Selection

use of jakarta.persistence.criteria.Selection in project hibernate-orm by hibernate.

the class AbstractQueryCacheResultTransformerTest method testJoinWithFetchJoinWithAliasedJoinedAndOwnerProjectedList.

@Test
public void testJoinWithFetchJoinWithAliasedJoinedAndOwnerProjectedList(SessionFactoryScope scope) 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(Object[].class);
            JpaRoot<Student> root = criteria.from(Student.class);
            final JpaSelection<Student> st = root.alias("s");
            root.fetch("enrolments", JoinType.LEFT);
            final Selection<Object> pc = root.join("preferredCourse", JoinType.LEFT).alias("pc");
            criteria.orderBy(builder.asc(root.get("studentNumber")));
            criteria.multiselect(pc, st);
            return criteria;
        }
    };
    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, criteriaExecutor, checker, false, scope);
}
Also used : CriteriaBuilder(jakarta.persistence.criteria.CriteriaBuilder) BasicTypeImpl(org.hibernate.type.internal.BasicTypeImpl) ServiceRegistry(org.hibernate.testing.orm.junit.ServiceRegistry) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) JoinType(jakarta.persistence.criteria.JoinType) JpaSelection(org.hibernate.query.criteria.JpaSelection) AvailableSettings(org.hibernate.cfg.AvailableSettings) Assertions.assertNotEquals(org.junit.jupiter.api.Assertions.assertNotEquals) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) Session(org.hibernate.Session) Constructor(java.lang.reflect.Constructor) ArrayList(java.util.ArrayList) HibernateProxy(org.hibernate.proxy.HibernateProxy) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) Map(java.util.Map) Query(org.hibernate.query.Query) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) Order(jakarta.persistence.criteria.Order) BigIntJdbcType(org.hibernate.type.descriptor.jdbc.BigIntJdbcType) Transformers(org.hibernate.transform.Transformers) Iterator(java.util.Iterator) ListJoin(jakarta.persistence.criteria.ListJoin) ReflectHelper(org.hibernate.internal.util.ReflectHelper) DomainModel(org.hibernate.testing.orm.junit.DomainModel) AliasToBeanConstructorResultTransformer(org.hibernate.transform.AliasToBeanConstructorResultTransformer) Selection(jakarta.persistence.criteria.Selection) CacheMode(org.hibernate.CacheMode) Assertions.assertSame(org.junit.jupiter.api.Assertions.assertSame) JpaCriteriaQuery(org.hibernate.query.criteria.JpaCriteriaQuery) Test(org.junit.jupiter.api.Test) MapJoin(jakarta.persistence.criteria.MapJoin) List(java.util.List) Root(jakarta.persistence.criteria.Root) SessionFactoryScope(org.hibernate.testing.orm.junit.SessionFactoryScope) CriteriaBuilder(jakarta.persistence.criteria.CriteriaBuilder) JpaRoot(org.hibernate.query.criteria.JpaRoot) LongJavaType(org.hibernate.type.descriptor.java.LongJavaType) Setting(org.hibernate.testing.orm.junit.Setting) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) AliasToEntityMapResultTransformer(org.hibernate.transform.AliasToEntityMapResultTransformer) SessionFactory(org.hibernate.testing.orm.junit.SessionFactory) Path(jakarta.persistence.criteria.Path) Hibernate(org.hibernate.Hibernate) ResultTransformer(org.hibernate.transform.ResultTransformer) Type(org.hibernate.type.Type) Join(jakarta.persistence.criteria.Join) ArrayList(java.util.ArrayList) List(java.util.List) JpaCriteriaQuery(org.hibernate.query.criteria.JpaCriteriaQuery) Session(org.hibernate.Session) Test(org.junit.jupiter.api.Test)

Example 3 with Selection

use of jakarta.persistence.criteria.Selection in project hibernate-orm by hibernate.

the class AbstractQueryCacheResultTransformerTest method testMultiSelectNewMapUsingAliasesWithFetchJoinList.

@Test
public void testMultiSelectNewMapUsingAliasesWithFetchJoinList(SessionFactoryScope scope) 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(Map.class);
            Root<Student> root = criteria.from(Student.class);
            final Selection<Student> studentAlias = root.alias("s");
            final Selection<Object> 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  )
        // .setFetchMode( "enrolments", FetchMode.JOIN )
        // .addOrder( Order.asc( "s.studentNumber" ))
        // .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP );
        }
    };
    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, criteriaExecutor, checker, false, scope);
}
Also used : CriteriaBuilder(jakarta.persistence.criteria.CriteriaBuilder) BasicTypeImpl(org.hibernate.type.internal.BasicTypeImpl) ServiceRegistry(org.hibernate.testing.orm.junit.ServiceRegistry) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) JoinType(jakarta.persistence.criteria.JoinType) JpaSelection(org.hibernate.query.criteria.JpaSelection) AvailableSettings(org.hibernate.cfg.AvailableSettings) Assertions.assertNotEquals(org.junit.jupiter.api.Assertions.assertNotEquals) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) Session(org.hibernate.Session) Constructor(java.lang.reflect.Constructor) ArrayList(java.util.ArrayList) HibernateProxy(org.hibernate.proxy.HibernateProxy) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) Map(java.util.Map) Query(org.hibernate.query.Query) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) Order(jakarta.persistence.criteria.Order) BigIntJdbcType(org.hibernate.type.descriptor.jdbc.BigIntJdbcType) Transformers(org.hibernate.transform.Transformers) Iterator(java.util.Iterator) ListJoin(jakarta.persistence.criteria.ListJoin) ReflectHelper(org.hibernate.internal.util.ReflectHelper) DomainModel(org.hibernate.testing.orm.junit.DomainModel) AliasToBeanConstructorResultTransformer(org.hibernate.transform.AliasToBeanConstructorResultTransformer) Selection(jakarta.persistence.criteria.Selection) CacheMode(org.hibernate.CacheMode) Assertions.assertSame(org.junit.jupiter.api.Assertions.assertSame) JpaCriteriaQuery(org.hibernate.query.criteria.JpaCriteriaQuery) Test(org.junit.jupiter.api.Test) MapJoin(jakarta.persistence.criteria.MapJoin) List(java.util.List) Root(jakarta.persistence.criteria.Root) SessionFactoryScope(org.hibernate.testing.orm.junit.SessionFactoryScope) CriteriaBuilder(jakarta.persistence.criteria.CriteriaBuilder) JpaRoot(org.hibernate.query.criteria.JpaRoot) LongJavaType(org.hibernate.type.descriptor.java.LongJavaType) Setting(org.hibernate.testing.orm.junit.Setting) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) AliasToEntityMapResultTransformer(org.hibernate.transform.AliasToEntityMapResultTransformer) SessionFactory(org.hibernate.testing.orm.junit.SessionFactory) Path(jakarta.persistence.criteria.Path) Hibernate(org.hibernate.Hibernate) ResultTransformer(org.hibernate.transform.ResultTransformer) Type(org.hibernate.type.Type) Join(jakarta.persistence.criteria.Join) ArrayList(java.util.ArrayList) List(java.util.List) JpaCriteriaQuery(org.hibernate.query.criteria.JpaCriteriaQuery) Map(java.util.Map) Session(org.hibernate.Session) Test(org.junit.jupiter.api.Test)

Example 4 with Selection

use of jakarta.persistence.criteria.Selection in project hibernate-orm by hibernate.

the class AbstractQueryCacheResultTransformerTest method testMultiSelectAliasToEntityMapUsingAliasesWithFetchJoinList.

@Test
public void testMultiSelectAliasToEntityMapUsingAliasesWithFetchJoinList(SessionFactoryScope scope) throws Exception {
    CriteriaExecutor criteriaExecutor = new CriteriaExecutor() {

        @Override
        protected JpaCriteriaQuery getCriteria(Session s) {
            CriteriaBuilder builder = s.getCriteriaBuilder();
            JpaCriteriaQuery criteria = (JpaCriteriaQuery) builder.createQuery();
            Root<Student> root = criteria.from(Student.class);
            final Selection<Student> studentAlias = root.alias("s");
            final Selection<Object> 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  )
        // .setFetchMode( "enrolments", FetchMode.JOIN )
        // .addOrder( Order.asc( "s.studentNumber" ))
        // .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP );
        }
    };
    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, criteriaExecutor, checker, false, scope);
}
Also used : CriteriaBuilder(jakarta.persistence.criteria.CriteriaBuilder) BasicTypeImpl(org.hibernate.type.internal.BasicTypeImpl) ServiceRegistry(org.hibernate.testing.orm.junit.ServiceRegistry) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) JoinType(jakarta.persistence.criteria.JoinType) JpaSelection(org.hibernate.query.criteria.JpaSelection) AvailableSettings(org.hibernate.cfg.AvailableSettings) Assertions.assertNotEquals(org.junit.jupiter.api.Assertions.assertNotEquals) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) Session(org.hibernate.Session) Constructor(java.lang.reflect.Constructor) ArrayList(java.util.ArrayList) HibernateProxy(org.hibernate.proxy.HibernateProxy) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) Map(java.util.Map) Query(org.hibernate.query.Query) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) Order(jakarta.persistence.criteria.Order) BigIntJdbcType(org.hibernate.type.descriptor.jdbc.BigIntJdbcType) Transformers(org.hibernate.transform.Transformers) Iterator(java.util.Iterator) ListJoin(jakarta.persistence.criteria.ListJoin) ReflectHelper(org.hibernate.internal.util.ReflectHelper) DomainModel(org.hibernate.testing.orm.junit.DomainModel) AliasToBeanConstructorResultTransformer(org.hibernate.transform.AliasToBeanConstructorResultTransformer) Selection(jakarta.persistence.criteria.Selection) CacheMode(org.hibernate.CacheMode) Assertions.assertSame(org.junit.jupiter.api.Assertions.assertSame) JpaCriteriaQuery(org.hibernate.query.criteria.JpaCriteriaQuery) Test(org.junit.jupiter.api.Test) MapJoin(jakarta.persistence.criteria.MapJoin) List(java.util.List) Root(jakarta.persistence.criteria.Root) SessionFactoryScope(org.hibernate.testing.orm.junit.SessionFactoryScope) CriteriaBuilder(jakarta.persistence.criteria.CriteriaBuilder) JpaRoot(org.hibernate.query.criteria.JpaRoot) LongJavaType(org.hibernate.type.descriptor.java.LongJavaType) Setting(org.hibernate.testing.orm.junit.Setting) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) AliasToEntityMapResultTransformer(org.hibernate.transform.AliasToEntityMapResultTransformer) SessionFactory(org.hibernate.testing.orm.junit.SessionFactory) Path(jakarta.persistence.criteria.Path) Hibernate(org.hibernate.Hibernate) ResultTransformer(org.hibernate.transform.ResultTransformer) Type(org.hibernate.type.Type) Join(jakarta.persistence.criteria.Join) ArrayList(java.util.ArrayList) List(java.util.List) JpaCriteriaQuery(org.hibernate.query.criteria.JpaCriteriaQuery) Map(java.util.Map) Session(org.hibernate.Session) Test(org.junit.jupiter.api.Test)

Example 5 with Selection

use of jakarta.persistence.criteria.Selection in project eclipselink by eclipse-ee4j.

the class JUnitCriteriaSimpleTestSuiteBase method testCriteriaBuilderArrayValidation.

// 366206 - CriteriaBuilder.array(Selection)
public void testCriteriaBuilderArrayValidation() {
    EntityManager em = createEntityManager();
    CriteriaBuilder qb = em.getCriteriaBuilder();
    CriteriaQuery<Object[]> cquery = qb.createQuery(Object[].class);
    Root<Employee> emp = wrapper.from(cquery, Employee.class);
    Selection[] s = { wrapper.get(emp, Employee_id), wrapper.get(emp, Employee_lastName), wrapper.get(emp, Employee_firstName) };
    Selection<Object[]> item = qb.array(s);
    cquery.select(item);
    TypedQuery<Object[]> query = em.createQuery(cquery);
    // verify they work and can be used:
    List<Object[]> list = query.getResultList();
    list.get(0);
    try {
        // verify tuple throws an exception when passed an array
        Object unexpectedResult = qb.tuple(item);
        fail("IllegalArgumentException expected using an invalid value to CriteriaBuilder.tuple(). Result returned:" + unexpectedResult);
    } catch (Exception iae) {
        assertEquals(iae.getClass(), IllegalArgumentException.class);
    }
    try {
        // verify array throws an exception when passed an array
        Object unexpectedResult = qb.array(item);
        fail("IllegalArgumentException expected using an invalid value to CriteriaBuilder.array(). Result returned:" + unexpectedResult);
    } catch (Exception iae) {
        assertEquals(iae.getClass(), IllegalArgumentException.class);
    }
    closeEntityManager(em);
}
Also used : CriteriaBuilder(jakarta.persistence.criteria.CriteriaBuilder) Selection(jakarta.persistence.criteria.Selection) EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) Employee(org.eclipse.persistence.testing.models.jpa.advanced.Employee)

Aggregations

Selection (jakarta.persistence.criteria.Selection)17 CriteriaBuilder (jakarta.persistence.criteria.CriteriaBuilder)11 EntityManager (jakarta.persistence.EntityManager)6 Join (jakarta.persistence.criteria.Join)5 ListJoin (jakarta.persistence.criteria.ListJoin)5 MapJoin (jakarta.persistence.criteria.MapJoin)5 Root (jakarta.persistence.criteria.Root)5 Constructor (java.lang.reflect.Constructor)5 ArrayList (java.util.ArrayList)5 Tuple (jakarta.persistence.Tuple)4 JoinType (jakarta.persistence.criteria.JoinType)4 Order (jakarta.persistence.criteria.Order)4 Path (jakarta.persistence.criteria.Path)4 Iterator (java.util.Iterator)4 List (java.util.List)4 Map (java.util.Map)4 JpaEntityManager (org.eclipse.persistence.jpa.JpaEntityManager)4 Employee (org.eclipse.persistence.testing.models.jpa.advanced.Employee)4 CacheMode (org.hibernate.CacheMode)4 Hibernate (org.hibernate.Hibernate)4