Example usage for javax.persistence.criteria CriteriaBuilder like

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

Introduction

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

Prototype

Predicate like(Expression<String> x, String pattern);

Source Link

Document

Create a predicate for testing whether the expression satisfies the given pattern.

Usage

From source file:com.qpark.eip.core.model.analysis.AnalysisDao.java

/**
 * Get the list of {@link FlowType}s matching the name pattern.
 *
 * @param modelVersion//from   ww w.jav a2  s  .  c  o m
 *            the model version.
 * @param namePattern
 *            the name pattern.
 * @return the list of {@link FlowType}s matching the name pattern.
 * @since 3.5.1
 */
@Transactional(value = EipModelAnalysisPersistenceConfig.TRANSACTION_MANAGER_NAME, propagation = Propagation.REQUIRED)
public List<FlowType> getFlowByNamePattern(final String modelVersion, final Collection<String> namePattern) {
    final CriteriaBuilder cb = this.em.getCriteriaBuilder();
    final CriteriaQuery<FlowType> q = cb.createQuery(FlowType.class);
    final Root<FlowType> f = q.from(FlowType.class);

    final Predicate or = cb.disjunction();
    namePattern.stream()
            .forEach(id -> or.getExpressions().add(cb.like(f.<String>get(FlowType_.name), "%" + id + "%")));
    final Predicate and = cb.conjunction();
    and.getExpressions().add(cb.equal(f.<String>get(FlowType_.modelVersion), modelVersion));
    and.getExpressions().add(or);
    q.where(and);
    final TypedQuery<FlowType> typedQuery = this.em.createQuery(q);
    final List<FlowType> value = typedQuery.getResultList();
    value.stream().forEach(ft -> EagerLoader.load(ft));
    return value;
}

From source file:name.marcelomorales.siqisiqi.openjpa.impl.OrmFinderImpl.java

protected Predicate newFullTextPredicate(CriteriaBuilder cb, Root<T> p, String terms) {
    LinkedList<Predicate> predicatesOr = Lists.newLinkedList();
    Iterable<Path<String>> fullTexts = settings.getFullTexts(p, persistentClass);
    if (fullTexts != null) {
        for (Path<String> x : fullTexts) {
            StringTokenizer tokenizer = new StringTokenizer(terms, " \t\n\r\f,.;:/");
            LinkedList<Predicate> predicatesAnd = Lists.newLinkedList();
            while (tokenizer.hasMoreTokens()) {
                String token = "%" + tokenizer.nextToken() + "%";

                predicatesAnd.add(cb.like(cb.lower(x), StringUtils.lowerCase(token)));
            }/*from   www .j  a va2  s  .c om*/
            predicatesOr.add(cb.and(predicatesAnd.toArray(new Predicate[predicatesAnd.size()])));
        }
    }
    final Predicate[] restrictions = predicatesOr.toArray(new Predicate[predicatesOr.size()]);
    return cb.or(restrictions);
}

From source file:com.ims.service.SupportingDataService.java

/**
 * SQL: select * from ims_product_info where CATEGORY_CODE='xxx' and PRODUCT_CODE like '%yyy%' and (CUST_PROD_CODE like '%aaa%' or CUST_PROD_SECOND_CODE like '%aaa%')
 * ??/*from w ww  .j av a  2 s. com*/
 *
 * @param prodSearchCriteria
 * @return
 */
public List<ProductInfo> findProductInfoListFrom(final ProdSearchCriteria prodSearchCriteria) {
    Specification<ProductInfo> speci = new Specification<ProductInfo>() {
        @Override
        public Predicate toPredicate(Root<ProductInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            List<Predicate> predicates = new ArrayList<Predicate>();
            Path<String> custProdCode = root.<String>get(ProductInfo.CUST_PROD_CODE);
            Path<String> custProdCode2 = root.<String>get(ProductInfo.CUST_SEC_PROD_CODE);
            Predicate orClause = null;

            if (StringUtils.isNotBlank(prodSearchCriteria.getProdCategoryCode())) {
                predicates.add(cb.equal(root.get(ProductInfo.CATEGORY_CODE),
                        prodSearchCriteria.getProdCategoryCode()));
            }
            if (StringUtils.isNotEmpty(prodSearchCriteria.getProdCode())) {
                predicates.add(cb.like(root.<String>get(ProductInfo.PRODUCT_CODE),
                        getLikeString(prodSearchCriteria.getProdCode())));
            }
            if (StringUtils.isNotBlank(prodSearchCriteria.getCustProdCode())) {
                //??orpredicates?where? query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
                //Predicate p1 = cb.or(cb.like(custProdCode, getLikeString(prodSearchCriteria.getCustProdCode())), cb.like(custProdCode2, getLikeString(prodSearchCriteria.getCustProdCode())));
                //predicates.add(p1);

                //??orPredicate?where????query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])),orClause);
                String param = getLikeString(prodSearchCriteria.getCustProdCode());
                orClause = cb.or(cb.like(custProdCode, param), cb.like(custProdCode2, param));
            }
            //select * from ims_product_info  where CATEGORY_CODE=? and (PRODUCT_CODE like ?) and (CUST_PROD_CODE like ? or CUST_PROD_SECOND_CODE like ?)
            //??
            //query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));

            //??
            if (orClause != null) {
                query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])), orClause);
            } else {
                query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
            }
            return null;
        }
    };

    return productInfoRepository.findAll(speci);
}

From source file:eu.uqasar.service.user.UserService.java

private List<Predicate> getFilterPredicates(final UserFilterStructure filter, CriteriaBuilder cb,
        Root<User> from) {//from  w ww  .  j a va  2 s. c  o  m
    List<Predicate> predicates = new ArrayList<>();
    if (filter == null) {
        return predicates;
    }

    if (filter.getRole() != null) {
        predicates.add(cb.equal(from.get(User_.userRole), filter.getRole()));
    }
    if (filter.getSource() != null) {
        predicates.add(cb.equal(from.get(User_.source), filter.getSource()));
    }
    if (filter.getStatus() != null) {
        predicates.add(cb.equal(from.get(User_.registrationStatus), filter.getStatus()));
    }
    if (!StringUtils.isEmpty(filter.getName())) {
        Predicate firstName = cb.like(cb.lower(from.get(User_.lastName)),
                LIKE_WILDCARD + filter.getName().toLowerCase() + LIKE_WILDCARD);
        Predicate lastName = cb.like(from.get(User_.firstName),
                LIKE_WILDCARD + filter.getName() + LIKE_WILDCARD);
        Predicate userName = cb.like(from.get(User_.userName),
                LIKE_WILDCARD + filter.getName() + LIKE_WILDCARD);
        Expression<String> fullName = cb.concat(cb.concat(from.get(User_.firstName), " "),
                from.get(User_.lastName));
        Expression<String> un = cb.concat(" (", cb.concat(from.get(User_.userName), ")"));
        Predicate fn = cb.like(fullName, LIKE_WILDCARD + filter.getName() + LIKE_WILDCARD);
        Expression<String> fnu = cb.concat(fullName, un);
        Predicate ff1 = cb.like(fnu, LIKE_WILDCARD + filter.getName() + LIKE_WILDCARD);

        predicates.add(cb.or(firstName, lastName, userName, fn, ff1));

    }
    return predicates;
}

From source file:com.sammyun.dao.impl.BaseDaoImpl.java

private void addRestrictions(CriteriaQuery<T> criteriaQuery, Pageable pageable) {
    if (criteriaQuery == null || pageable == null) {
        return;//from   w  w w.ja v  a2s.  c o m
    }
    Root<T> root = getRoot(criteriaQuery);
    if (root == null) {
        return;
    }
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    Predicate restrictions = criteriaQuery.getRestriction() != null ? criteriaQuery.getRestriction()
            : criteriaBuilder.conjunction();
    if (StringUtils.isNotEmpty(pageable.getSearchProperty())
            && StringUtils.isNotEmpty(pageable.getSearchValue())) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder
                .like(root.<String>get(pageable.getSearchProperty()), "%" + pageable.getSearchValue() + "%"));
    }
    if (pageable.getFilters() != null) {
        for (Filter filter : pageable.getFilters()) {
            if (filter == null || StringUtils.isEmpty(filter.getProperty())) {
                continue;
            }
            /**  */
            if (filter.getMold() == Mold.dl || filter.getMold() == Mold.dg) {
                if (filter.getOperator() == Operator.lt && filter.getValue() != null) {
                    restrictions = criteriaBuilder.and(restrictions,
                            criteriaBuilder.lessThan(root.<Date>get(filter.getProperty()),
                                    DateUtil.parseDate(filter.getValue().toString())));
                } else if (filter.getOperator() == Operator.gt && filter.getValue() != null) {
                    restrictions = criteriaBuilder.and(restrictions,
                            criteriaBuilder.greaterThan(root.<Date>get(filter.getProperty()),
                                    DateUtil.parseDate(filter.getValue().toString())));
                } else if (filter.getOperator() == Operator.le && filter.getValue() != null) {
                    restrictions = criteriaBuilder.and(restrictions,
                            criteriaBuilder.lessThanOrEqualTo(root.<Date>get(filter.getProperty()),
                                    DateUtil.parseDate(filter.getValue().toString())));
                } else if (filter.getOperator() == Operator.ge && filter.getValue() != null) {
                    restrictions = criteriaBuilder.and(restrictions,
                            criteriaBuilder.greaterThanOrEqualTo(root.<Date>get(filter.getProperty()),
                                    DateUtil.parseDate(filter.getValue().toString())));
                }
            } else {

                if (filter.getOperator() == Operator.eq && filter.getValue() != null) {
                    if (filter.getIgnoreCase() != null && filter.getIgnoreCase()
                            && filter.getValue() instanceof String) {
                        restrictions = criteriaBuilder.and(restrictions,
                                criteriaBuilder.equal(
                                        criteriaBuilder.lower(root.<String>get(filter.getProperty())),
                                        ((String) filter.getValue()).toLowerCase()));
                    } else {
                        restrictions = criteriaBuilder.and(restrictions,
                                criteriaBuilder.equal(root.get(filter.getProperty()), filter.getValue()));
                    }
                } else if (filter.getOperator() == Operator.ne && filter.getValue() != null) {
                    if (filter.getIgnoreCase() != null && filter.getIgnoreCase()
                            && filter.getValue() instanceof String) {
                        restrictions = criteriaBuilder.and(restrictions,
                                criteriaBuilder.notEqual(
                                        criteriaBuilder.lower(root.<String>get(filter.getProperty())),
                                        ((String) filter.getValue()).toLowerCase()));
                    } else {
                        restrictions = criteriaBuilder.and(restrictions,
                                criteriaBuilder.notEqual(root.get(filter.getProperty()), filter.getValue()));
                    }
                } else if (filter.getOperator() == Operator.gt && filter.getValue() != null) {
                    restrictions = criteriaBuilder.and(restrictions, criteriaBuilder
                            .gt(root.<Number>get(filter.getProperty()), (Number) filter.getValue()));
                } else if (filter.getOperator() == Operator.lt && filter.getValue() != null) {
                    restrictions = criteriaBuilder.and(restrictions, criteriaBuilder
                            .lt(root.<Number>get(filter.getProperty()), (Number) filter.getValue()));
                } else if (filter.getOperator() == Operator.ge && filter.getValue() != null) {
                    restrictions = criteriaBuilder.and(restrictions, criteriaBuilder
                            .ge(root.<Number>get(filter.getProperty()), (Number) filter.getValue()));
                } else if (filter.getOperator() == Operator.le && filter.getValue() != null) {
                    restrictions = criteriaBuilder.and(restrictions, criteriaBuilder
                            .le(root.<Number>get(filter.getProperty()), (Number) filter.getValue()));
                } else if (filter.getOperator() == Operator.like && filter.getValue() != null
                        && filter.getValue() instanceof String) {
                    restrictions = criteriaBuilder.and(restrictions, criteriaBuilder
                            .like(root.<String>get(filter.getProperty()), (String) filter.getValue()));
                } else if (filter.getOperator() == Operator.in && filter.getValue() != null) {
                    restrictions = criteriaBuilder.and(restrictions,
                            root.get(filter.getProperty()).in(filter.getValue()));
                } else if (filter.getOperator() == Operator.isNull) {
                    restrictions = criteriaBuilder.and(restrictions, root.get(filter.getProperty()).isNull());
                } else if (filter.getOperator() == Operator.isNotNull) {
                    restrictions = criteriaBuilder.and(restrictions,
                            root.get(filter.getProperty()).isNotNull());
                }
            }
        }
    }
    criteriaQuery.where(restrictions);
}

From source file:com.creditcloud.common.entities.dao.AbstractReadDAO.java

/**
 * count entity by ParamInfo//  w  w  w .j  a v a  2  s.  co  m
 *
 * @param paramInfo
 * @return
 */
public int count(ParamInfo paramInfo) {
    EntityManager em = getEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery(entityClass);
    Root<T> userRoot = cq.from(entityClass);
    cq.select(cb.count(userRoot));

    //build query for paramInfo
    if (paramInfo != null) {
        Set<Predicate> andCriteria = new HashSet();
        Set<Predicate> orCriteria = new HashSet();

        for (ParamItem item : paramInfo.getParamItems()) {
            Predicate predicate;
            if (item.getValue() instanceof String) {
                //fuzy search for string
                String regExp = "%" + item.getValue() + "%";
                predicate = cb.like((Expression) (userRoot.get(item.getFieldName())), regExp);
            } else {
                predicate = cb.equal((userRoot.get(item.getFieldName())), item.getValue());
            }

            switch (item.getOperator()) {
            case AND:
                andCriteria.add(predicate);
                break;
            case OR:
                orCriteria.add(predicate);
                break;
            }
        }
        if (orCriteria.size() > 0) {
            Predicate or = cb.or(orCriteria.toArray(new Predicate[orCriteria.size()]));
            andCriteria.add(or);
        }
        if (andCriteria.size() > 0) {
            Predicate and = cb.and(andCriteria.toArray(new Predicate[andCriteria.size()]));
            cq.where(and);
        }
    }

    TypedQuery<Long> query = em.createQuery(cq);
    Long result = query.getSingleResult();
    return result == null ? 0 : result.intValue();
}

From source file:org.businessmanager.dao.GenericDaoImpl.java

@SuppressWarnings("unchecked")
private List<Predicate> createFilterList(Map<SingularAttribute<T, ?>, Object> filterAttributes,
        boolean enableLikeSearch, CriteriaBuilder queryBuilder, Root<T> rootQuery) {
    List<Predicate> predicateList = new ArrayList<Predicate>();
    if (filterAttributes != null) {
        Iterator<SingularAttribute<T, ?>> iter = filterAttributes.keySet().iterator();
        while (iter.hasNext()) {
            SingularAttribute<T, ?> key = iter.next();
            Object value = filterAttributes.get(key);
            if (enableLikeSearch) {
                String searchKey = value.toString();
                if (!value.toString().contains("%")) {
                    searchKey = "%" + value.toString() + "%";
                }//from www .j a va 2s. co m

                Expression<String> lowerKey = queryBuilder.lower((Expression<String>) rootQuery.get(key));
                Predicate predicate = queryBuilder.like(lowerKey, searchKey.toLowerCase());
                predicateList.add(predicate);
            } else {
                Predicate predicate = queryBuilder.equal(rootQuery.get(key), value);
                predicateList.add(predicate);
            }
        }
    }
    return predicateList;
}

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

public List<Product> search(String keyword, Boolean isGift, Integer count) {
    if (StringUtils.isEmpty(keyword)) {
        return Collections.<Product>emptyList();
    }//  w  w  w .jav a  2  s .c  om
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Product> criteriaQuery = criteriaBuilder.createQuery(Product.class);
    Root<Product> root = criteriaQuery.from(Product.class);
    criteriaQuery.select(root);
    Predicate restrictions = criteriaBuilder.conjunction();
    if (pattern.matcher(keyword).matches()) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.or(criteriaBuilder.equal(root.get("id"), Long.valueOf(keyword)),
                        criteriaBuilder.like(root.<String>get("sn"), "%" + keyword + "%"),
                        criteriaBuilder.like(root.<String>get("fullName"), "%" + keyword + "%")));
    } else {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.or(criteriaBuilder.like(root.<String>get("sn"), "%" + keyword + "%"),
                        criteriaBuilder.like(root.<String>get("fullName"), "%" + keyword + "%")));
    }
    if (isGift != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isGift"), isGift));
    }
    criteriaQuery.where(restrictions);
    criteriaQuery.orderBy(criteriaBuilder.desc(root.get("isTop")));
    return super.findList(criteriaQuery, null, count, null, null);
}

From source file:com.creditcloud.common.entities.dao.AbstractReadDAO.java

/**
 * list entity by CriteriaInfo/*from w  ww  . ja v a  2 s  . c o  m*/
 *
 * @param criteriaInfo
 * @return PagedResult
 */
public PagedResult<T> list(CriteriaInfo criteriaInfo) {
    EntityManager em = getEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery(entityClass);
    Root<T> userRoot = cq.from(entityClass);
    cq.select(userRoot);
    ParamInfo paramInfo = criteriaInfo.getParamInfo();
    PageInfo pageInfo = criteriaInfo.getPageInfo();
    SortInfo sortInfo = criteriaInfo.getSortInfo();

    //build query for paramInfo
    if (paramInfo != null) {
        Set<Predicate> andCriteria = new HashSet();
        Set<Predicate> orCriteria = new HashSet();

        for (ParamItem item : paramInfo.getParamItems()) {
            Predicate predicate;
            if (item.getValue() instanceof String) {
                //fuzy search for string
                String regExp = "%" + item.getValue() + "%";
                predicate = cb.like((Expression) (userRoot.get(item.getFieldName())), regExp);
            } else {
                predicate = cb.equal((userRoot.get(item.getFieldName())), item.getValue());
            }

            switch (item.getOperator()) {
            case AND:
                andCriteria.add(predicate);
                break;
            case OR:
                orCriteria.add(predicate);
                break;
            }
        }
        if (orCriteria.size() > 0) {
            Predicate or = cb.or(orCriteria.toArray(new Predicate[orCriteria.size()]));
            andCriteria.add(or);
        }
        if (andCriteria.size() > 0) {
            Predicate and = cb.and(andCriteria.toArray(new Predicate[andCriteria.size()]));
            cq.where(and);
        }
    }

    //build query for sortInfo
    Set<Order> orderPredicate = new HashSet<>();
    if (sortInfo != null) {
        for (SortItem item : sortInfo.getSortItems()) {
            if (item.isDescending()) {
                orderPredicate.add(cb.desc(userRoot.get(item.getFieldName())));
            } else {
                orderPredicate.add(cb.asc(userRoot.get(item.getFieldName())));
            }
        }
    }
    if (orderPredicate.size() > 0) {
        cq.orderBy(orderPredicate.toArray(new Order[orderPredicate.size()]));
    }

    TypedQuery<T> query = em.createQuery(cq);
    //set result range
    if (pageInfo != null) {
        query.setFirstResult(pageInfo.getOffset());
        query.setMaxResults(pageInfo.getSize());
    }

    int totalSize;
    if (paramInfo != null && paramInfo.getParamItems().size() > 0) {
        totalSize = count(paramInfo);
    } else {
        totalSize = count();
    }

    return new PagedResult(query.getResultList(), totalSize);
}