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:org.niord.core.category.CategoryService.java

/**
 * Searches for categories matching the given term in the given language
 *
 * @param params the sesarch params/*ww  w .  ja v a  2 s . com*/
 * @return the search result
 */
@SuppressWarnings("all")
public List<Category> searchCategories(CategorySearchParams params) {

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Category> categoryQuery = cb.createQuery(Category.class);

    Root<Category> categoryRoot = categoryQuery.from(Category.class);

    // Build the predicate
    CriteriaHelper<Category> criteriaHelper = new CriteriaHelper<>(cb, categoryQuery);

    // Match the name
    Join<Category, CategoryDesc> descs = categoryRoot.join("descs", JoinType.LEFT);
    if (params.isExact()) {
        criteriaHelper.equalsIgnoreCase(descs.get("name"), params.getName());
    } else {
        criteriaHelper.like(descs.get("name"), params.getName());
    }

    // Optionally, match the language
    if (StringUtils.isNotBlank(params.getLanguage())) {
        criteriaHelper.equals(descs.get("lang"), params.getLanguage());
    }

    // Optionally, match the parent
    if (params.getParentId() != null) {
        categoryRoot.join("parent", JoinType.LEFT);
        Path<Category> parent = categoryRoot.get("parent");
        criteriaHelper.equals(parent.get("id"), params.getParentId());
    }

    // Optionally, filter by the domains associated with the current domain
    if (StringUtils.isNotBlank(params.getDomain())) {
        Domain d = domainService.findByDomainId(params.getDomain());
        if (d != null && d.getCategories().size() > 0) {
            Predicate[] categoryMatch = d.getCategories().stream()
                    .map(c -> cb.like(categoryRoot.get("lineage"), c.getLineage() + "%"))
                    .toArray(Predicate[]::new);
            criteriaHelper.add(cb.or(categoryMatch));
        }
    }

    // Unless the "inactive" search flag is set, only include active categories.
    if (!params.isInactive()) {
        criteriaHelper.add(cb.equal(categoryRoot.get("active"), true));
    }

    // Complete the query
    categoryQuery.select(categoryRoot).distinct(true).where(criteriaHelper.where());
    //.orderBy(cb.asc(cb.locate(cb.lower(descs.get("name")), name.toLowerCase())));

    // Execute the query and update the search result
    return em.createQuery(categoryQuery).setMaxResults(params.getMaxSize()).getResultList();
}

From source file:org.niord.core.message.MessageService.java

/**
 * Searches out the ID's of the paged result set of messages defined by the search parameters.
 * Also fills out the total result count of the message search result.
 *
 * @param param the search parameters/*from w ww .ja  v a  2 s . c o  m*/
 * @param result the search result to update with the total result count
 * @return the paged list of message ID's
 */
@SuppressWarnings("all")
List<Integer> searchPagedMessageIds(MessageSearchParams param, PagedSearchResultVo<Message> result)
        throws Exception {

    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Tuple> tupleQuery = builder.createTupleQuery();

    // Select messages
    Root<Message> msgRoot = tupleQuery.from(Message.class);

    // Build the predicates based on the search parameters
    CriteriaHelper<Tuple> criteriaHelper = CriteriaHelper.initWithTupleQuery(em).between(msgRoot.get("updated"),
            param.getUpdatedFrom(), param.getUpdatedTo());

    // Filter by dates
    if (param.getFrom() != null || param.getTo() != null) {
        DateType dateType = param.getDateType() != null ? param.getDateType() : DateType.PUBLISH_DATE;
        Date from = param.getFrom();
        Date to = param.getTo();
        switch (dateType) {
        case PUBLISH_DATE:
            criteriaHelper.overlaps(msgRoot.get("publishDateFrom"), msgRoot.get("publishDateTo"), from, to);
            break;
        case EVENT_DATE:
            criteriaHelper.overlaps(msgRoot.get("eventDateFrom"), msgRoot.get("eventDateTo"), from, to);
            break;
        case CREATED_DATE:
            criteriaHelper.between(msgRoot.get("created"), from, to);
            break;
        case UPDATED_DATE:
            criteriaHelper.between(msgRoot.get("updated"), from, to);
            break;
        case PUBLISH_FROM_DATE:
            criteriaHelper.between(msgRoot.get("publishDateFrom"), from, to);
            break;
        case PUBLISH_TO_DATE:
            criteriaHelper.between(msgRoot.get("publishDateTo"), from, to);
            break;
        }
    }

    // Main types and sub-types
    if (!param.getMainTypes().isEmpty()) {
        criteriaHelper.in(msgRoot.get("mainType"), param.getMainTypes());
    }
    if (!param.getTypes().isEmpty()) {
        criteriaHelper.in(msgRoot.get("type"), param.getTypes());
    }

    // Statuses
    if (!param.getStatuses().isEmpty()) {
        criteriaHelper.in(msgRoot.get("status"), param.getStatuses());
    }

    // Search the Lucene index for free text search
    if (param.requiresLuceneSearch()) {
        List<Long> ids = null;
        try {
            ids = messageLuceneIndex.searchIndex(param.getQuery(), param.getLanguage(), Integer.MAX_VALUE);
        } catch (Exception e) {
            log.warn("Error searching lucene index for query " + param.getQuery());
            ids = Collections.emptyList();
        }
        criteriaHelper.in(msgRoot.get("id"), ids);
    }

    // Message series
    if (!param.getSeriesIds().isEmpty()) {
        criteriaHelper.in(msgRoot.get("messageSeries").get("seriesId"), param.getSeriesIds());
    }

    // Filter by area, join over...
    if (!param.getAreaIds().isEmpty()) {
        Join<Message, Area> areas = msgRoot.join("areas", JoinType.LEFT);
        if (!param.getAreaIds().isEmpty()) {
            Predicate[] areaMatch = param.getAreaIds().stream().map(aid -> areaService.findByAreaId(aid))
                    .filter(Objects::nonNull).map(a -> builder.like(areas.get("lineage"), a.getLineage() + "%"))
                    .toArray(Predicate[]::new);
            criteriaHelper.add(builder.or(areaMatch));
        }
    }

    // Filter on categories
    if (!param.getCategoryIds().isEmpty()) {
        Join<Message, Category> categories = msgRoot.join("categories", JoinType.LEFT);
        Predicate[] categoryMatch = param.getCategoryIds().stream()
                .map(cid -> categoryService.findByCategoryId(cid)).filter(Objects::nonNull)
                .map(c -> builder.like(categories.get("lineage"), c.getLineage() + "%"))
                .toArray(Predicate[]::new);
        criteriaHelper.add(builder.or(categoryMatch));
    }

    // Filter on charts
    if (!param.getChartNumbers().isEmpty()) {
        Join<Message, Chart> charts = msgRoot.join("charts", JoinType.LEFT);
        Predicate[] chartMatch = param.getChartNumbers().stream()
                .map(m -> builder.equal(charts.get("chartNumber"), m)).toArray(Predicate[]::new);
        criteriaHelper.add(builder.or(chartMatch));
    }

    // Geometry
    if (param.getExtent() != null) {
        param.getExtent().setSRID(WGS84_SRID);
        Join<Message, MessagePart> partRoot = msgRoot.join("parts", JoinType.LEFT);
        Join<Message, FeatureCollection> fcRoot = partRoot.join("geometry", JoinType.LEFT);
        Join<FeatureCollection, Feature> fRoot = fcRoot.join("features", JoinType.LEFT);
        Predicate geomPredicate = new SpatialIntersectsPredicate(criteriaHelper.getCriteriaBuilder(),
                fRoot.get("geometry"), param.getExtent());

        if (param.getIncludeNoPos() != null && param.getIncludeNoPos().booleanValue()) {
            // search for message with no geometry in addition to messages within extent
            criteriaHelper.add(builder.or(builder.equal(msgRoot.get("hasGeometry"), false), geomPredicate));
        } else {
            // Only search for messages within extent
            criteriaHelper.add(geomPredicate);
        }
    }

    // Tags
    if (!param.getTags().isEmpty()) {
        Join<Message, MessageTag> tags = msgRoot.join("tags", JoinType.LEFT);
        String[] tagIds = param.getTags().toArray(new String[param.getTags().size()]);
        Predicate[] tagMatch = messageTagService.findTags(tagIds).stream()
                .map(t -> builder.equal(tags.get("id"), t.getId())).toArray(Predicate[]::new);
        criteriaHelper.add(builder.or(tagMatch));
    }

    // User
    if (StringUtils.isNotBlank(param.getUsername())) {
        UserType userType = param.getUserType() == null ? UserType.UPDATED_BY : param.getUserType();
        if (userType == UserType.CREATED_BY || userType == UserType.LAST_UPDATED_BY) {
            String joinCol = userType == UserType.CREATED_BY ? "createdBy" : "lastUpdatedBy";
            Join<Message, User> userRoot = msgRoot.join(joinCol, JoinType.LEFT);
            criteriaHelper.equals(userRoot.get("username"), param.getUsername());
        } else {
            Join<Message, MessageHistory> historyRoot = msgRoot.join("history", JoinType.LEFT);
            Join<MessageHistory, User> userRoot = historyRoot.join("user", JoinType.LEFT);
            criteriaHelper.equals(userRoot.get("username"), param.getUsername());
        }
    }

    // Comments
    if (param.getCommentsType() != null) {
        Join<Message, Comment> comments = msgRoot.join("comments", JoinType.LEFT);
        User user = userService.currentUser();
        Predicate own = user != null ? builder.equal(comments.get("user"), user) : null;
        Predicate exists = builder.isNotNull(comments.get("id"));
        Predicate unack = builder.isNull(comments.get("acknowledgedBy"));

        if (user != null && param.getCommentsType() == OWN) {
            criteriaHelper.add(own);
        } else if (user != null && param.getCommentsType() == OWN_UNACK) {
            criteriaHelper.add(builder.and(own, unack));
        } else if (param.getCommentsType() == ANY_UNACK) {
            criteriaHelper.add(builder.and(exists, unack));
        } else if (param.getCommentsType() == ANY) {
            criteriaHelper.add(exists);
        }
    }

    // Refenced messages
    if (StringUtils.isNotBlank(param.getMessageId())) {
        int levels = param.getReferenceLevels() == null ? 1 : param.getReferenceLevels();
        // NB: This is expensive queries - limit the levels
        levels = Math.max(0, Math.min(5, levels));
        // First, find messages referenced by the message ID
        Set<Integer> referencedIds = findReferencedMessageIds(new HashSet<>(), param.getMessageId(), levels);
        // Next, add messages referencing the message ID
        findReferencingMessageIds(referencedIds, param.getMessageId(), levels);
        criteriaHelper.in(msgRoot.get("id"), referencedIds);
    }

    // Determine the fields to fetch
    Join<Message, Area> areaRoot = null;
    Expression<?> treeSortOrder = null;
    List<Selection<?>> fields = new ArrayList<>();
    fields.add(msgRoot.get("id"));
    if (param.sortByEventDate()) {
        fields.add(msgRoot.get("eventDateFrom"));
        fields.add(msgRoot.get("eventDateTo"));
    } else if (param.sortByPublishDate()) {
        fields.add(msgRoot.get("publishDateFrom"));
        fields.add(msgRoot.get("publishDateTo"));
    } else if (param.sortByFollowUpDate()) {
        fields.add(msgRoot.get("followUpDate"));
    } else if (param.sortById()) {
        fields.add(msgRoot.get("year"));
        fields.add(msgRoot.get("number"));
        fields.add(msgRoot.get("publishDateFrom"));
    } else if (param.sortByArea()) {
        areaRoot = msgRoot.join("area", JoinType.LEFT);
        // General messages (without an associated area) should be sorted last
        treeSortOrder = builder.selectCase().when(builder.isNull(areaRoot.get("treeSortOrder")), 999999)
                .otherwise(areaRoot.get("treeSortOrder"));
        fields.add(treeSortOrder);
        fields.add(msgRoot.get("areaSortOrder"));
        fields.add(msgRoot.get("year"));
        fields.add(msgRoot.get("number"));
    }
    Selection[] f = fields.toArray(new Selection<?>[fields.size()]);

    // Complete the query and fetch the message id's (and fields used for sorting)
    tupleQuery.multiselect(f).distinct(true).where(criteriaHelper.where());

    // Sort the query
    if (param.sortByEventDate()) {
        if (param.getSortOrder() == SortOrder.ASC) {
            tupleQuery.orderBy(builder.asc(msgRoot.get("eventDateFrom")),
                    builder.asc(msgRoot.get("eventDateTo")), builder.asc(msgRoot.get("id")));
        } else {
            tupleQuery.orderBy(builder.desc(msgRoot.get("eventDateFrom")),
                    builder.desc(msgRoot.get("eventDateTo")), builder.desc(msgRoot.get("id")));
        }
    } else if (param.sortByPublishDate()) {
        if (param.getSortOrder() == SortOrder.ASC) {
            tupleQuery.orderBy(builder.asc(msgRoot.get("publishDateFrom")),
                    builder.asc(msgRoot.get("publishDateTo")), builder.asc(msgRoot.get("id")));
        } else {
            tupleQuery.orderBy(builder.desc(msgRoot.get("publishDateFrom")),
                    builder.desc(msgRoot.get("publishDateTo")), builder.desc(msgRoot.get("id")));
        }
    } else if (param.sortByFollowUpDate()) {
        if (param.getSortOrder() == SortOrder.ASC) {
            tupleQuery.orderBy(builder.asc(msgRoot.get("followUpDate")), builder.asc(msgRoot.get("id")));
        } else {
            tupleQuery.orderBy(builder.desc(msgRoot.get("followUpDate")), builder.desc(msgRoot.get("id")));
        }
    } else if (param.sortById()) {
        if (param.getSortOrder() == SortOrder.ASC) {
            tupleQuery.orderBy(builder.asc(msgRoot.get("year")), builder.asc(msgRoot.get("number")),
                    builder.asc(msgRoot.get("publishDateFrom")), builder.asc(msgRoot.get("id")));
        } else {
            tupleQuery.orderBy(builder.desc(msgRoot.get("year")), builder.desc(msgRoot.get("number")),
                    builder.desc(msgRoot.get("publishDateFrom")), builder.desc(msgRoot.get("id")));
        }
    } else if (param.sortByArea()) {
        if (param.getSortOrder() == SortOrder.ASC) {
            tupleQuery.orderBy(builder.asc(treeSortOrder), builder.asc(msgRoot.get("areaSortOrder")),
                    builder.asc(msgRoot.get("year")), builder.asc(msgRoot.get("number")),
                    builder.asc(msgRoot.get("id")));
        } else {
            tupleQuery.orderBy(builder.desc(treeSortOrder), builder.desc(msgRoot.get("areaSortOrder")),
                    builder.desc(msgRoot.get("year")), builder.desc(msgRoot.get("number")),
                    builder.desc(msgRoot.get("id")));
        }
    }

    // Execute the query
    List<Tuple> totalResult = em.createQuery(tupleQuery).getResultList();

    // Register the total result
    result.setTotal(totalResult.size());

    List<Integer> msgIds = totalResult.stream().map(t -> (Integer) t.get(0)).collect(Collectors.toList());

    // Extract and return the paged sub-list
    int startIndex = Math.min(msgIds.size(), param.getPage() * param.getMaxSize());
    int endIndex = Math.min(msgIds.size(), startIndex + param.getMaxSize());
    return msgIds.subList(startIndex, endIndex);
}

From source file:org.opencastproject.messages.MailService.java

public List<MessageTemplate> findMessageTemplates(TemplateMessageQuery query) {
    EntityManager em = null;//  w ww.  j a  v  a  2 s .c o m
    List<MessageTemplate> messageTemplates = new ArrayList<MessageTemplate>();

    try {
        em = emf.createEntityManager();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<MessageTemplateDto> q = cb.createQuery(MessageTemplateDto.class);
        Root<MessageTemplateDto> messageTemplateRoot = q.from(MessageTemplateDto.class);

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

        q.select(messageTemplateRoot);

        String orgId = securityService.getOrganization().getId();
        predicates.add(cb.equal(messageTemplateRoot.get("organization"), orgId));

        if (!query.isIncludeHidden())
            predicates.add(cb.isFalse(messageTemplateRoot.get("hidden").as(Boolean.class)));

        if (StringUtils.isNotEmpty(query.getName()))
            predicates.add(cb.equal(messageTemplateRoot.get("name"), query.getName()));

        if (StringUtils.isNotEmpty(query.getCreator()))
            predicates.add(cb.equal(messageTemplateRoot.get("creator"), query.getCreator()));

        if (query.getType() != null)
            predicates.add(
                    cb.equal(messageTemplateRoot.get("type").as(TemplateType.Type.class), query.getType()));

        if (StringUtils.isNotEmpty(query.getFullText())) {
            List<Predicate> fullTextPredicates = new ArrayList<Predicate>();
            fullTextPredicates
                    .add(cb.like(messageTemplateRoot.<String>get("name"), "%" + query.getFullText() + "%"));
            fullTextPredicates
                    .add(cb.like(messageTemplateRoot.<String>get("subject"), "%" + query.getFullText() + "%"));
            fullTextPredicates
                    .add(cb.like(messageTemplateRoot.<String>get("body"), "%" + query.getFullText() + "%"));
            predicates.add(cb.or(fullTextPredicates.toArray(new Predicate[fullTextPredicates.size()])));
        }

        q.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));

        TypedQuery<MessageTemplateDto> typedQuery = em.createQuery(q);
        List<MessageTemplateDto> messageTemplatesDto = typedQuery.getResultList();

        for (MessageTemplateDto mt : messageTemplatesDto) {
            messageTemplates.add(mt.toMessageTemplate(userDirectoryService));
        }

        return messageTemplates;
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.seedstack.i18n.rest.internal.KeyJpaFinder.java

/**
 * Extracts predicates from criteria.//  w ww .j a v  a 2 s  .  c  om
 *
 * @param criteria criteria
 * @param cb       criteria builder
 * @param k        root key
 * @return list of predicate
 */
private Predicate[] getPredicates(Map<String, Object> criteria, CriteriaQuery q, CriteriaBuilder cb,
        Root<Key> k) {
    List<Predicate> predicates = new ArrayList<Predicate>();
    if (criteria != null) {
        // extract criteria from the map
        Boolean isApprox = (Boolean) criteria.get(IS_APPROX);
        Boolean isMissing = (Boolean) criteria.get(IS_MISSING);
        Boolean isOutdated = (Boolean) criteria.get(IS_OUTDATED);
        String searchName = (String) criteria.get(SEARCH_NAME);

        // is the key LIKE searchName
        if (StringUtils.isNotBlank(searchName)) {
            predicates.add(cb.like(k.<String>get(ENTITY_ID), "%" + searchName + "%"));
        }
        // is the key outdated
        if (isOutdated != null) {
            predicates.add(cb.equal(k.<Boolean>get(OUTDATED), isOutdated));
        }

        // if a default translation is available
        String defaultLocale = localeService.getDefaultLocale();
        if (defaultLocale != null && isApprox != null) {
            // join translation table
            Join<Key, Translation> tln = k.join(TRANSLATIONS, JoinType.LEFT);
            // WHERE locale = default locale
            predicates.add(cb.equal(tln.get(ENTITY_ID).get(LOCALE), defaultLocale));

            // is the translation approximate
            predicates.add(cb.equal(tln.get(APPROXIMATE), isApprox));
        }

        // is the translation missing
        if (isMissing != null) {
            // SubQuery to find all the key which get a translation for the default locale
            //noinspection unchecked
            Subquery<String> subquery = q.subquery(String.class);
            Root<Key> fromKey = subquery.from(Key.class);
            subquery.select(fromKey.<String>get(ENTITY_ID));
            Join join = fromKey.join(TRANSLATIONS, JoinType.LEFT);
            subquery.where(cb.and(cb.equal(join.get(ENTITY_ID).get(LOCALE), defaultLocale),
                    cb.notEqual(join.get(VALUE), "")));
            // Find all keys not in the above subquery, ie. all the keys missing
            predicates.add(cb.not(cb.in(k.get(ENTITY_ID)).value(subquery)));
        }
    }
    return predicates.toArray(new Predicate[predicates.size()]);
}

From source file:org.seedstack.i18n.rest.internal.TranslationJpaFinder.java

/**
 * Extracts predicates from criteria./*w w w  .jav a  2s  .  co m*/
 *
 * @param criteria criteria
 * @param cb       criteria builder
 * @param k        root key
 * @return list of predicate
 */
private Predicate[] getPredicates(Map<String, Object> criteria, CriteriaQuery q, CriteriaBuilder cb,
        Root<Key> k) {
    List<Predicate> predicates = new ArrayList<Predicate>();
    if (criteria != null) {
        // extract criteria from the map
        Boolean isApprox = (Boolean) criteria.get(IS_APPROX);
        Boolean isMissing = (Boolean) criteria.get(IS_MISSING);
        Boolean isOutdated = (Boolean) criteria.get(IS_OUTDATED);
        String searchName = (String) criteria.get(SEARCH_NAME);
        String locale = (String) criteria.get(LOCALE);

        // is the key LIKE searchName
        if (StringUtils.isNotBlank(searchName)) {
            predicates.add(cb.like(k.<String>get(ENTITY_ID), "%" + searchName + "%"));
        }

        // if a default translation is available
        if (isApprox != null || isOutdated != null) {
            // join translation table
            Join<Key, Translation> tln = k.join(TRANSLATIONS, JoinType.LEFT);
            // WHERE locale = default locale
            predicates.add(cb.equal(tln.get(ENTITY_ID).get(LOCALE), locale));

            // is the key outdated
            if (isOutdated != null) {
                predicates.add(cb.equal(tln.<Boolean>get(OUTDATED), isOutdated));
            }

            // is the translation approximate
            if (isApprox != null) {
                predicates.add(cb.equal(tln.<Boolean>get(APPROXIMATE), isApprox));
            }
        }
        // is the translation missing
        if (isMissing != null) {
            // SubQuery to find all the key which get a translation for the default locale
            //noinspection unchecked
            Subquery<String> subquery = q.subquery(String.class);
            Root<Key> fromKey = subquery.from(Key.class);
            subquery.select(fromKey.<String>get(ENTITY_ID));
            Join join = fromKey.join(TRANSLATIONS, JoinType.LEFT);
            subquery.where(cb.and(cb.equal(join.get(ENTITY_ID).get(LOCALE), locale),
                    cb.notEqual(join.get(VALUE), "")));
            // Find all keys not in the above subquery, ie. all the keys missing
            predicates.add(cb.not(cb.in(k.get(ENTITY_ID)).value(subquery)));
        }
    }
    return predicates.toArray(new Predicate[predicates.size()]);
}

From source file:org.sparkcommerce.core.catalog.dao.ProductDaoImpl.java

protected List<Product> readFilteredActiveProductsByQueryInternal(String query, Date currentDate,
        ProductSearchCriteria searchCriteria) {
    // Set up the criteria query that specifies we want to return Products
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Product> criteria = builder.createQuery(Product.class);

    // The root of our search is Product since we are searching
    Root<ProductImpl> product = criteria.from(ProductImpl.class);

    // We also want to filter on attributes from sku and productAttributes
    Join<Product, Sku> sku = product.join("defaultSku");

    // Product objects are what we want back
    criteria.select(product);//w  w  w  . j  a v  a  2 s  .c  o m

    // We only want results that match the search query
    List<Predicate> restrictions = new ArrayList<Predicate>();
    String lq = query.toLowerCase();
    restrictions.add(builder.or(builder.like(builder.lower(sku.get("name").as(String.class)), '%' + lq + '%'),
            builder.like(builder.lower(sku.get("longDescription").as(String.class)), '%' + lq + '%')));

    attachProductSearchCriteria(searchCriteria, product, sku, restrictions);

    attachActiveRestriction(currentDate, product, sku, restrictions);

    attachOrderBy(searchCriteria, product, sku, criteria);

    // Execute the query with the restrictions
    criteria.where(restrictions.toArray(new Predicate[restrictions.size()]));

    TypedQuery<Product> typedQuery = em.createQuery(criteria);
    //don't cache - not really practical for open ended search

    return typedQuery.getResultList();
}

From source file:org.xiaoqiaotq.util.persistence.DynamicSpecifications.java

public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters,
        final Class<T> entityClazz) {
    return new Specification<T>() {
        @Override//from   ww  w  .ja va  2 s  .com
        public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
            if ((filters != null) && !(filters.isEmpty())) {

                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:
                        predicates.add(builder.equal(expression, filter.value));
                        break;
                    case NEQ:
                        predicates.add(builder.notEqual(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;
                    }
                }

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

            return builder.conjunction();
        }
    };
}

From source file:yoyo.actor.service.domain.misc.NewsRepositoryImpl.java

/**
 * {@inheritDoc}/*from  www . j a  va2s . co m*/
 * <dl>
 * <dt>??</dt>
 * <dd>??NULL????</dd>
 * <dt>?</dt>
 * <dd>?????????</dd>
 * </dl>
 */
@Override
protected Predicate expression(final SimpleFilter filter) {
    assert filter != null;
    if (StringUtils.isEmpty(filter.getKeyword())) {
        return super.expression(filter);
    }
    final CriteriaBuilder b = service.builder();
    final Root<News> r = service.root();
    return b.or(b.like(r.get(title), wrapWildcard(filter.getKeyword())),
            b.like(r.get(description), wrapWildcard(filter.getKeyword())),
            b.like(r.get(category), wrapWildcard(filter.getKeyword())));
}