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:org.broadleafcommerce.cms.file.dao.StaticAssetDaoImpl.java

@Override
public StaticAsset readStaticAssetById(Long id) {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<StaticAsset> criteria = builder.createQuery(StaticAsset.class);
    Root<StaticAssetImpl> handler = criteria.from(StaticAssetImpl.class);
    criteria.select(handler);
    List<Predicate> restrictions = new ArrayList<Predicate>();
    restrictions.add(builder.equal(handler.get("id"), id));

    if (queryExtensionManager != null) {
        queryExtensionManager.getProxy().setup(StaticAssetImpl.class, null);
        queryExtensionManager.getProxy().refineRetrieve(StaticAssetImpl.class, null, builder, criteria, handler,
                restrictions);//from   w  w w  .  ja  v a2  s . c  o m
    }
    criteria.where(restrictions.toArray(new Predicate[restrictions.size()]));

    TypedQuery<StaticAsset> query = em.createQuery(criteria);
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    List<StaticAsset> response = query.getResultList();
    if (response.size() > 0) {
        return response.get(0);
    }
    return null;
}

From source file:com.aimdek.ccm.dao.impl.StatementRepositoryImpl.java

/**
 * {@inheritDoc}/*from   w w w. j ava2  s.  c o m*/
 */
public List<Statement> getStatements(int start, int limit, String sortField, String sortOrder,
        Map<String, Object> filters, long userId) {

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Statement> query = builder.createQuery(Statement.class);
    Root<Statement> root = query.from(Statement.class);
    query.select(root);
    addSorting(sortField, sortOrder, query, builder, root);
    addFilterCriteria(userId, filters, builder, root, query);
    return entityManager.createQuery(query).setFirstResult(start).setMaxResults(limit).getResultList();
}

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

public Long count(Member member, Boolean read) {
    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"), false));
    if (member != null) {
        if (read != null) {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.or(//from  w w w  .  j  av  a 2  s . c o  m
                            criteriaBuilder.and(criteriaBuilder.equal(root.get("sender"), member),
                                    criteriaBuilder.equal(root.get("senderDelete"), false),
                                    criteriaBuilder.equal(root.get("senderRead"), read)),
                            criteriaBuilder.and(criteriaBuilder.equal(root.get("receiver"), member),
                                    criteriaBuilder.equal(root.get("receiverDelete"), false),
                                    criteriaBuilder.equal(root.get("receiverRead"), read))));
        } else {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.or(
                            criteriaBuilder.and(criteriaBuilder.equal(root.get("sender"), member),
                                    criteriaBuilder.equal(root.get("senderDelete"), false)),
                            criteriaBuilder.and(criteriaBuilder.equal(root.get("receiver"), member),
                                    criteriaBuilder.equal(root.get("receiverDelete"), false))));
        }
    } else {
        if (read != null) {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.or(
                            criteriaBuilder.and(criteriaBuilder.isNull(root.get("sender")),
                                    criteriaBuilder.equal(root.get("senderDelete"), false),
                                    criteriaBuilder.equal(root.get("senderRead"), read)),
                            criteriaBuilder.and(criteriaBuilder.isNull(root.get("receiver")),
                                    criteriaBuilder.equal(root.get("receiverDelete"), false),
                                    criteriaBuilder.equal(root.get("receiverRead"), read))));
        } else {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.or(
                            criteriaBuilder.and(criteriaBuilder.isNull(root.get("sender")),
                                    criteriaBuilder.equal(root.get("senderDelete"), false)),
                            criteriaBuilder.and(criteriaBuilder.isNull(root.get("receiver")),
                                    criteriaBuilder.equal(root.get("receiverDelete"), false))));
        }
    }
    criteriaQuery.where(restrictions);
    return super.count(criteriaQuery, null);
}

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

@Override
public Collection<Observation> getByUser(User u) throws NullPointerException, IllegalArgumentException {
    if (u == null) {
        throw new NullPointerException();
    }/* www  .j  av a2s . com*/
    if (u.isNew()) {
        throw new EntityNotKnownException();
    }
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<Observation> cq = cb.createQuery(Observation.class);
    Root<Observation> o = cq.from(Observation.class);
    cq.select(o).where(cb.equal(o.get(Observation_.user), u));
    Collection<Observation> result = getEntityManager().createQuery(cq).getResultList();
    logger.info("{} Observations by User {}.", result.size(), u);
    return result;
}

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

@Override
public Collection<Observation> getByCategorie(Categorie c)
        throws NullPointerException, IllegalArgumentException {
    if (c == null) {
        throw new NullPointerException();
    }/*from  w  ww  .  j av a2s. c o  m*/
    if (c.isNew()) {
        throw new IllegalArgumentException();
    }
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<Observation> cq = cb.createQuery(Observation.class);
    Root<Observation> o = cq.from(Observation.class);
    cq.select(o).where(cb.equal(o.get(Observation_.categorie), c));
    Collection<Observation> result = getEntityManager().createQuery(cq).getResultList();
    logger.info("{} Observations in Categorie {}.", result.size(), c);
    return result;
}

From source file:com.saake.invoicer.sessionbean.PurchaseOrderFacade.java

@Override
public List<PurchaseOrder> findAll() {

    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    javax.persistence.criteria.CriteriaQuery cq = cb.createQuery();

    Root<PurchaseOrder> root = cq.from(PurchaseOrder.class);
    cq.select(root);

    ParameterExpression<String> status = cb.parameter(String.class);

    //        cq.where(cb.notEqual(invRoot.get("status"), status));
    cq.where(cb.notEqual(root.get("deleted"), 'Y'));
    cq.orderBy(cb.desc(root.get("purchaseOrderId")));
    Query query = getEntityManager().createQuery(cq);
    //        query.setParameter(status, PaymentStatusEnum.DELETE.getValue());

    List<PurchaseOrder> list = query.getResultList();

    for (PurchaseOrder wo : list) {
        List<PurchaseOrderItems> tempDel = new ArrayList<>();
        for (PurchaseOrderItems wot : wo.getPurchaseOrderItems()) {
            if (wot.isDeleted()) {
                tempDel.add(wot);//from  w w w.j a v  a 2s  . c o m
            }
        }
        wo.getPurchaseOrderItems().removeAll(tempDel);
    }
    return list;
}

From source file:com.aimdek.ccm.dao.impl.StatementRepositoryImpl.java

/**
 * {@inheritDoc}//w  w  w. j a v  a2 s .  com
 */
public Statement findLastStatement() {

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Statement> query = builder.createQuery(Statement.class);
    Root<Statement> root = query.from(Statement.class);
    query.select(root);
    query.orderBy(builder.desc(root.get(FIELD_CONSTANT_STATEMENT_DATE)));
    try {
        return entityManager.createQuery(query).setMaxResults(1).getSingleResult();
    } catch (NoResultException e) {
        LOGGER.error("Error while retrieving last statement", e);
    }
    return null;
}

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

@Override
public List<Observation> getNewestObservations(int count) {
    if (count <= 0) {
        return new LinkedList<Observation>();
    }/*from   w  w w  . j  a  v a2  s.  co  m*/
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<Observation> cq = cb.createQuery(Observation.class);
    Root<Observation> o = cq.from(Observation.class);
    cq.select(o).orderBy(cb.desc(o.get(Observation_.creationDate)));
    List<Observation> result = getEntityManager().createQuery(cq).setMaxResults(count).getResultList();

    if (result.size() < count) {
        logger.info("Only {} Observations in the database", result.size());
    } else {
        logger.info("Found the {} last Observations", result.size());
    }
    return result;

}

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

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

From source file:ru.portal.services.TableServiceImpl.java

@Override
public Page<HashMap<String, String>> findAll(String tableOrViewName, Pageable pageable) {

    List<HashMap<String, String>> result = new ArrayList<>();

    EntityType<?> type = null;//w w w . j a  va 2s .c o  m
    Set<EntityType<?>> set = em.getEntityManagerFactory().getMetamodel().getEntities();
    for (EntityType<?> entityType : set) {
        if (entityType.getBindableJavaType().getAnnotation(PortalTable.class) != null) {
            if (entityType.getBindableJavaType().getName().equals(tableOrViewName)) {
                type = entityType;
                break;
            }
        }
    }

    Long totalRows = 0L;

    if (type != null) {
        Class<?> bindableJavaType = type.getBindableJavaType();

        //count
        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
        CriteriaQuery<Long> countQuery = criteriaBuilder.createQuery(Long.class);
        countQuery.select(criteriaBuilder.count(countQuery.from(bindableJavaType)));
        totalRows = em.createQuery(countQuery).getSingleResult();

        //select
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<?> cq = cb.createQuery(bindableJavaType);
        Root<?> root = cq.from(bindableJavaType);
        //          cq.select(root);
        if (pageable == null) {
            pageable = new PageRequest(0, 50);
        }

        TypedQuery<?> query = em.createQuery(cq);

        query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
        query.setMaxResults(pageable.getPageSize());
        List<?> all = query.getResultList();

        List<String> columns = getTableOrViewMetaData(tableOrViewName);

        for (Object object : all) {

            HashMap<String, String> res = new HashMap<>(columns.size());
            Class<? extends Object> clazz = object.getClass();
            for (String fieldName : columns) {
                try {
                    Field field = clazz.getDeclaredField(fieldName);
                    field.setAccessible(true);
                    Object fieldValue = field.get(object);
                    res.put(fieldName, fieldValue.toString());
                    //TODO cast data integer long etc
                } catch (NoSuchFieldException | SecurityException | IllegalArgumentException
                        | IllegalAccessException ex) {
                    Logger.getLogger(TableServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            result.add(res);
        }
    }

    PageImpl<HashMap<String, String>> list = new PageImpl<>(result, pageable, totalRows);
    return list;
}