Example usage for javax.persistence.criteria CriteriaBuilder construct

List of usage examples for javax.persistence.criteria CriteriaBuilder construct

Introduction

In this page you can find the example usage for javax.persistence.criteria CriteriaBuilder construct.

Prototype

<Y> CompoundSelection<Y> construct(Class<Y> resultClass, Selection<?>... selections);

Source Link

Document

Create a selection item corresponding to a constructor.

Usage

From source file:bq.jpa.demo.query.criteria.service.CriteriaService.java

/**
 * use customize object in select/*from w  w w .java 2s .  c  o m*/
 */
public void doSelect3() {
    CriteriaBuilder cb = em.getCriteriaBuilder();

    // return type is a customized object
    CriteriaQuery<EmployeeBasicInfo> c = cb.createQuery(EmployeeBasicInfo.class);
    Root<Employee> e = c.from(Employee.class);

    // method 1 : must use multiple select, cannot use select method, because of strong type check
    c.multiselect(e.get("name"));
    showResult(c);

    // method 2 : use select and cb.construct
    c.select(cb.construct(EmployeeBasicInfo.class, e.get("name")));
    showResult(c);

    // method 3 : use multiple select and cb.construct
    // NOTE : UNSUPPORT!
    //      CriteriaQuery<EmployeeBasicInfo> c2 = cb.createQuery(EmployeeBasicInfo.class);
    //      Root<Employee> e2 = c2.from(Employee.class);
    //      c2.multiselect(cb.construct(EmployeeBasicInfo.class, e2.get("name")));
    //      showResult(c2);
}

From source file:com.adeptj.modules.data.jpa.core.AbstractJpaRepository.java

/**
 * {@inheritDoc}/*  w  w  w .  j a  v  a 2  s  .  com*/
 */
@Override
public <T extends BaseEntity, C> List<C> findByCriteriaAndMapConstructor(ConstructorCriteria<T, C> criteria) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<C> cq = cb.createQuery(criteria.getConstructorClass());
        Root<T> root = cq.from(criteria.getEntity());
        return em.createQuery(cq
                .select(cb.construct(criteria.getConstructorClass(),
                        criteria.getSelections().stream().map(root::get).toArray(Selection[]::new)))
                .where(Predicates.from(criteria.getCriteriaAttributes(), cb, root))).getResultList();
    } catch (Exception ex) { // NOSONAR
        throw new JpaException(ex);
    } finally {
        JpaUtil.closeEntityManager(em);
    }
}