Example usage for javax.persistence.criteria CriteriaBuilder selectCase

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

Introduction

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

Prototype

<R> Case<R> selectCase();

Source Link

Document

Create a general case expression.

Usage

From source file:bq.jpa.demo.query.criteria.service.CriteriaService.java

/**
 * NOTE : Hibernate cannot support case in criteria way
 * //w  ww . ja v  a  2s . c o  m
 * case 1:
 * SELECT p.name, 
 *          CASE WHEN TYPE(p)=bq.jpa.demo.query.domain.DesignProject  THEN 'dev' 
 *              WHEN TYPE(p)=bq.jpa.demo.query.domain.QualityProject THEN 'QA' 
 *              ELSE 'unknown' 
 *          END 
 * FROM jpa_query_project p
 * 
 * case 2:
 * SELECT p.name, 
 *          CASE TYPE(p)
 *              WHEN bq.jpa.demo.query.domain.DesignProject  THEN 'dev' 
 *              WHEN bq.jpa.demo.query.domain.QualityProject THEN 'QA' 
 *              ELSE 'unknown' 
 *          END 
 * FROM jpa_query_project p
 */
@Transactional
public void doWhere4() {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Object[]> c = cb.createQuery(Object[].class);
    Root<Project> p = c.from(Project.class);

    // method 1
    c.multiselect(p.get("name"), cb.selectCase().when(cb.equal(p.type(), DesignProject.class), "dev")
            .when(cb.equal(p.type(), QualityProject.class), "QA").otherwise("unknown"));

    //      showResult(c);

    // method 2:
    CriteriaQuery<Object[]> c2 = cb.createQuery(Object[].class);
    Root<Project> p2 = c2.from(Project.class);
    c2.multiselect(p2.get("name"), cb.selectCase(p2.type()).when(DesignProject.class, "dev")
            .when(QualityProject.class, "QA").otherwise("unknown"));
    //      showResult(c2);
}

From source file:org.eclipse.hawkbit.repository.jpa.JpaTargetManagement.java

@Override
public Slice<Target> findTargetsAllOrderByLinkedDistributionSet(final Pageable pageable,
        final Long orderByDistributionId, final FilterParams filterParams) {
    final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    final CriteriaQuery<JpaTarget> query = cb.createQuery(JpaTarget.class);
    final Root<JpaTarget> targetRoot = query.from(JpaTarget.class);

    // select case expression to retrieve the case value as a column to be
    // able to order based on
    // this column, installed first,...
    final Expression<Object> selectCase = cb.selectCase()
            .when(cb.equal(targetRoot.get(JpaTarget_.installedDistributionSet).get(JpaDistributionSet_.id),
                    orderByDistributionId), 1)
            .when(cb.equal(targetRoot.get(JpaTarget_.assignedDistributionSet).get(JpaDistributionSet_.id),
                    orderByDistributionId), 2)
            .otherwise(100);/* w w w .  j a  v a2s.  c om*/
    // multiselect statement order by the select case and controllerId
    query.distinct(true);
    // build the specifications and then to predicates necessary by the
    // given filters
    final Predicate[] specificationsForMultiSelect = specificationsToPredicate(
            buildSpecificationList(filterParams), targetRoot, query, cb);

    // if we have some predicates then add it to the where clause of the
    // multiselect
    if (specificationsForMultiSelect.length > 0) {
        query.where(specificationsForMultiSelect);
    }
    // add the order to the multi select first based on the selectCase
    query.orderBy(cb.asc(selectCase), cb.desc(targetRoot.get(JpaTarget_.id)));
    // the result is a Object[] due the fact that the selectCase is an extra
    // column, so it cannot
    // be mapped directly to a Target entity because the selectCase is not a
    // attribute of the
    // Target entity, the the Object array contains the Target on the first
    // index (case of the
    // multiselect order) of the array and
    // the 2nd contains the selectCase int value.
    final int pageSize = pageable.getPageSize();
    final List<JpaTarget> resultList = entityManager.createQuery(query).setFirstResult(pageable.getOffset())
            .setMaxResults(pageSize + 1).getResultList();
    final boolean hasNext = resultList.size() > pageSize;
    return new SliceImpl<>(Collections.unmodifiableList(resultList), pageable, hasNext);
}

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 w w. ja  v  a2s  .  com*/
 * @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);
}