Example usage for javax.persistence.criteria CriteriaQuery select

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

Introduction

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

Prototype

CriteriaQuery<T> select(Selection<? extends T> selection);

Source Link

Document

Specify the item that is to be returned in the query result.

Usage

From source file:com.sapito.db.dao.AbstractDao.java

/**
 * Obtiene todos los registros para una entidad dada ordenados con los
 * criterios establecidos a traves de la lista <code>ordering</code>
 * /* w  w  w.ja v  a2  s  . c om*/
 * @param ordering : ["fieldName", "ASC" | "DESC"] <br>
 *                   (if != "ASC" se utiliza "DESC" por default)
 * 
 * @return Registros recuperados ordenados mediante los criterios dados
 */
public List<T> findAll(LinkedHashMap<String, String> ordering) {
    CriteriaQuery cq = entityManager.getCriteriaBuilder().createQuery();
    Root<T> root = cq.from(entityClass);
    cq.select(root);

    if (ordering != null) {
        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        Set<String> set = ordering.keySet();
        List<Order> orders = new ArrayList<>();
        for (String orderingField : set) {
            Order order = (ordering.get(orderingField).equals("ASC")) ? cb.asc(root.get(orderingField))
                    : cb.desc(root.get(orderingField));
            orders.add(order);
        }

        cq.orderBy(orders);
    }

    return entityManager.createQuery(cq).setMaxResults(MAX_RECORDS_RETURNED).getResultList();
}

From source file:net.groupbuy.dao.impl.MessageDaoImpl.java

public Page<Message> findDraftPage(Member sender, Pageable pageable) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Message> criteriaQuery = criteriaBuilder.createQuery(Message.class);
    Root<Message> root = criteriaQuery.from(Message.class);
    criteriaQuery.select(root);
    Predicate restrictions = criteriaBuilder.conjunction();
    restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNull(root.get("forMessage")),
            criteriaBuilder.equal(root.get("isDraft"), true));
    if (sender != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("sender"), sender));
    } else {/*  ww w  .  j  a  va  2 s  .  c  o  m*/
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNull(root.get("sender")));
    }
    criteriaQuery.where(restrictions);
    return super.findPage(criteriaQuery, pageable);
}

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

public List<Article> findList(ArticleCategory articleCategory, Tag tag, Boolean isPublication, Integer count,
        List<Filter> filters, List<Order> orders) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Article> criteriaQuery = criteriaBuilder.createQuery(Article.class);
    Root<Article> root = criteriaQuery.from(Article.class);
    criteriaQuery.select(root);
    Predicate restrictions = criteriaBuilder.conjunction();
    if (articleCategory != null) {
        Subquery<ArticleCategory> subquery = criteriaQuery.subquery(ArticleCategory.class);
        Root<ArticleCategory> subqueryRoot = subquery.from(ArticleCategory.class);
        subquery.select(subqueryRoot);/*from w w  w .  j a  v a2  s.c  o m*/
        subquery.where(criteriaBuilder.or(criteriaBuilder.equal(subqueryRoot, articleCategory),
                criteriaBuilder.like(subqueryRoot.<String>get("treePath"),
                        "%" + ArticleCategory.TREE_PATH_SEPARATOR + articleCategory.getId()
                                + ArticleCategory.TREE_PATH_SEPARATOR + "%")));
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.in(root.get("articleCategory")).value(subquery));
    }
    if (tag != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.join("tags"), tag));
    }
    if (isPublication != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isPublication"), isPublication));
    }
    criteriaQuery.where(restrictions);
    if (orders == null || orders.isEmpty()) {
        criteriaQuery.orderBy(criteriaBuilder.desc(root.get("isTop")),
                criteriaBuilder.desc(root.get("createDate")));
    }
    return super.findList(criteriaQuery, null, count, filters, orders);
}

From source file:org.sloth.persistence.impl.ObservationDaoImpl.java

@Override
public Collection<Observation> getAll() {
    CriteriaQuery<Observation> cq = getEntityManager().getCriteriaBuilder().createQuery(Observation.class);
    cq.select(cq.from(Observation.class));
    Collection<Observation> list = getEntityManager().createQuery(cq).getResultList();
    logger.info("Getting all Observations; Found: {}", list.size());
    return list;//  www. ja  v  a2 s  .  c om
}

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

public Page<Article> findPage(ArticleCategory articleCategory, Tag tag, Boolean isPublication,
        Pageable pageable) {/*from w  w w  .j ava 2  s  . c om*/
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Article> criteriaQuery = criteriaBuilder.createQuery(Article.class);
    Root<Article> root = criteriaQuery.from(Article.class);
    criteriaQuery.select(root);
    Predicate restrictions = criteriaBuilder.conjunction();
    if (articleCategory != null) {
        Subquery<ArticleCategory> subquery = criteriaQuery.subquery(ArticleCategory.class);
        Root<ArticleCategory> subqueryRoot = subquery.from(ArticleCategory.class);
        subquery.select(subqueryRoot);
        subquery.where(criteriaBuilder.or(criteriaBuilder.equal(subqueryRoot, articleCategory),
                criteriaBuilder.like(subqueryRoot.<String>get("treePath"),
                        "%" + ArticleCategory.TREE_PATH_SEPARATOR + articleCategory.getId()
                                + ArticleCategory.TREE_PATH_SEPARATOR + "%")));
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.in(root.get("articleCategory")).value(subquery));
    }
    if (tag != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.join("tags"), tag));
    }
    if (isPublication != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isPublication"), isPublication));
    }
    criteriaQuery.where(restrictions);
    if (pageable == null
            || ((StringUtils.isEmpty(pageable.getOrderProperty()) || pageable.getOrderDirection() == null)
                    && CollectionUtils.isEmpty(pageable.getOrders()))) {
        criteriaQuery.orderBy(criteriaBuilder.desc(root.get("isTop")),
                criteriaBuilder.desc(root.get("createDate")));
    }
    return super.findPage(criteriaQuery, pageable);
}

From source file:com.fantasy.stataggregator.entities.dao.AbstractRepository.java

public int count() {
    javax.persistence.criteria.CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
    javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
    cq.select(em.getCriteriaBuilder().count(rt));
    javax.persistence.Query q = em.createQuery(cq);
    return ((Long) q.getSingleResult()).intValue();
}

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

public List<Article> findList(ArticleCategory articleCategory, Boolean isPublication,
        Article.GenerateMethod generateMethod, Date beginDate, Date endDate, Integer first, Integer count) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Article> criteriaQuery = criteriaBuilder.createQuery(Article.class);
    Root<Article> root = criteriaQuery.from(Article.class);
    criteriaQuery.select(root);
    Predicate restrictions = criteriaBuilder.conjunction();
    if (articleCategory != null) {
        Subquery<ArticleCategory> subquery = criteriaQuery.subquery(ArticleCategory.class);
        Root<ArticleCategory> subqueryRoot = subquery.from(ArticleCategory.class);
        subquery.select(subqueryRoot);// www.  j  a  va2  s  . c  o m
        subquery.where(criteriaBuilder.or(criteriaBuilder.equal(subqueryRoot, articleCategory),
                criteriaBuilder.like(subqueryRoot.<String>get("treePath"),
                        "%" + ArticleCategory.TREE_PATH_SEPARATOR + articleCategory.getId()
                                + ArticleCategory.TREE_PATH_SEPARATOR + "%")));
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.in(root.get("articleCategory")).value(subquery));
    }
    if (isPublication != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isPublication"), isPublication));
    }
    if (generateMethod != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("generateMethod"), generateMethod));
    }
    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.findList(criteriaQuery, first, count, null, null);
}

From source file:ispok.dao.TournamentHibernateJpaDao.java

@Override
public List<Tournament> getPage(int first, int rows, String sortBy, boolean ascending,
        Map<String, Object> filters) {

    //        Session session = getEntityManager().unwrap(Session.class);
    //        Criteria criteria = session.createCriteria(Tournament.class);
    //        CriteriaBuilder cb = entityManagerfactory.getCriteriaBuilder();
    //        CriteriaQuery<Tournament> cq = cb.createQuery(Tournament.class);
    //        Root<Tournament> tou = cq.from(Tournament.class);
    //        cb.para
    //        criteria.add(cb.equal(tou, tou))
    //        String queryString = "SELECT e FROM " + Tournament.class.getSimpleName();
    //        if (!filters.isEmpty()) {
    //            queryString += " WHERE ";
    //            for (Map.Entry<String, Object> entry : filters.entrySet()) {
    //                if ("id".equals(entry.getKey())) {
    //                    queryString += "e." + entry.getKey() + " = " + entry.getValue();
    //                } else {
    //                    queryString += "e." + entry.getKey() + " LIKE '" + entry.getValue() + "'";
    //                }
    //            }
    //        }//from  ww  w . j  a va2 s . c  o m
    //                " e WHERE e." + property + " = :value";
    //        return getEntityManager().createQuery(queryString).setParameter("value", value).getResultList();
    //        return null;
    //        Session session = getEntityManager().unwrap(Session.class);
    //        Criteria criteria = session.createCriteria(Tournament.class);
    //
    //        for (Map.Entry<String, Object> filter : filters.entrySet()) {
    //            if ("id".equals(filter.getKey())) {
    //                criteria.add(Restrictions.eq("id", Long.parseLong(filter.getValue().toString())));
    //            } else {
    //                criteria.add(Restrictions.ilike(filter.getKey(), (String) filter.getValue(), MatchMode.START));
    //            }
    //        }
    //
    //        if (ascending) {
    //            criteria.addOrder(Order.asc(sortBy));
    //        } else {
    //            criteria.addOrder(Order.desc(sortBy));
    //        }
    //
    //        criteria.setFirstResult(first);
    //        criteria.setMaxResults(rows);
    //
    //        criteria.setResultTransformer(Transformers.aliasToBean(clazz));
    //        List<ENTITY> list = criteria.list();
    //
    //        return list;
    EntityManager em = getEntityManager();

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Tournament> cq = cb.createQuery(Tournament.class);
    Root<Tournament> t = cq.from(Tournament.class);

    cq.select(t);

    TypedQuery<Tournament> tq = em.createQuery(cq);

    List<Tournament> tournaments = tq.getResultList();
    return tournaments;

}

From source file:org.oncoblocks.centromere.jpa.CentromereJpaRepository.java

/**
 * Returns a unsorted list of distinct values of the requested field.
 *
 * @param field Model field name.//from  www .jav  a  2  s. c  o m
 * @return Sorted list of distinct values of {@code field}.
 */
public Iterable<Object> distinct(String field) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<T> query = builder.createQuery(metadata.getJavaType());
    Root<T> root = query.from(metadata.getJavaType());
    query.select(root.get(field)).distinct(true);
    return (List) entityManager.createQuery(query).getResultList();
}

From source file:org.eclipse.jubula.client.core.persistence.NodePM.java

/**
 * Finds a Test Suite within the currently opened project.
 * //from  ww  w  .j a  va2s  .  c  o  m
 * @param testSuiteGuid The GUID of the Test Suite.
 * @return the Test Suite with the given GUID, or <code>null</code> if 
 *         no such Test Suite can be found.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static synchronized ITestSuitePO getTestSuite(String testSuiteGuid) {

    GeneralStorage gs = GeneralStorage.getInstance();
    IProjectPO currentProject = gs.getProject();
    if (currentProject != null) {
        EntityManager s = gs.getMasterSession();

        CriteriaBuilder builder = s.getCriteriaBuilder();
        CriteriaQuery query = builder.createQuery();
        Root from = query.from(NodeMaker.getTestSuitePOClass());
        query.select(from).where(builder.like(from.get("guid"), testSuiteGuid), //$NON-NLS-1$
                builder.equal(from.get("hbmParentProjectId"), currentProject.getId())); //$NON-NLS-1$

        try {
            Object result = s.createQuery(query).getSingleResult();
            if (result instanceof ITestSuitePO) {
                return (ITestSuitePO) result;
            }
        } catch (NoResultException nre) {
            // No result found. Fall through to return null as per javadoc.
        }
    }

    return null;
}