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:ch.puzzle.itc.mobiliar.business.resourcegroup.control.ResourceTypeDomainService.java

private Query applicationServersForSuggestBox(String input) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<String> q = cb.createQuery(String.class);
    Root<ResourceEntity> r = q.from(ResourceEntity.class);
    Join<ResourceEntity, ResourceTypeEntity> resType = r.join("resourceType");
    Predicate appServerNamePred = cb.like(resType.<String>get("name"),
            DefaultResourceTypeDefinition.APPLICATIONSERVER.name());
    input = input + "%";
    q.where(cb.and(appServerNamePred, cb.like(r.<String>get("name"), input)));
    q.select(r.<String>get("name"));
    q.distinct(true);//  ww w .  ja va  2  s. com

    q.orderBy(cb.asc(r.get("name")));

    return entityManager.createQuery(q);
}

From source file:com.carser.viamais.vo.TransactionFilter.java

private Predicate[] getPredicates(CriteriaBuilder cb, Root<Transaction> transaction) {
    List<Predicate> predicates = new ArrayList<>();
    if (StringUtils.hasLength(pattern)) {
        String[] words = pattern.split(" ");
        for (String word : words) {
            Predicate model = cb.like(transaction.get(Transaction_.car).get(Car_.model).get(Model_.name),
                    "%" + word + "%");
            Predicate customer = cb.like(transaction.get(Transaction_.customer).get(Customer_.name),
                    "%" + word + "%");
            predicates.add((cb.or(model, customer)));
        }//from   w w w .j  av  a 2 s.c o  m
    }
    if (StringUtils.hasLength(rg)) {
        predicates.add(cb.like(transaction.get(Transaction_.customer).get(Customer_.rg), "%" + rg + "%"));
    }
    if (StringUtils.hasLength(cpf)) {
        predicates.add(cb.like(transaction.get(Transaction_.customer).get(Customer_.cpf).as(String.class),
                "%" + cpf + "%"));
    }
    if (StringUtils.hasLength(renavam)) {
        predicates.add(cb.like(transaction.get(Transaction_.car).get(Car_.renavam), "%" + renavam + "%"));
    }
    if (StringUtils.hasLength(plate)) {
        predicates.add(cb.equal(transaction.get(Transaction_.car).get(Car_.licensePlate), plate));
    }
    if (StringUtils.hasLength(chassi)) {
        predicates.add(cb.like(transaction.get(Transaction_.car).get(Car_.chassi), "%" + chassi + "%"));
    }
    Expression<Date> date = cb.function("date", Date.class, transaction.get(Transaction_.transactionDate));
    if (startDate != null) {
        predicates.add(cb.greaterThanOrEqualTo(date, startDate));
    }
    if (finalDate != null) {
        predicates.add(cb.lessThanOrEqualTo(date, finalDate));
    }
    if (StringUtils.hasLength(type)) {
        switch (type) {
        case "sale":
            predicates.add(cb.equal(transaction.get(Transaction_.type), Sale.class.getSimpleName()));
            break;
        case "purchase":
            predicates.add(cb.equal(transaction.get(Transaction_.type), Purchase.class.getSimpleName()));
            break;
        default:
            throw new BusinessException("transaction type not supported");
        }
    }
    if (StringUtils.hasLength(advertiser)) {
        predicates.add(cb.equal(transaction.get(Transaction_.advertiser), advertiser));
    }
    if (StringUtils.hasLength(financial)) {
        predicates.add(cb.like(cb.treat(transaction, Sale.class).get(Sale_.financial), financial));
    }
    if (seller != null) {
        predicates.add(cb.equal(transaction.get(Transaction_.seller).get(Seller_.id), seller));
    }
    return (predicates.toArray(new Predicate[predicates.size()]));
}

From source file:br.com.sementesdoamanha.repository.Servidores.java

public List<Servidor> filtrados(ServidorFilter filtro) {
    //select, from, where, like... --> select(), from(), where()
    //JPQL: from Servidor

    //JPQL: select s from Servidor s where c.nome like = 'Joo%' and c.cpf = like '046.244.901-77'
    CriteriaBuilder builder = manager.getCriteriaBuilder();
    CriteriaQuery<Servidor> criteriaQuery = builder.createQuery(Servidor.class);
    Root<Servidor> s = criteriaQuery.from(Servidor.class);
    criteriaQuery.select(s);//from www. j  a  v a2  s.co  m

    List<Predicate> predicates = new ArrayList<>();

    if (StringUtils.isNotBlank(filtro.getCpf())) {
        predicates.add(builder.equal(s.<String>get("cpf"), filtro.getCpf()));
    }
    if (StringUtils.isNotBlank(filtro.getNome())) {
        predicates
                .add(builder.like(builder.upper(s.<String>get("nome")), filtro.getNome().toUpperCase() + "%"));

    }

    criteriaQuery.where(predicates.toArray(new Predicate[0]));
    TypedQuery<Servidor> query = manager.createQuery(criteriaQuery);
    return query.getResultList();

}

From source file:com.faceye.feature.repository.jpa.DynamicSpecifications.java

public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters,
        final Class<T> entityClazz) {
    return new Specification<T>() {
        @Override/*from   w  w w.j  a  va2  s. c  o  m*/
        public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
            if (CollectionUtils.isNotEmpty(filters)) {

                List<Predicate> predicates = Lists.newArrayList();
                for (SearchFilter filter : filters) {
                    // nested path translate, Task??"user.name"filedName, ?Task.user.name
                    String[] names = StringUtils.split(filter.fieldName, ".");
                    Path expression = root.get(names[0]);
                    for (int i = 1; i < names.length; i++) {
                        expression = expression.get(names[i]);
                    }

                    // logic operator
                    switch (filter.operator) {
                    case EQ:
                        if (filter.value instanceof Number) {
                            predicates.add(builder.equal(expression, (Number) filter.value));
                        } else if (filter.value instanceof String) {
                            if (StringUtils.isNotEmpty(filter.value.toString())) {
                                predicates.add(builder.equal(expression, filter.value));
                            }
                        } else {
                            predicates.add(builder.equal(expression, filter.value));
                        }
                        break;
                    case LIKE:
                        predicates.add(builder.like(expression, "%" + filter.value + "%"));
                        break;
                    case GT:
                        predicates.add(builder.greaterThan(expression, (Comparable) filter.value));
                        break;
                    case LT:
                        predicates.add(builder.lessThan(expression, (Comparable) filter.value));
                        break;
                    case GTE:
                        predicates.add(builder.greaterThanOrEqualTo(expression, (Comparable) filter.value));
                        break;
                    case LTE:
                        predicates.add(builder.lessThanOrEqualTo(expression, (Comparable) filter.value));
                        break;
                    case ISTRUE:
                        predicates.add(builder.isTrue(expression));
                        break;
                    case ISFALSE:
                        predicates.add(builder.isFalse(expression));
                        break;
                    case ISEMPTY:
                        predicates.add(builder.isEmpty(expression));
                        break;
                    case ISNULL:
                        predicates.add(builder.isNull(expression));
                        break;
                    case NE:
                        predicates.add(builder.notEqual(expression, filter.value));
                    }
                }

                // ? and ???
                if (!predicates.isEmpty()) {
                    return builder.and(predicates.toArray(new Predicate[predicates.size()]));
                }
            }

            return builder.conjunction();
        }
    };
}

From source file:org.verinice.persistence.VeriniceAccountDaoImpl.java

private TypedQuery<Entity> buildQueryForProperties(String loginName) {

    CriteriaBuilder builder = getCriteriaBuilder();

    CriteriaQuery<Entity> query = builder.createQuery(Entity.class);
    Root<Entity> entity = query.from(Entity.class);
    Join<PropertyList, Entity> propertyListJoin = entity.join("propertyLists");
    Join<PropertyList, Property> propertiesJoin = propertyListJoin.join("properties");
    List<Predicate> conditions = new ArrayList<>();
    Path<String> propertytypePath = propertiesJoin.get("propertytype");
    conditions.add(builder.like(propertytypePath, "configuration_benutzername"));
    Path<String> propertyvaluePath = propertiesJoin.get("propertyvalue");
    conditions.add(builder.like(propertyvaluePath, loginName));
    query.where(conditions.toArray(new Predicate[conditions.size()]));

    return entityManager.createQuery(query);
}

From source file:com.vladmihalcea.HibernateCriteriaTest.java

private List<Product> getProducts_Mercilessly() {
    return transactionTemplate.execute(new TransactionCallback<List<Product>>() {
        @Override/* w  ww  . j  av  a  2  s .c o  m*/
        public List<Product> doInTransaction(TransactionStatus transactionStatus) {
            CriteriaBuilder cb = entityManager.getCriteriaBuilder();
            CriteriaQuery<Product> query = cb.createQuery(Product.class);
            Root<Product> product = query.from(Product.class);
            query.select(product);
            query.distinct(true);

            List<Predicate> criteria = new ArrayList<Predicate>();
            criteria.add(cb.like(cb.lower(product.get(Product_.name)), "%tv%"));

            Subquery<Long> subQuery = query.subquery(Long.class);
            Root<Image> infoRoot = subQuery.from(Image.class);
            Join<Image, Product> productJoin = infoRoot.join(Image_.product);
            subQuery.select(productJoin.<Long>get(Product_.id));

            subQuery.where(cb.gt(infoRoot.get(Image_.index), 0));
            criteria.add(cb.in(product.get(Product_.id)).value(subQuery));
            query.where(cb.and(criteria.toArray(new Predicate[criteria.size()])));
            return entityManager.createQuery(query).getResultList();
        }
    });
}

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

/**
 * Adds the filter criteria.//  w ww.j av a2 s. c  o m
 *
 * @param filters the filters
 * @param builder the builder
 * @param root the root
 * @param query the query
 */

private void addFilterCriteria(Map<String, Object> filters, CriteriaBuilder builder, Root<CreditCard> root,
        CriteriaQuery query) {
    if (!filters.isEmpty()) {
        List<Predicate> predicates = new ArrayList<Predicate>();
        for (Entry<String, Object> entry : filters.entrySet()) {
            if (entry.getKey().equalsIgnoreCase(FIELDCONSTANT_CARDNUMBER)
                    || entry.getKey().equalsIgnoreCase(FIELDCONSTANT_CREDITLIMIT)
                    || entry.getKey().equalsIgnoreCase(FIELDCONSTANT_BALANCE)) {
                predicates.add(builder.like(root.<String>get(entry.getKey()), entry.getValue() + MODULO));
            }
        }
        query.where(predicates.toArray(new Predicate[] {}));
    }
}

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

/**
 * Adds the filter criteria./*from   www  .  j a va2 s. c o m*/
 *
 * @param filters the filters
 * @param builder the builder
 * @param root the root
 * @param query the query
 */
private void addFilterCriteria(Map<String, Object> filters, CriteriaBuilder builder, Root<User> root,
        CriteriaQuery query) {
    if (!filters.isEmpty()) {
        List<Predicate> predicates = new ArrayList<Predicate>();
        for (Entry<String, Object> entry : filters.entrySet()) {
            if (!entry.getKey().equalsIgnoreCase(FIELDCONSTANT_BALANCE)
                    && !entry.getKey().equalsIgnoreCase(FIELDCONSTANT_CARDNUMBER)
                    && !entry.getKey().equalsIgnoreCase(FIELDCONSTANT_CREDITLIMIT)) {
                predicates.add(builder.like(root.<String>get(entry.getKey()), entry.getValue() + MODULO));
            }
        }
        query.where(predicates.toArray(new Predicate[] {}));
    }
}

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

public List<User> getAllExceptAndFilter(Collection<User> usersToExclude, final String filter) {
    if (usersToExclude == null || usersToExclude.isEmpty()) {
        return this.getAll();
    }// w  w w  .j  a  va 2s . c  om
    logger.infof("loading all Users except %s ...", usersToExclude);
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<User> query = cb.createQuery(User.class);
    Root<User> root = query.from(User.class);
    if (filter != null && !filter.isEmpty()) {

        Expression<String> literal = cb.upper(cb.literal(LIKE_WILDCARD + filter + LIKE_WILDCARD));
        Predicate likeFirstName = cb.like(cb.upper(root.get(User_.firstName)), literal);
        Predicate likeLastName = cb.like(cb.upper(root.get(User_.lastName)), literal);
        Predicate likeUserName = cb.like(cb.upper(root.get(User_.userName)), literal);
        Predicate orLikeName = cb.or(likeFirstName, likeLastName, likeUserName);
        query.where(cb.and(cb.not(root.in(usersToExclude)), orLikeName));
    } else {
        query.where(cb.not(root.in(usersToExclude)));
    }
    return em.createQuery(query).getResultList();
}

From source file:eu.uqasar.service.ProductService.java

private List<Predicate> getFilterPredicates(final ProductFilterStructure filter, CriteriaBuilder cb,
        Root<Product> from) {/*  w w  w  . j ava  2  s . c  o  m*/
    List<Predicate> predicates = new ArrayList<>();
    if (filter == null) {
        return predicates;
    }

    if (filter.getReleaseDate() != null) {
        predicates.add(cb.equal(from.get(Product_.releaseDate), filter.getReleaseDate()));
    }
    if (filter.getVersion() != null) {
        predicates.add(cb.equal(from.get(Product_.version), filter.getVersion()));
    }

    if (!StringUtils.isEmpty(filter.getName())) {
        Predicate firstName = cb.like(cb.lower(from.get(Product_.name)),
                LIKE_WILDCARD + filter.getName().toLowerCase() + LIKE_WILDCARD);
        predicates.add(firstName);
    }
    return predicates;
}