Example usage for javax.persistence.criteria CriteriaQuery from

List of usage examples for javax.persistence.criteria CriteriaQuery from

Introduction

In this page you can find the example usage for javax.persistence.criteria CriteriaQuery from.

Prototype

<X> Root<X> from(Class<X> entityClass);

Source Link

Document

Create and add a query root corresponding to the given entity, forming a cartesian product with any existing roots.

Usage

From source file:net.awired.generic.jpa.dao.impl.GenericDaoImpl.java

@Override
public List<ENTITY> find(Collection<KEY> ids) {
    if (log.isDebugEnabled()) {
        log.debug("Finding by ids " + entityClass + "#" + ids);
    }/* w  ww.j av  a  2s . com*/
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<ENTITY> criteriaQuery = cb.createQuery(entityClass);
    Root<ENTITY> from = criteriaQuery.from(entityClass);
    criteriaQuery.where(from.in(ids));
    TypedQuery<ENTITY> query = entityManager.createQuery(criteriaQuery);
    return findList(query);
}

From source file:org.jasig.portlet.blackboardvcportlet.dao.impl.ConferenceUserDaoImpl.java

@Override
public void afterPropertiesSet() throws Exception {
    this.emailParameter = this.createParameterExpression(String.class, "email");

    this.getUsersByPrimaryEmailQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<ConferenceUserImpl>>() {
                @Override//  w ww.  ja  v a 2 s .c  o  m
                public CriteriaQuery<ConferenceUserImpl> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<ConferenceUserImpl> criteriaQuery = cb
                            .createQuery(ConferenceUserImpl.class);
                    final Root<ConferenceUserImpl> definitionRoot = criteriaQuery
                            .from(ConferenceUserImpl.class);
                    criteriaQuery.select(definitionRoot);
                    criteriaQuery
                            .where(cb.equal(definitionRoot.get(ConferenceUserImpl_.email), emailParameter));

                    return criteriaQuery;
                }
            });

    this.getUsersByAnyEmailQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<ConferenceUserImpl>>() {
                @Override
                public CriteriaQuery<ConferenceUserImpl> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<ConferenceUserImpl> criteriaQuery = cb
                            .createQuery(ConferenceUserImpl.class);
                    final Root<ConferenceUserImpl> definitionRoot = criteriaQuery
                            .from(ConferenceUserImpl.class);
                    criteriaQuery.select(definitionRoot);
                    criteriaQuery.where(
                            cb.or(cb.equal(definitionRoot.get(ConferenceUserImpl_.email), emailParameter),
                                    cb.isMember(emailParameter,
                                            definitionRoot.get(ConferenceUserImpl_.additionalEmails))));

                    return criteriaQuery;
                }
            });
}

From source file:eu.uqasar.service.AbstractService.java

/**
 *
 * @return//from   w  w  w.  jav a2 s.  c o m
 */
public long countAll() {
    logger.infof("counting all %ss ...", readableClassName);
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Long> criteria = cb.createQuery(Long.class);
    Root<T> root = criteria.from(clazz);
    criteria.select(cb.countDistinct(root));
    return em.createQuery(criteria).getSingleResult();
}

From source file:org.openregistry.core.repository.jpa.JpaPersonRepository.java

@Override
public List<Person> findByUnknownIdentifier(final String identifierValue) throws RepositoryAccessException {
    final CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder();

    final CriteriaQuery<JpaPersonImpl> c = criteriaBuilder.createQuery(JpaPersonImpl.class);
    final Root<JpaPersonImpl> person = c.from(JpaPersonImpl.class);
    final Join<JpaPersonImpl, JpaIdentifierImpl> identifier = person.join(JpaPersonImpl_.identifiers);

    c.select(person).distinct(true)// w w  w .j av  a  2s  .c om
            .where(criteriaBuilder.like(identifier.get(JpaIdentifierImpl_.value), identifierValue + "%"));

    final List<JpaPersonImpl> persons = this.entityManager.createQuery(c).getResultList();

    return new ArrayList<Person>(persons);
}

From source file:it.attocchi.jpa2.JPAEntityFilter.java

public CriteriaQuery<T> getCriteria(Class<T> clazz, EntityManagerFactory emf) throws Exception {

    // CriteriaBuilder
    CriteriaBuilder criteriaBuilder = emf.getCriteriaBuilder();

    CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(clazz);
    Root<T> root = criteriaQuery.from(clazz);

    criteriaQuery.select(root);//from w w  w .jav a2  s.  com

    // criteria.where( builder.equal( personRoot.get( Utente_.eyeColor ),
    // "brown" ) );

    List<Predicate> predicateList = new ArrayList<Predicate>();

    // buildWhere(emf, predicateList, criteriaQuery, criteriaBuilder, root);
    //
    // Predicate[] predicates = new Predicate[predicateList.size()];
    // predicateList.toArray(predicates);

    Predicate[] predicates = getWherePredicates(emf, predicateList, criteriaQuery, criteriaBuilder, root);
    Predicate wherePredicate = criteriaBuilder.and(predicates);
    criteriaQuery.where(wherePredicate);

    // buildSort(criteriaQuery, criteriaBuilder, root);
    List<Order> orders = new ArrayList<Order>();
    buildSort(orders, criteriaQuery, criteriaBuilder, root);
    if (ListUtils.isNotEmpty(orders))
        criteriaQuery.orderBy(orders);

    return criteriaQuery;
}

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

/**
 * use customize object in select/*ww  w .  j  a va  2 s .  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:net.awired.generic.jpa.dao.impl.GenericDaoImpl.java

/**
 * @param length//from  w  w w.j  av  a  2s. c  o  m
 *            maxResult
 * @param start
 *            pagination starting point
 * @param search
 *            search string like ' name: toto , dupont' to search for %toto% on name + %dupont% in all properties
 * @param searchProperties
 *            properties to search or all if null
 * @param orders
 *            sorted result by properties
 * @return
 */
public List<ENTITY> findFiltered(Integer length, Integer start, String search, List<String> searchProperties,
        List<Order> orders) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<ENTITY> query = builder.createQuery(entityClass);
    Root<ENTITY> root = query.from(entityClass);

    if (!Strings.isNullOrEmpty(search)) {
        Predicate[] buildFilterPredicates = BuildFilterPredicates(root, search, searchProperties);
        if (buildFilterPredicates.length > 0) {
            query.where(builder.or(buildFilterPredicates));
        }
    }

    if (orders != null) {
        query.orderBy(OrderToOrder.toJpa(builder, root, orders));
    }

    TypedQuery<ENTITY> q = entityManager.createQuery(query);
    if (start != null) {
        q.setFirstResult(start);
    }
    if (length != null) {
        q.setMaxResults(length);
    }
    return findList(q);
}

From source file:com.qpark.eip.core.spring.statistics.dao.StatisticsLoggingDao.java

/**
 * Get all {@link SystemUserLogType}s of the day of the application.
 *
 * @param date/*  ww w .j  a v  a  2s .  c o  m*/
 *            the date the calls are recorded.
 * @return the list of {@link SystemUserLogType}s.
 */
@Transactional(value = EipPersistenceConfig.TRANSACTION_MANAGER_NAME, propagation = Propagation.REQUIRED)
public List<SystemUserLogType> getSystemUserLogType(final Date date) {
    final CriteriaBuilder cb = this.em.getCriteriaBuilder();
    Date d = date;
    if (d == null) {
        d = new Date();
    }
    final CriteriaQuery<SystemUserLogType> q = cb.createQuery(SystemUserLogType.class);
    final Root<SystemUserLogType> c = q.from(SystemUserLogType.class);
    q.where(cb.equal(c.<String>get(SystemUserLogType_.context), this.contextNameProvider.getContextName()),
            cb.between(c.<Date>get(SystemUserLogType_.logDateItem), getDayStart(d), getDayEnd(d)));

    final TypedQuery<SystemUserLogType> typedQuery = this.em.createQuery(q);
    return typedQuery.getResultList();
}

From source file:com.creditcloud.common.entities.dao.AbstractReadDAO.java

/**
 * count entity by ParamInfo//  w  ww .j  a v a2 s  .  c  o  m
 *
 * @param paramInfo
 * @return
 */
public int count(ParamInfo paramInfo) {
    EntityManager em = getEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery(entityClass);
    Root<T> userRoot = cq.from(entityClass);
    cq.select(cb.count(userRoot));

    //build query for paramInfo
    if (paramInfo != null) {
        Set<Predicate> andCriteria = new HashSet();
        Set<Predicate> orCriteria = new HashSet();

        for (ParamItem item : paramInfo.getParamItems()) {
            Predicate predicate;
            if (item.getValue() instanceof String) {
                //fuzy search for string
                String regExp = "%" + item.getValue() + "%";
                predicate = cb.like((Expression) (userRoot.get(item.getFieldName())), regExp);
            } else {
                predicate = cb.equal((userRoot.get(item.getFieldName())), item.getValue());
            }

            switch (item.getOperator()) {
            case AND:
                andCriteria.add(predicate);
                break;
            case OR:
                orCriteria.add(predicate);
                break;
            }
        }
        if (orCriteria.size() > 0) {
            Predicate or = cb.or(orCriteria.toArray(new Predicate[orCriteria.size()]));
            andCriteria.add(or);
        }
        if (andCriteria.size() > 0) {
            Predicate and = cb.and(andCriteria.toArray(new Predicate[andCriteria.size()]));
            cq.where(and);
        }
    }

    TypedQuery<Long> query = em.createQuery(cq);
    Long result = query.getSingleResult();
    return result == null ? 0 : result.intValue();
}

From source file:net.shopxx.dao.impl.OrderDaoImpl.java

public Long createOrderCount(Date beginDate, Date endDate) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Order> criteriaQuery = criteriaBuilder.createQuery(Order.class);
    Root<Order> root = criteriaQuery.from(Order.class);
    criteriaQuery.select(root);/*from   ww w  .j  av a2  s .  c  om*/
    Predicate restrictions = criteriaBuilder.conjunction();
    if (beginDate != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.greaterThanOrEqualTo(root.<Date>get("createDate"), beginDate));
    }
    if (endDate != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.lessThanOrEqualTo(root.<Date>get("createDate"), endDate));
    }
    criteriaQuery.where(restrictions);
    return super.count(criteriaQuery, null);
}