Example usage for javax.persistence.criteria CriteriaBuilder createQuery

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

Introduction

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

Prototype

<T> CriteriaQuery<T> createQuery(Class<T> resultClass);

Source Link

Document

Create a CriteriaQuery object with the specified result type.

Usage

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   ww  w . j a v a  2s.  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:org.sloth.persistence.impl.ObservationDaoImpl.java

@Override
public Collection<Observation> getByKeyWord(String key) throws NullPointerException {
    if (key == null) {
        throw new NullPointerException();
    }//from   ww  w  .j  a v a  2s  .  c o m
    key = "%" + key.trim().replace('*', '%').toUpperCase() + "%";
    CriteriaBuilder b = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<Observation> q = b.createQuery(Observation.class);
    Root<Observation> o = q.from(Observation.class);
    Join<Observation, Categorie> j = o.join(Observation_.categorie);
    Collection<Observation> result = getEntityManager().createQuery(q.select(o).distinct(true)
            .where(b.or(b.like(b.upper(j.get(Categorie_.title)), key),
                    b.like(b.upper(j.get(Categorie_.description)), key),
                    b.like(b.upper(o.get(Observation_.title)), key),
                    b.like(b.upper(o.get(Observation_.description)), key))))
            .getResultList();
    logger.info("Searched for {}. Got {} Results.", key, result.size());
    return result;
}

From source file:org.osiam.resource_server.storage.dao.ResourceDao.java

/**
 * Retrieves a single {@link ResourceEntity} by the given attribute and value.
 * /* w w  w  . ja  va  2s .c  o m*/
 * @param attribute
 *        The attribute of the resource entity to retrieve it by
 * @param value
 *        The value of the attribute to compare it to
 * @param clazz
 *        The concrete resource entity class to retrieve (may also be {@link ResourceEntity})
 * @return The matching {@link ResourceEntity}
 * @throws ResourceNotFoundException
 *         If no {@link ResourceEntity} could be found
 * @throws OsiamException
 *         If more than 1 {@link ResourceEntity} was found
 */
public <T extends ResourceEntity, V> T getByAttribute(SingularAttribute<? super T, V> attribute, V value,
        Class<T> clazz) {

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<T> cq = cb.createQuery(clazz);
    Root<T> resource = cq.from(clazz);

    cq.select(resource).where(cb.equal(resource.get(attribute), value));

    TypedQuery<T> q = em.createQuery(cq);

    try {
        return q.getSingleResult();
    } catch (NoResultException nre) {
        throw new ResourceNotFoundException(
                String.format("Resource with attribute '%s' set to '%s' not found", attribute.getName(), value),
                nre);
    } catch (NonUniqueResultException nure) {
        throw new OsiamException(String.format("Muliple resources with attribute '%s' set to '%s' found",
                attribute.getName(), value), nure);
    }
}

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

@Override
public List<Observation> getNewestObservations(int count) {
    if (count <= 0) {
        return new LinkedList<Observation>();
    }/*  w ww . j  ava  2 s  .  c o 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.orangeandbronze.jblubble.sample.PersonController.java

protected List<Person> getAllPersons() {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Person> criteriaQuery = criteriaBuilder.createQuery(Person.class);
    criteriaQuery.select(criteriaQuery.from(Person.class));
    return entityManager.createQuery(criteriaQuery).getResultList();
}

From source file:org.osiam.resource_server.storage.dao.ResourceDao.java

private <T extends ResourceEntity> long getTotalResults(Class<T> clazz, Subquery<Long> internalIdQuery) {

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Long> resourceQuery = cb.createQuery(Long.class);
    Root<T> resourceRoot = resourceQuery.from(clazz);

    resourceQuery.select(cb.count(resourceRoot))
            .where(cb.in(resourceRoot.get(ResourceEntity_.internalId)).value(internalIdQuery));

    Long total = em.createQuery(resourceQuery).getSingleResult();

    return total;
}

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

/**
 * {@inheritDoc}//  w ww  . ja va2 s . c  om
 */
public long getTransactionsCount(Map<String, Object> filters, long userId) {

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Long> query = builder.createQuery(Long.class);
    Root<Transaction> root = query.from(Transaction.class);
    query.select(builder.count(root));
    addFilterCriteria(userId, filters, builder, root, query);

    return entityManager.createQuery(query).getSingleResult();

}

From source file:ch.puzzle.itc.mobiliar.business.resourcegroup.control.ResourceGroupRepository.java

/**
 *
 * @param name/*from   w w  w. j  ava2 s  .  c o  m*/
 * @param resourceTypeId
 * @return
 */
public ResourceGroupEntity loadUniqueGroupByNameAndType(String name, Integer resourceTypeId) {
    ResourceGroupEntity result = null;
    try {
        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery<ResourceGroupEntity> q = cb.createQuery(ResourceGroupEntity.class);
        Root<ResourceGroupEntity> r = q.from(ResourceGroupEntity.class);
        r.fetch("resources");
        Join<ResourceGroupEntity, ResourceEntity> resources = r.join("resources");
        Predicate typePred = cb.equal(resources.get("resourceType").get("id"), resourceTypeId);
        Predicate resNamePred = cb.equal(resources.get("name"), name);

        q.where(cb.and(typePred, resNamePred));

        q.distinct(true);

        result = entityManager.createQuery(q).getSingleResult();
    } catch (NoResultException e) {
        // do nothing
    }
    return result;
}

From source file:eu.domibus.common.dao.MessageLogDao.java

public List<MessageLogEntry> findPaged(int from, int max, String column, boolean asc,
        HashMap<String, Object> filters) {

    CriteriaBuilder cb = this.em.getCriteriaBuilder();
    CriteriaQuery<MessageLogEntry> cq = cb.createQuery(MessageLogEntry.class);
    Root<MessageLogEntry> mle = cq.from(MessageLogEntry.class);
    cq.select(mle);/*from   w w w.j  a  v a 2s .  c om*/
    List<Predicate> predicates = new ArrayList<Predicate>();
    for (Map.Entry<String, Object> filter : filters.entrySet()) {
        if (filter.getValue() != null) {
            if (filter.getValue() instanceof String) {
                if (!filter.getValue().toString().isEmpty()) {
                    switch (filter.getKey().toString()) {
                    case "receivedFrom":
                        predicates.add(cb.greaterThanOrEqualTo(mle.<Date>get("received"),
                                Timestamp.valueOf(filter.getValue().toString())));
                        break;
                    case "receivedTo":
                        predicates.add(cb.lessThanOrEqualTo(mle.<Date>get("received"),
                                Timestamp.valueOf(filter.getValue().toString())));
                        break;
                    default:
                        predicates.add(cb.like(mle.<String>get(filter.getKey()), (String) filter.getValue()));
                        break;
                    }
                }
            } else {
                predicates.add(cb.equal(mle.<String>get(filter.getKey()), filter.getValue()));
            }
        }
    }
    cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
    if (column != null) {
        if (asc) {
            cq.orderBy(cb.asc(mle.get(column)));
        } else {
            cq.orderBy(cb.desc(mle.get(column)));
        }

    }
    final TypedQuery<MessageLogEntry> query = this.em.createQuery(cq);
    query.setFirstResult(from);
    query.setMaxResults(max);
    return query.getResultList();
}

From source file:net.dontdrinkandroot.persistence.dao.GenericJpaDao.java

@Override
@Transactional(propagation = Propagation.MANDATORY, readOnly = true)
public <E extends Entity<K>, K> List<E> findAll(final Class<E> clazz) {
    final CriteriaBuilder builder = this.getCriteriaBuilder();
    final CriteriaQuery<E> criteriaQuery = builder.createQuery(clazz);
    criteriaQuery.from(clazz);/*from w w  w  . j  a  v  a  2 s.co m*/

    return this.find(criteriaQuery);
}