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.qpark.eip.core.spring.statistics.dao.StatisticsLoggingDao.java

/**
 * Add the {@link SystemUserLogType} to the database.
 *
 * @param log//from   ww  w .  j  a v a  2  s .c o  m
 *            the {@link SystemUserLogType} to add.
 */
private void addChannelInvocation(final SystemUserLogType log) {
    /* Setup context and version. */
    log.setContext(this.getContextName());
    log.setVersion(this.getContextVersion());
    if (log.getUserName() != null && log.getUserName().trim().length() == 0) {
        log.setUserName(null);
    }

    /* Setup to search existing one. */
    final CriteriaBuilder cb = this.em.getCriteriaBuilder();
    final CriteriaQuery<SystemUserLogType> q = cb.createQuery(SystemUserLogType.class);
    final Root<SystemUserLogType> c = q.from(SystemUserLogType.class);

    final List<Predicate> predicates = new ArrayList<Predicate>();
    predicates.add(cb.equal(c.<String>get(SystemUserLogType_.context), log.getContext()));
    predicates.add(cb.equal(c.<String>get(SystemUserLogType_.version), log.getVersion()));
    if (log.getUserName() == null) {
        predicates.add(cb.isNull(c.<String>get(SystemUserLogType_.userName)));
    } else {
        predicates.add(cb.equal(c.<String>get(SystemUserLogType_.userName), log.getUserName()));
    }
    predicates.add(cb.equal(c.<String>get(SystemUserLogType_.serviceName), log.getServiceName()));
    predicates.add(cb.equal(c.<String>get(SystemUserLogType_.operationName), log.getOperationName()));
    predicates.add(cb.between(c.<Date>get(SystemUserLogType_.logDateItem), getDayStart(log.getLogDateItem()),
            getDayEnd(log.getLogDateItem())));

    q.where(predicates.toArray(new Predicate[predicates.size()]));
    q.orderBy(cb.desc(c.<Long>get(SystemUserLogType_.hjid)));
    TypedQuery<SystemUserLogType> typedQuery = this.em.createQuery(q);

    SystemUserLogType persistence = null;
    synchronized (StatisticsLoggingDao.class) {
        try {
            persistence = typedQuery.getSingleResult();
            if (persistence == null) {
                /* Not found -> persist */
                persistence = log;
                this.setupSystemUserLog(persistence, null);
                this.em.persist(persistence);
            } else {
                /* Found -> add and merge */
                this.setupSystemUserLog(persistence, log);
                this.em.merge(persistence);
            }
        } catch (final NoResultException e) {
            /* Not found -> persist */
            persistence = log;
            this.setupSystemUserLog(persistence, null);
            this.em.persist(persistence);
        } catch (final NonUniqueResultException e) {
            /* Found more */
            typedQuery = this.em.createQuery(q);
            final List<SystemUserLogType> list = typedQuery.getResultList();
            SystemUserLogType l;
            for (int i = 0; i < list.size(); i++) {
                l = list.get(i);
                if (persistence == null && l.getHjid() != null) {
                    persistence = l;
                    break;
                }
            }
            if (persistence != null) {
                /* Found more -> condense to first valid one -> merge. */
                this.setupSystemUserLog(persistence, log);
                for (int i = list.size() - 1; i >= 0; i--) {
                    l = list.get(i);
                    if (l != null && l.getHjid() != null) {
                        if (persistence.getHjid().equals(l.getHjid())) {
                        } else {
                            this.setupSystemUserLog(persistence, l);
                            list.remove(i);
                            this.em.remove(l);
                        }
                    }
                }
                this.em.merge(persistence);
            } else {
                /* Found more -> no valid one in list -> persist. */
                persistence = log;
                this.setupSystemUserLog(persistence, null);
                this.em.persist(persistence);
            }
        }
    }
    this.logger.debug("addChannelInvocation SystemUserLog {} {} {} {} {} {}",
            this.contextNameProvider.getContextName(), this.contextNameProvider.getContextVersion(),
            String.valueOf(persistence.getUserName()), persistence.getServiceName(),
            persistence.getOperationName(), persistence.getLogDate().toXMLFormat());
}

From source file:com.yunguchang.data.ApplicationRepository.java

public TBusApplyinfoEntity getApplicationById(String id, PrincipalExt principalExt) {
    applySecurityFilter("applications", principalExt);

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<TBusApplyinfoEntity> cq = cb.createQuery(TBusApplyinfoEntity.class);
    Root<TBusApplyinfoEntity> applyRoot = cq.from(TBusApplyinfoEntity.class);
    applyRoot.fetch(TBusApplyinfoEntity_.passenger, JoinType.LEFT);
    applyRoot.fetch(TBusApplyinfoEntity_.senduser, JoinType.LEFT);
    cq.where(cb.equal(applyRoot.get(TBusApplyinfoEntity_.uuid), id));
    return Iterables.getFirst(em.createQuery(cq).getResultList(), null);
}

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);//from   ww w  .j a v  a 2 s  . c  o  m
    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 (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:net.shopxx.dao.impl.ArticleDaoImpl.java

public Page<Article> findPage(ArticleCategory articleCategory, Tag tag, Boolean isPublication,
        Pageable pageable) {/* w  w  w  . j  a  v  a2 s.  co m*/
    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:net.groupbuy.dao.impl.ProductNotifyDaoImpl.java

public Long count(Member member, Boolean isMarketable, Boolean isOutOfStock, Boolean hasSent) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<ProductNotify> criteriaQuery = criteriaBuilder.createQuery(ProductNotify.class);
    Root<ProductNotify> root = criteriaQuery.from(ProductNotify.class);
    criteriaQuery.select(root);/*from  ww w  . j a va 2 s. com*/
    Predicate restrictions = criteriaBuilder.conjunction();
    if (member != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member));
    }
    if (isMarketable != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("product").get("isMarketable"), isMarketable));
    }
    if (isOutOfStock != null) {
        Path<Integer> stock = root.get("product").get("stock");
        Path<Integer> allocatedStock = root.get("product").get("allocatedStock");
        if (isOutOfStock) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock),
                    criteriaBuilder.lessThanOrEqualTo(stock, allocatedStock));
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.isNull(stock),
                    criteriaBuilder.greaterThan(stock, allocatedStock)));
        }
    }
    if (hasSent != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("hasSent"), hasSent));
    }
    criteriaQuery.where(restrictions);
    return super.count(criteriaQuery, null);
}

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

public Page<ProductNotify> findPage(Member member, Boolean isMarketable, Boolean isOutOfStock, Boolean hasSent,
        Pageable pageable) {//ww  w.  j  a  v  a2 s .  c o  m
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<ProductNotify> criteriaQuery = criteriaBuilder.createQuery(ProductNotify.class);
    Root<ProductNotify> root = criteriaQuery.from(ProductNotify.class);
    criteriaQuery.select(root);
    Predicate restrictions = criteriaBuilder.conjunction();
    if (member != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member));
    }
    if (isMarketable != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("product").get("isMarketable"), isMarketable));
    }
    if (isOutOfStock != null) {
        Path<Integer> stock = root.get("product").get("stock");
        Path<Integer> allocatedStock = root.get("product").get("allocatedStock");
        if (isOutOfStock) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock),
                    criteriaBuilder.lessThanOrEqualTo(stock, allocatedStock));
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.isNull(stock),
                    criteriaBuilder.greaterThan(stock, allocatedStock)));
        }
    }
    if (hasSent != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("hasSent"), hasSent));
    }
    criteriaQuery.where(restrictions);
    return super.findPage(criteriaQuery, pageable);
}

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

public Long count(Member member, Boolean isMarketable, Boolean isOutOfStock, Boolean hasSent) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<ProductNotify> criteriaQuery = criteriaBuilder.createQuery(ProductNotify.class);
    Root<ProductNotify> root = criteriaQuery.from(ProductNotify.class);
    criteriaQuery.select(root);/*w  ww .ja v a  2 s .  c  o  m*/
    Predicate restrictions = criteriaBuilder.conjunction();
    if (member != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member));
    }
    if (isMarketable != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("product").get("goods").get("isMarketable"), isMarketable));
    }
    if (isOutOfStock != null) {
        Path<Integer> stock = root.get("product").get("stock");
        Path<Integer> allocatedStock = root.get("product").get("allocatedStock");
        if (isOutOfStock) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock),
                    criteriaBuilder.lessThanOrEqualTo(stock, allocatedStock));
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.isNull(stock),
                    criteriaBuilder.greaterThan(stock, allocatedStock)));
        }
    }
    if (hasSent != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("hasSent"), hasSent));
    }
    criteriaQuery.where(restrictions);
    return super.count(criteriaQuery, null);
}

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

@Override
public void afterPropertiesSet() throws Exception {
    this.nameParameter = this.createParameterExpression(String.class, "name");
    this.titleParameter = this.createParameterExpression(String.class, "title");

    this.findAllPortletDefinitions = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<PortletDefinitionImpl>>() {
                @Override// w  w  w  . j  av  a2  s .  c o m
                public CriteriaQuery<PortletDefinitionImpl> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<PortletDefinitionImpl> criteriaQuery = cb
                            .createQuery(PortletDefinitionImpl.class);
                    final Root<PortletDefinitionImpl> definitionRoot = criteriaQuery
                            .from(PortletDefinitionImpl.class);
                    criteriaQuery.select(definitionRoot);
                    addFetches(definitionRoot);

                    return criteriaQuery;
                }
            });

    this.findDefinitionByNameQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<PortletDefinitionImpl>>() {
                @Override
                public CriteriaQuery<PortletDefinitionImpl> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<PortletDefinitionImpl> criteriaQuery = cb
                            .createQuery(PortletDefinitionImpl.class);
                    final Root<PortletDefinitionImpl> definitionRoot = criteriaQuery
                            .from(PortletDefinitionImpl.class);
                    criteriaQuery.select(definitionRoot);
                    addFetches(definitionRoot);
                    criteriaQuery
                            .where(cb.equal(definitionRoot.get(PortletDefinitionImpl_.name), nameParameter));

                    return criteriaQuery;
                }
            });

    this.findDefinitionByNameOrTitleQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<PortletDefinitionImpl>>() {
                @Override
                public CriteriaQuery<PortletDefinitionImpl> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<PortletDefinitionImpl> criteriaQuery = cb
                            .createQuery(PortletDefinitionImpl.class);
                    final Root<PortletDefinitionImpl> definitionRoot = criteriaQuery
                            .from(PortletDefinitionImpl.class);
                    criteriaQuery.select(definitionRoot);
                    addFetches(definitionRoot);
                    criteriaQuery.where(cb.or(
                            cb.equal(definitionRoot.get(PortletDefinitionImpl_.name), nameParameter),
                            cb.equal(definitionRoot.get(PortletDefinitionImpl_.title), titleParameter)));

                    return criteriaQuery;
                }
            });

    this.searchDefinitionByNameOrTitleQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<PortletDefinitionImpl>>() {
                @Override
                public CriteriaQuery<PortletDefinitionImpl> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<PortletDefinitionImpl> criteriaQuery = cb
                            .createQuery(PortletDefinitionImpl.class);
                    final Root<PortletDefinitionImpl> definitionRoot = criteriaQuery
                            .from(PortletDefinitionImpl.class);
                    criteriaQuery.select(definitionRoot);
                    addFetches(definitionRoot);
                    criteriaQuery.where(
                            cb.or(cb.like(definitionRoot.get(PortletDefinitionImpl_.name), nameParameter),
                                    cb.like(definitionRoot.get(PortletDefinitionImpl_.title), titleParameter)));

                    return criteriaQuery;
                }
            });
}

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

public Page<ProductNotify> findPage(Member member, Boolean isMarketable, Boolean isOutOfStock, Boolean hasSent,
        Pageable pageable) {//ww w  . j  av a  2 s.co m
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<ProductNotify> criteriaQuery = criteriaBuilder.createQuery(ProductNotify.class);
    Root<ProductNotify> root = criteriaQuery.from(ProductNotify.class);
    criteriaQuery.select(root);
    Predicate restrictions = criteriaBuilder.conjunction();
    if (member != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member));
    }
    if (isMarketable != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("product").get("goods").get("isMarketable"), isMarketable));
    }
    if (isOutOfStock != null) {
        Path<Integer> stock = root.get("product").get("stock");
        Path<Integer> allocatedStock = root.get("product").get("allocatedStock");
        if (isOutOfStock) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock),
                    criteriaBuilder.lessThanOrEqualTo(stock, allocatedStock));
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.isNull(stock),
                    criteriaBuilder.greaterThan(stock, allocatedStock)));
        }
    }
    if (hasSent != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("hasSent"), hasSent));
    }
    criteriaQuery.where(restrictions);
    return super.findPage(criteriaQuery, pageable);
}

From source file:org.apache.openejb.util.proxy.QueryProxy.java

private <T> Query createFinderQuery(final EntityManager entityManager, final String methodName,
        final Class<T> entityType, final Object[] args) {
    final List<String> conditions = parseMethodName(methodName);

    final EntityType<T> et = entityManager.getMetamodel().entity(entityType);
    final CriteriaBuilder cb = entityManager.getCriteriaBuilder();

    CriteriaQuery<Object> query = cb.createQuery();
    final Root<T> from = query.from(entityType);
    query = query.select(from);/*from   www.ja v a 2  s . co  m*/

    int i = 0;
    Predicate where = null;
    for (final String condition : conditions) {
        final SingularAttribute<? super T, ?> attribute = et.getSingularAttribute(condition);
        final Path<?> path = from.get(attribute);
        final Class<?> javaType = attribute.getType().getJavaType();

        final Predicate currentClause;
        if (javaType.equals(String.class)) {
            currentClause = cb.like((Expression<String>) path, (String) args[i++]);
        } else if (Number.class.isAssignableFrom(javaType) || javaType.isPrimitive()) {
            currentClause = cb.equal(path, args[i++]);
        } else {
            LOGGER.warning("field " + condition + " not found, ignoring");
            continue;
        }

        if (where == null) {
            where = currentClause;
        } else {
            where = cb.and(where, currentClause);
        }
    }

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

    // pagination
    final TypedQuery<?> emQuery = entityManager.createQuery(query);
    if (args != null && args.length == conditions.size() + 2 && isInt(args[args.length - 2].getClass())
            && isInt(args[args.length - 1].getClass())) {
        final int first = (Integer) args[args.length - 2];
        final int max = (Integer) args[args.length - 1];

        emQuery.setFirstResult(first);
        emQuery.setMaxResults(max);
    }

    return emQuery;
}