Example usage for javax.persistence.criteria CriteriaQuery where

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

Introduction

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

Prototype

CriteriaQuery<T> where(Predicate... restrictions);

Source Link

Document

Modify the query to restrict the query result according to the conjunction of the specified restriction predicates.

Usage

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

/**
 * {@inheritDoc}/*from w w  w.j  a  va  2  s .  co m*/
 */
@Override
public <T extends BaseEntity> List<T> findByCriteria(ReadCriteria<T> criteria) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<T> cq = cb.createQuery(criteria.getEntity());
        Root<T> root = cq.from(criteria.getEntity());
        return em.createQuery(cq.where(cb.and(Predicates.from(criteria.getCriteriaAttributes(), cb, root))))
                .getResultList();
    } catch (Exception ex) { // NOSONAR
        throw new JpaException(ex);
    } finally {
        JpaUtil.closeEntityManager(em);
    }
}

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

/**
 * {@inheritDoc}/*from   w  w w . ja va2s.c  o  m*/
 */
@Override
public <T extends BaseEntity> List<T> findPaginatedRecordsByCriteria(ReadCriteria<T> criteria) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<T> cq = cb.createQuery(criteria.getEntity());
        Root<T> root = cq.from(criteria.getEntity());
        return em.createQuery(cq.where(cb.and(Predicates.from(criteria.getCriteriaAttributes(), cb, root))))
                .setFirstResult(criteria.getStartPos()).setMaxResults(criteria.getMaxResult()).getResultList();
    } catch (Exception ex) { // NOSONAR
        throw new JpaException(ex);
    } finally {
        JpaUtil.closeEntityManager(em);
    }
}

From source file:cn.guoyukun.spring.jpa.repository.support.SimpleBaseRepository.java

/**
 * Applies the given {@link org.springframework.data.jpa.domain.Specification} to the given {@link javax.persistence.criteria.CriteriaQuery}.
 *
 * @param spec  can be {@literal null}./*from   www .j av a  2s  .co m*/
 * @param query must not be {@literal null}.
 * @return
 */
private <S> Root<M> applySpecificationToCriteria(Specification<M> spec, CriteriaQuery<S> query) {

    Assert.notNull(query);
    Root<M> root = query.from(entityClass);

    if (spec == null) {
        return root;
    }

    CriteriaBuilder builder = em.getCriteriaBuilder();
    Predicate predicate = spec.toPredicate(root, query, builder);

    if (predicate != null) {
        query.where(predicate);
    }

    return root;
}

From source file:com.netflix.genie.core.jpa.services.JpaJobSearchServiceImpl.java

/**
 * {@inheritDoc}/*  w w  w  . j a  va  2  s .co m*/
 */
@Override
public Page<JobSearchResult> findJobs(final String id, final String jobName, final String user,
        final Set<JobStatus> statuses, final Set<String> tags, final String clusterName, final String clusterId,
        final String commandName, final String commandId, final Date minStarted, final Date maxStarted,
        final Date minFinished, final Date maxFinished, @NotNull final Pageable page) {
    log.debug("called");

    final CriteriaBuilder cb = this.entityManager.getCriteriaBuilder();
    final CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
    final Root<JobEntity> root = countQuery.from(JobEntity.class);

    final Predicate whereClause = JpaJobSpecs.getFindPredicate(root, cb, id, jobName, user, statuses, tags,
            clusterName, clusterId == null ? null : this.clusterRepository.findOne(clusterId), commandName,
            commandId == null ? null : this.commandRepository.findOne(commandId), minStarted, maxStarted,
            minFinished, maxFinished);

    countQuery.select(cb.count(root)).where(whereClause);

    final Long count = this.entityManager.createQuery(countQuery).getSingleResult();

    // Use the count to make sure we even need to make this query
    if (count > 0) {
        final CriteriaQuery<JobSearchResult> contentQuery = cb.createQuery(JobSearchResult.class);
        contentQuery.from(JobEntity.class);

        contentQuery.multiselect(root.get(JobEntity_.id), root.get(JobEntity_.name), root.get(JobEntity_.user),
                root.get(JobEntity_.status), root.get(JobEntity_.started), root.get(JobEntity_.finished),
                root.get(JobEntity_.clusterName), root.get(JobEntity_.commandName));

        contentQuery.where(whereClause);

        final Sort sort = page.getSort();
        final List<Order> orders = new ArrayList<>();
        sort.iterator().forEachRemaining(order -> {
            if (order.isAscending()) {
                orders.add(cb.asc(root.get(order.getProperty())));
            } else {
                orders.add(cb.desc(root.get(order.getProperty())));
            }
        });

        contentQuery.orderBy(orders);

        final List<JobSearchResult> results = this.entityManager.createQuery(contentQuery)
                .setFirstResult(page.getOffset()).setMaxResults(page.getPageSize()).getResultList();

        return new PageImpl<>(results, page, count);
    } else {
        return new PageImpl<>(Lists.newArrayList(), page, count);
    }
}

From source file:org.apereo.portal.portlet.dao.jpa.JpaMarketplaceRatingDao.java

/**
 * @since 5.0/*  w ww  . j a v a2 s. c  o m*/
 * @param marketplaceRatingPK the primary key of the entity you want
 * @return Set of ratings per portlet definition
 */
@PortalTransactionalReadOnly
@OpenEntityManager(unitName = PERSISTENCE_UNIT_NAME)
public Set<IMarketplaceRating> getRatingsByFname(String fname) {

    //Build criteria to fetch MarketplaceRatingImpl based on the incoming portlet name. 
    final EntityManager entityManager = this.getEntityManager();
    final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    final CriteriaQuery<IMarketplaceRating> getByPortlet = cb.createQuery(IMarketplaceRating.class);
    final Root<MarketplaceRatingImpl> imr = getByPortlet.from(MarketplaceRatingImpl.class);
    getByPortlet.select(imr);

    //Define the path to the portlet fName
    final Path<MarketplaceRatingPK> mrPK = imr.get("marketplaceRatingPK");
    final Path<PortletDefinitionImpl> mrIPD = mrPK.get("portletDefinition");

    final ParameterExpression<String> portletFName = cb.parameter(String.class, "portletFName");

    getByPortlet.where(cb.equal(mrIPD.get("fname"), portletFName));
    TypedQuery<IMarketplaceRating> tq = entityManager.createQuery(getByPortlet);
    tq.setParameter("portletFName", fname);
    List<IMarketplaceRating> resultList = tq.getResultList();
    Set<IMarketplaceRating> resultSet = new HashSet<IMarketplaceRating>(resultList);
    return resultSet;

}

From source file:de.ks.idnadrev.information.view.InformationOverviewDS.java

private List<InformationPreviewItem> getResults(String name, List<String> tagNames, Category category,
        EntityManager em, CriteriaBuilder builder, Class<? extends Information<?>> clazz) {
    CriteriaQuery<InformationPreviewItem> query = builder.createQuery(InformationPreviewItem.class);
    Root<? extends Information<?>> root = query.from(clazz);

    ArrayList<Predicate> filters = new ArrayList<>();
    if (!name.isEmpty()) {
        filters.add(builder.like(builder.lower(root.<String>get(KEY_NAME)), name));
    }//from  w  w w .  j ava 2s.  c  o m
    if (!tagNames.isEmpty()) {
        List<Tag> tags = getTags(tagNames, em);
        SetJoin<TextInfo, Tag> tagJoin = root.joinSet(KEY_TAGS);
        filters.add(tagJoin.in(tags));
    }
    if (category != null) {
        filters.add(builder.equal(root.get(KEY_CATEGORY), category));
    }
    query.distinct(true);

    query.where(filters.toArray(new Predicate[filters.size()]));
    query.select(
            builder.construct(InformationPreviewItem.class, root.get(KEY_NAME), root.get(KEY_CREATIONTIME)));
    List<InformationPreviewItem> resultList = em.createQuery(query).getResultList();
    return resultList;
}

From source file:ch.puzzle.itc.mobiliar.business.resourcerelation.control.ResourceRelationService.java

public List<ConsumedResourceRelationEntity> getConsumedSlaveRelations(ResourceEntity slaveResource) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<ConsumedResourceRelationEntity> q = cb.createQuery(ConsumedResourceRelationEntity.class);
    Root<ConsumedResourceRelationEntity> r = q.from(ConsumedResourceRelationEntity.class);
    Join<ConsumedResourceRelationEntity, ResourceEntity> slaveResourceJoin = r.join("slaveResource");
    q.where(cb.equal(slaveResourceJoin.get("id"), slaveResource.getId()));

    TypedQuery<ConsumedResourceRelationEntity> query = entityManager.createQuery(q);
    return query.getResultList();
}

From source file:ch.puzzle.itc.mobiliar.business.resourcerelation.control.ResourceRelationService.java

public List<ProvidedResourceRelationEntity> getProvidedSlaveRelations(ResourceEntity slaveResource) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<ProvidedResourceRelationEntity> q = cb.createQuery(ProvidedResourceRelationEntity.class);
    Root<ProvidedResourceRelationEntity> r = q.from(ProvidedResourceRelationEntity.class);
    Join<ProvidedResourceRelationEntity, ResourceEntity> slaveResourceJoin = r.join("slaveResource");
    q.where(cb.equal(slaveResourceJoin.get("id"), slaveResource.getId()));

    TypedQuery<ProvidedResourceRelationEntity> query = entityManager.createQuery(q);
    return query.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);/*  ww w.j  a  v  a  2 s . c o  m*/
    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 {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNull(root.get("sender")));
    }
    criteriaQuery.where(restrictions);
    return super.findPage(criteriaQuery, pageable);
}

From source file:com.home.ln_spring.ch10.service.jpa.ContactServiceImplOld.java

@Override
@Transactional(readOnly = true)//from  ww  w  .  j av  a2  s .c  om
public List<Contact> findByCriteriaQuery(String firstName, String lastName) {
    log.info("Finding contact for firstName: " + firstName + " and lastName: " + lastName);

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Contact> criteriaQuery = cb.createQuery(Contact.class);
    Root<Contact> contactRoot = criteriaQuery.from(Contact.class);
    contactRoot.fetch(Contact_.contactTelDetails, JoinType.LEFT);
    contactRoot.fetch(Contact_.hobbies, JoinType.LEFT);

    criteriaQuery.select(contactRoot).distinct(true);

    Predicate criteria = cb.conjunction();
    if (firstName != null) {
        Predicate p = cb.equal(contactRoot.get(Contact_.firstName), firstName);
        criteria = cb.and(criteria, p);
    }

    if (lastName != null) {
        Predicate p = cb.equal(contactRoot.get(Contact_.lastName), lastName);
        criteria = cb.and(criteria, p);
    }

    criteriaQuery.where(criteria);
    List<Contact> result = em.createQuery(criteriaQuery).getResultList();
    return result;
}