Search in sources :

Example 11 with Selection

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

the class MultiSelectTests method tupleSelectionArrayTest.

@Test
public void tupleSelectionArrayTest(SessionFactoryScope scope) {
    scope.inTransaction((session) -> {
        final CriteriaBuilder nodeBuilder = session.getFactory().getNodeBuilder();
        final CriteriaQuery<Tuple> criteria = nodeBuilder.createTupleQuery();
        final Root<BasicEntity> root = criteria.from(BasicEntity.class);
        Selection<?>[] s = { root.get("id"), root.get("data") };
        criteria.select(nodeBuilder.tuple(s));
        final List<Tuple> results = session.createQuery(criteria).list();
        assertThat(results).hasSize(1);
        final Tuple firstResult = results.get(0);
        assertThat(firstResult.getElements()).hasSize(2);
        assertThat(firstResult.get(0)).isEqualTo(1);
        assertThat(firstResult.get(1)).isEqualTo("abc");
    });
}
Also used : CriteriaBuilder(jakarta.persistence.criteria.CriteriaBuilder) Selection(jakarta.persistence.criteria.Selection) Tuple(jakarta.persistence.Tuple) BasicEntity(org.hibernate.testing.orm.domain.gambit.BasicEntity) Test(org.junit.jupiter.api.Test)

Example 12 with Selection

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

the class AbstractQueryCacheResultTransformerTest method testJoinWithFetchJoinWithOwnerAndAliasedJoinedProjectedList.

@Test
public void testJoinWithFetchJoinWithOwnerAndAliasedJoinedProjectedList(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);
            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(root, pc);
            return criteria;
        }
    };
    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, 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 13 with Selection

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

the class JUnitCriteriaSimpleTestSuiteBase method testCompoundSelectionAliasValidation.

// 366386 - IllegalArgumentException for duplicated aliases
public void testCompoundSelectionAliasValidation() {
    EntityManager em = createEntityManager();
    CriteriaBuilder qb = em.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteria = qb.createTupleQuery();
    Root<Employee> emp = wrapper.from(criteria, Employee.class);
    Selection[] s = { wrapper.get(emp, Employee_lastName).alias("duplicateAlias"), wrapper.get(emp, Employee_firstName).alias("duplicateAlias") };
    try {
        criteria.multiselect(s);
        fail("IllegalArgumentException expected using multiselect on items using duplicate aliases");
    } catch (Exception iae) {
        assertEquals(iae.getClass(), IllegalArgumentException.class);
    }
    Selection<Tuple> tupleItem = qb.tuple(s);
    try {
        criteria.select(tupleItem);
        fail("IllegalArgumentException expected on select using a Tuple with items using duplicate aliases");
    } catch (Exception iae) {
        assertEquals(iae.getClass(), IllegalArgumentException.class);
    }
    closeEntityManager(em);
}
Also used : CriteriaBuilder(jakarta.persistence.criteria.CriteriaBuilder) EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) Employee(org.eclipse.persistence.testing.models.jpa.advanced.Employee) Selection(jakarta.persistence.criteria.Selection) Tuple(jakarta.persistence.Tuple)

Example 14 with Selection

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

the class CriteriaQueryImpl method select.

/**
 * Specify the item that is to be returned in the query result. Replaces the
 * previously specified selection, if any.
 *
 * @param selection
 *            selection specifying the item that is to be returned in the
 *            query result
 * @return the modified query
 */
@Override
public CriteriaQuery<T> select(Selection<? extends T> selection) {
    this.selection = (SelectionImpl<? extends T>) selection;
    this.selection.findRootAndParameters(this);
    if (selection.isCompoundSelection()) {
        // bug 366386: validate that aliases are not reused
        if (this.selection.isCompoundSelection() && ((CompoundSelectionImpl) this.selection).getDuplicateAliasNames() != null) {
            throw new IllegalArgumentException(ExceptionLocalization.buildMessage("jpa_criteriaapi_alias_reused", new Object[] { ((CompoundSelectionImpl) this.selection).getDuplicateAliasNames() }));
        }
        if (selection.getJavaType().equals(Tuple.class)) {
            this.queryResult = ResultType.TUPLE;
            this.queryType = (Class<T>) Tuple.class;
        } else if (((InternalSelection) selection).isConstructor()) {
            Selection[] selectArray = selection.getCompoundSelectionItems().toArray(new Selection[selection.getCompoundSelectionItems().size()]);
            populateAndSetConstructorSelection((ConstructorSelectionImpl) selection, this.selection.getJavaType(), selectArray);
            this.queryType = (Class<T>) selection.getJavaType();
        } else {
            this.queryResult = ResultType.OBJECT_ARRAY;
            this.queryType = (Class<T>) ClassConstants.AOBJECT;
        }
    } else {
        // Update query type only when it's not null in selection argument.
        Class<?> queryType = selection.getJavaType();
        if (queryType != null) {
            this.queryType = (Class<T>) queryType;
        }
        TypeImpl type = ((MetamodelImpl) this.metamodel).getType(this.queryType);
        if (type != null && type.getPersistenceType().equals(PersistenceType.ENTITY)) {
            // this will be a selection item in a report query
            this.queryResult = ResultType.ENTITY;
        } else {
            this.queryResult = ResultType.OTHER;
        }
    }
    return this;
}
Also used : MetamodelImpl(org.eclipse.persistence.internal.jpa.metamodel.MetamodelImpl) Selection(jakarta.persistence.criteria.Selection) Tuple(jakarta.persistence.Tuple) TypeImpl(org.eclipse.persistence.internal.jpa.metamodel.TypeImpl)

Example 15 with Selection

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

the class CriteriaQueryImpl method populateAndSetConstructorSelection.

/**
 * This method will set this queryImpl's selection to a ConstructorSelectionImpl, creating a new
 * instance or populating the one passed in as necessary.
 * Throws IllegalArgumentException if a constructor taking arguments represented
 * by the selections array doesn't exist for the given class.
 *
 * Also sets the query result to ResultType.CONSTRUCTOR
 */
public void populateAndSetConstructorSelection(ConstructorSelectionImpl constructorSelection, Class<?> class1, Selection<?>... selections) throws IllegalArgumentException {
    Class<?>[] constructorArgs = new Class<?>[selections.length];
    int count = 0;
    for (Selection select : selections) {
        if (select instanceof ConstructorSelectionImpl) {
            ConstructorSelectionImpl constructorSelect = (ConstructorSelectionImpl) select;
            Selection[] selectArray = constructorSelect.getCompoundSelectionItems().toArray(new Selection[constructorSelect.getCompoundSelectionItems().size()]);
            populateAndSetConstructorSelection(constructorSelect, constructorSelect.getJavaType(), selectArray);
        }
        constructorArgs[count++] = select.getJavaType();
    }
    Constructor constructor = null;
    try {
        if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
            constructor = AccessController.doPrivileged(new PrivilegedGetConstructorFor<>(class1, constructorArgs, false));
        } else {
            constructor = PrivilegedAccessHelper.getConstructorFor(class1, constructorArgs, false);
        }
        if (constructorSelection == null) {
            constructorSelection = new ConstructorSelectionImpl(class1, selections);
        }
        this.queryResult = ResultType.CONSTRUCTOR;
        constructorSelection.setConstructor(constructor);
        constructorSelection.setConstructorArgTypes(constructorArgs);
        this.selection = constructorSelection;
    } catch (Exception e) {
        // PrivilegedActionException and NoSuchMethodException are possible
        Object[] params = new Object[1];
        params[0] = this.queryType;
        throw new IllegalArgumentException(ExceptionLocalization.buildMessage("criteria_no_constructor_found", params), e);
    }
}
Also used : Selection(jakarta.persistence.criteria.Selection) Constructor(java.lang.reflect.Constructor) PrivilegedGetConstructorFor(org.eclipse.persistence.internal.security.PrivilegedGetConstructorFor)

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