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.finra.herd.dao.impl.StorageFileDaoImpl.java

@Override
public Long getStorageFileCount(String storageName, String filePathPrefix) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Long> criteria = builder.createQuery(Long.class);

    // The criteria root is the storage files.
    Root<StorageFileEntity> storageFileEntity = criteria.from(StorageFileEntity.class);

    // Join to the other tables we can filter on.
    Join<StorageFileEntity, StorageUnitEntity> storageUnitEntity = storageFileEntity
            .join(StorageFileEntity_.storageUnit);
    Join<StorageUnitEntity, StorageEntity> storageEntity = storageUnitEntity.join(StorageUnitEntity_.storage);

    // Create path.
    Expression<Long> storageFileCount = builder.count(storageFileEntity.get(StorageFileEntity_.id));

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate storageNameRestriction = builder.equal(builder.upper(storageEntity.get(StorageEntity_.name)),
            storageName.toUpperCase());/*  w  w w  .  ja v a 2  s  . co  m*/
    Predicate filePathRestriction = builder.like(storageFileEntity.get(StorageFileEntity_.path),
            String.format("%s%%", filePathPrefix));

    // Add the clauses for the query.
    criteria.select(storageFileCount).where(builder.and(storageNameRestriction, filePathRestriction));

    return entityManager.createQuery(criteria).getSingleResult();
}

From source file:org.finra.herd.dao.impl.StorageFileDaoImpl.java

@Override
public List<String> getStorageFilesByStorageAndFilePathPrefix(String storageName, String filePathPrefix) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<StorageFileEntity> criteria = builder.createQuery(StorageFileEntity.class);

    // The criteria root is the storage files.
    Root<StorageFileEntity> storageFileEntity = criteria.from(StorageFileEntity.class);

    // Join to the other tables we can filter on.
    Join<StorageFileEntity, StorageUnitEntity> storageUnitEntity = storageFileEntity
            .join(StorageFileEntity_.storageUnit);
    Join<StorageUnitEntity, StorageEntity> storageEntity = storageUnitEntity.join(StorageUnitEntity_.storage);

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate filePathRestriction = builder.like(storageFileEntity.get(StorageFileEntity_.path),
            String.format("%s%%", filePathPrefix));
    Predicate storageNameRestriction = builder.equal(builder.upper(storageEntity.get(StorageEntity_.name)),
            storageName.toUpperCase());/*from  w w w .  ja v  a2  s .c o  m*/

    // Order the results by file path.
    Order orderByFilePath = builder.asc(storageFileEntity.get(StorageFileEntity_.path));

    criteria.select(storageFileEntity).where(builder.and(filePathRestriction, storageNameRestriction))
            .orderBy(orderByFilePath);

    // Retrieve the storage files.
    List<StorageFileEntity> storageFileEntities = entityManager.createQuery(criteria).getResultList();

    // Build the result list.
    List<String> storageFilePaths = new ArrayList<>();
    for (StorageFileEntity storageFile : storageFileEntities) {
        storageFilePaths.add(storageFile.getPath());
    }

    return storageFilePaths;
}

From source file:org.jboss.pnc.datastore.predicates.rsql.RSQLNodeTravellerPredicate.java

public RSQLNodeTravellerPredicate(Class<Entity> entityClass, String rsql) throws RSQLParserException {
    operations.put(RSQLOperators.EQUAL, new AbstractTransformer<Entity>() {
        @Override//from  ww  w .  j av  a  2  s  .c o m
        Predicate transform(Root<Entity> r, Path<?> selectedPath, CriteriaBuilder cb, String operand,
                List<Object> convertedArguments) {
            return cb.equal(selectedPath, convertedArguments.get(0));
        }
    });

    operations.put(RSQLOperators.NOT_EQUAL, new AbstractTransformer<Entity>() {
        @Override
        Predicate transform(Root<Entity> r, Path<?> selectedPath, CriteriaBuilder cb, String operand,
                List<Object> convertedArguments) {
            return cb.notEqual(selectedPath, convertedArguments.get(0));
        }
    });

    operations.put(RSQLOperators.GREATER_THAN, (r, cb, clazz, operand, arguments) -> cb
            .greaterThan((Path) selectWithOperand(r, operand, clazz), arguments.get(0)));
    operations.put(RSQLOperators.GREATER_THAN_OR_EQUAL, (r, cb, clazz, operand, arguments) -> cb
            .greaterThanOrEqualTo((Path) selectWithOperand(r, operand, clazz), arguments.get(0)));
    operations.put(RSQLOperators.LESS_THAN, (r, cb, clazz, operand, arguments) -> cb
            .lessThan((Path) selectWithOperand(r, operand, clazz), arguments.get(0)));
    operations.put(RSQLOperators.LESS_THAN_OR_EQUAL, (r, cb, clazz, operand, arguments) -> cb
            .lessThanOrEqualTo((Path) selectWithOperand(r, operand, clazz), arguments.get(0)));
    operations.put(RSQLOperators.IN,
            (r, cb, clazz, operand, arguments) -> ((Path) selectWithOperand(r, operand, clazz)).in(arguments));
    operations.put(RSQLOperators.NOT_IN, (r, cb, clazz, operand, arguments) -> cb
            .not(((Path) selectWithOperand(r, operand, clazz)).in(arguments)));
    operations.put(LIKE,
            (r, cb, clazz, operand, arguments) -> cb.like(cb.lower((Path) selectWithOperand(r, operand, clazz)),
                    preprocessLikeOperatorArgument(arguments.get(0).toLowerCase())));
    operations.put(IS_NULL, (r, cb, clazz, operand, arguments) -> {
        if (Boolean.parseBoolean(arguments.get(0))) {
            return cb.isNull((Path) selectWithOperand(r, operand, clazz));
        } else {
            return cb.isNotNull((Path) selectWithOperand(r, operand, clazz));
        }
    });

    Set<ComparisonOperator> operators = RSQLOperators.defaultOperators();
    operators.add(LIKE);
    operators.add(IS_NULL);

    rootNode = new RSQLParser(operators).parse(preprocessRSQL(rsql));
    selectingClass = entityClass;
}

From source file:org.kisoonlineapp.uc.teilnehmer.SearchPredicatesForTeilnehmerFilterForm.java

List<Predicate> createSearchPredicates(TeilnehmerFilterForm teilnehmerFilterForm, Root<Teilnehmer> root) {

    final Teilnehmer example = teilnehmerFilterForm.getExample();

    final CriteriaBuilder builder = this.entityManager.getCriteriaBuilder();
    final List<Predicate> predicatesList = new ArrayList<>();

    {/*w w  w .  ja v  a2  s  . c o m*/
        final String vorname = example.getVorname();
        if (isNotEmpty(vorname)) {
            predicatesList
                    .add(builder.like(builder.lower(root.<String>get("vorname")), lowerWildcards(vorname)));
        }
    }
    {
        final String nachname = example.getNachname();
        if (isNotEmpty(nachname)) {
            predicatesList
                    .add(builder.like(builder.lower(root.<String>get("nachname")), lowerWildcards(nachname)));
        }
    }
    {
        final String email = example.getEmail();
        if (isNotEmpty(email)) {
            predicatesList.add(builder.like(builder.lower(root.<String>get("email")), lowerWildcards(email)));
        }
    }
    {
        final String telefon = example.getTelefon();
        if (isNotEmpty(telefon)) {
            predicatesList
                    .add(builder.like(builder.lower(root.<String>get("telefon")), lowerWildcards(telefon)));
        }
    }

    return Collections.unmodifiableList(predicatesList);
}

From source file:org.kisoonlineapp.uc.veranstalter.SearchPredicatesForVeranstalterFilterForm.java

List<Predicate> createSearchPredicates(VeranstalterFilterForm veranstalterFilterForm, Root<Veranstalter> root) {

    Veranstalter example = veranstalterFilterForm.getExample();

    CriteriaBuilder builder = this.entityManager.getCriteriaBuilder();
    List<Predicate> predicatesList = new ArrayList<Predicate>();

    {/*from   ww w  .j  ava 2s.c  o m*/
        final String code = example.getCode();
        if (isNotEmpty(code)) {
            predicatesList.add(builder.like(builder.lower(root.<String>get("code")), lowerWildcards(code)));
        }
    }
    {
        final String vorname = example.getVorname();
        if (isNotEmpty(vorname)) {
            predicatesList
                    .add(builder.like(builder.lower(root.<String>get("vorname")), lowerWildcards(vorname)));
        }
    }
    {
        final String nachname = example.getNachname();
        if (isNotEmpty(nachname)) {
            predicatesList
                    .add(builder.like(builder.lower(root.<String>get("nachname")), lowerWildcards(nachname)));
        }
    }
    {
        final String organisation = example.getOrganisation();
        if (isNotEmpty(organisation)) {
            predicatesList.add(builder.like(builder.lower(root.<String>get("organisation")),
                    lowerWildcards(organisation)));
        }
    }
    {
        final String beschreibung = example.getBeschreibung();
        if (isNotEmpty(beschreibung)) {
            predicatesList.add(builder.like(builder.lower(root.<String>get("beschreibung")),
                    lowerWildcards(beschreibung)));
        }
    }

    return Collections.unmodifiableList(predicatesList);
}

From source file:org.kisoonlineapp.uc.veranstaltung.SearchPredicatesForVeranstaltungFilterForm.java

List<Predicate> createSearchPredicates(VeranstaltungFilterForm veranstaltungFilterForm,
        Root<Veranstaltung> root) {

    Veranstaltung example = veranstaltungFilterForm.getExample();

    CriteriaBuilder builder = this.entityManager.getCriteriaBuilder();
    List<Predicate> predicatesList = new ArrayList<Predicate>();

    {// w w  w . ja  v a2 s. c om
        final String code = example.getCode();
        if (isNotEmpty(code)) {
            predicatesList.add(builder.like(builder.lower(root.<String>get("code")), lowerWildcards(code)));
        }
    }
    {
        final String name = example.getName();
        if (isNotEmpty(name)) {
            predicatesList.add(builder.like(builder.lower(root.<String>get("name")), lowerWildcards(name)));
        }
    }
    {
        final Veranstalter veranstalter = example.getVeranstalter();
        if (veranstalter != null) {
            predicatesList.add(builder.equal(root.get("veranstalter"), veranstalter));
        }
    }
    {
        final String beschreibung = example.getBeschreibung();
        if (isNotEmpty(beschreibung)) {
            predicatesList.add(builder.like(builder.lower(root.<String>get("beschreibung")),
                    lowerWildcards(beschreibung)));
        }
    }
    {
        final Gemeinde gemeinde = example.getGemeinde();
        if (gemeinde != null) {
            final Path<Gemeinde> gemeindePath = root.<Gemeinde>get("gemeinde");
            {
                {
                    final String gemeindeName = gemeinde.getName();
                    if (isNotEmpty(gemeindeName)) {
                        predicatesList.add(builder.like(builder.lower(gemeindePath.<String>get("name")),
                                lowerWildcards(gemeindeName)));
                    }
                }
                {
                    final String gemeindePlz = gemeinde.getPlz();
                    if (isNotEmpty(gemeindePlz)) {
                        predicatesList.add(builder.like(builder.lower(gemeindePath.<String>get("plz")),
                                lowerWildcards(gemeindePlz)));
                    }
                }
            }
        }
    }

    return Collections.unmodifiableList(predicatesList);
}

From source file:org.kuali.rice.kew.rule.dao.impl.RuleDAOJpa.java

private Subquery<RuleResponsibilityBo> addResponsibilityCriteria(CriteriaQuery<RuleBaseValues> query,
        Collection<String> workgroupIds, String workflowId, Collection actionRequestCodes, Boolean searchUser,
        Boolean searchUserInWorkgroups) {

    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    Subquery<RuleResponsibilityBo> subquery = query.subquery(RuleResponsibilityBo.class);
    Root fromResp = subquery.from(RuleResponsibilityBo.class);

    List<javax.persistence.criteria.Predicate> respPredicates = new ArrayList<javax.persistence.criteria.Predicate>();

    List<javax.persistence.criteria.Predicate> ruleRespNamePredicates = new ArrayList<javax.persistence.criteria.Predicate>();

    List<javax.persistence.criteria.Predicate> userNamePreds = new ArrayList<javax.persistence.criteria.Predicate>();

    List<javax.persistence.criteria.Predicate> workgroupPreds = new ArrayList<javax.persistence.criteria.Predicate>();

    if ((actionRequestCodes != null) && (!actionRequestCodes.isEmpty())) {
        Expression<String> exp = fromResp.get("actionRequestedCd");
        javax.persistence.criteria.Predicate actionRequestPredicate = exp.in(actionRequestCodes);

        respPredicates.add(actionRequestPredicate);
    }//from   w  w  w .  j  a v  a  2  s .  c om

    if (!org.apache.commons.lang.StringUtils.isEmpty(workflowId)) {
        // workflow user id exists
        if (searchUser != null && searchUser) {
            // searching user wishes to search for rules specific to user
            userNamePreds.add(cb.like(fromResp.get("ruleResponsibilityName"), workflowId));
            userNamePreds.add(cb.equal(fromResp.get("ruleResponsibilityType"),
                    KewApiConstants.RULE_RESPONSIBILITY_WORKFLOW_ID));

            javax.persistence.criteria.Predicate[] preds = userNamePreds
                    .toArray(new javax.persistence.criteria.Predicate[userNamePreds.size()]);
            ruleRespNamePredicates.add(cb.and(preds));

        }
        if ((searchUserInWorkgroups != null && searchUserInWorkgroups) && (workgroupIds != null)
                && (!workgroupIds.isEmpty())) {
            // at least one workgroup id exists and user wishes to search on workgroups

            Expression<String> exp = fromResp.get("ruleResponsibilityName");
            javax.persistence.criteria.Predicate groupIdPredicate = exp.in(workgroupIds);
            workgroupPreds.add(groupIdPredicate);
            workgroupPreds.add(cb.equal(fromResp.get("ruleResponsibilityType"),
                    KewApiConstants.RULE_RESPONSIBILITY_GROUP_ID));
            javax.persistence.criteria.Predicate[] preds = workgroupPreds
                    .toArray(new javax.persistence.criteria.Predicate[workgroupPreds.size()]);
            ruleRespNamePredicates.add(cb.and(preds));
        }
    } else if ((workgroupIds != null) && (workgroupIds.size() == 1)) {
        // no user and one workgroup id
        workgroupPreds.add(cb.like(fromResp.get("ruleResponsibilityName"), workgroupIds.iterator().next()));
        workgroupPreds.add(
                cb.equal(fromResp.get("ruleResponsibilityType"), KewApiConstants.RULE_RESPONSIBILITY_GROUP_ID));
        javax.persistence.criteria.Predicate[] preds = workgroupPreds
                .toArray(new javax.persistence.criteria.Predicate[workgroupPreds.size()]);
        ruleRespNamePredicates.add(cb.and(preds));

    } else if ((workgroupIds != null) && (workgroupIds.size() > 1)) {
        // no user and more than one workgroup id

        Expression<String> exp = fromResp.get("ruleResponsibilityName");
        javax.persistence.criteria.Predicate groupIdPredicate = exp.in(workgroupIds);
        workgroupPreds.add(
                cb.equal(fromResp.get("ruleResponsibilityType"), KewApiConstants.RULE_RESPONSIBILITY_GROUP_ID));
        javax.persistence.criteria.Predicate[] preds = workgroupPreds
                .toArray(new javax.persistence.criteria.Predicate[workgroupPreds.size()]);
        ruleRespNamePredicates.add(cb.and(preds));
    }

    if (!ruleRespNamePredicates.isEmpty()) {
        javax.persistence.criteria.Predicate[] preds = ruleRespNamePredicates
                .toArray(new javax.persistence.criteria.Predicate[ruleRespNamePredicates.size()]);
        respPredicates.add(cb.or(preds));
    }

    if (!respPredicates.isEmpty()) {

        javax.persistence.criteria.Predicate[] preds = respPredicates
                .toArray(new javax.persistence.criteria.Predicate[respPredicates.size()]);
        subquery.where(preds);
        subquery.select(fromResp.get("ruleBaseValuesId"));
        return subquery;
    }
    return null;
}

From source file:org.kuali.rice.kew.rule.dao.impl.RuleDAOJpa.java

private List<javax.persistence.criteria.Predicate> getSearchCriteria(Root<RuleBaseValues> root,
        CriteriaQuery<RuleBaseValues> query, String docTypeName, String ruleTemplateId, String ruleDescription,
        Boolean delegateRule, Boolean activeInd, Map extensionValues) {
    List<javax.persistence.criteria.Predicate> predicates = new ArrayList<javax.persistence.criteria.Predicate>();
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();

    predicates.add(cb.equal(root.get("currentInd"), Boolean.TRUE));
    predicates.add(cb.equal(root.get("templateRuleInd"), Boolean.FALSE));
    if (activeInd != null) {
        predicates.add(cb.equal(root.get("active"), activeInd));
    }/*from   www.  j  a va2 s .c  om*/
    if (docTypeName != null) {
        predicates.add(cb.like(cb.upper(root.<String>get("docTypeName")), docTypeName.toUpperCase()));
    }
    if (ruleDescription != null && !ruleDescription.trim().equals("")) {
        predicates.add(cb.like(cb.upper(root.<String>get("description")), ruleDescription.toUpperCase()));
    }
    if (ruleTemplateId != null) {
        predicates.add(cb.equal(root.get("ruleTemplateId"), ruleTemplateId));
    }
    if (delegateRule != null) {
        predicates.add(cb.equal(root.get("delegateRule"), delegateRule));
    }
    if (extensionValues != null && !extensionValues.isEmpty()) {
        for (Iterator iter2 = extensionValues.entrySet().iterator(); iter2.hasNext();) {
            Map.Entry entry = (Map.Entry) iter2.next();
            if (!StringUtils.isEmpty((String) entry.getValue())) {
                Subquery ruleExtSubQuery = query.subquery(RuleExtensionBo.class);
                Root<RuleExtensionBo> ruleExtRoot = ruleExtSubQuery.from(RuleExtensionBo.class);
                javax.persistence.criteria.Predicate predAnd = cb.and(
                        cb.equal(ruleExtRoot.get("extensionValues").get("key"), entry.getKey()),
                        cb.like(ruleExtRoot.get("extensionValues").<String>get("value"),
                                ("%" + (String) entry.getValue() + "%").toUpperCase()));
                ruleExtSubQuery.where(predAnd);
                ruleExtSubQuery.select(ruleExtRoot.get("ruleBaseValuesId"));

                predicates.add(cb.in(root.get("id")).value(ruleExtSubQuery));
            }
        }
    }
    return predicates;
}

From source file:org.medici.bia.dao.volume.VolumeDAOJpaImpl.java

/**
 * {@inheritDoc}/*from   ww w.jav a  2 s  .  co  m*/
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public Page searchVolumes(String text, PaginationFilter paginationFilter) throws PersistenceException {
    // Create criteria objects
    CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();

    Page page = new Page(paginationFilter);

    if (paginationFilter.getTotal() == null) {
        CriteriaQuery<Long> criteriaQueryCount = criteriaBuilder.createQuery(Long.class);
        Root<Volume> rootCount = criteriaQueryCount.from(Volume.class);
        criteriaQueryCount.select(criteriaBuilder.count(rootCount));

        List<Predicate> predicates = new ArrayList<Predicate>();
        predicates.add(
                criteriaBuilder.like((Expression) rootCount.get("serieList").get("title"), "%" + text + "%"));
        predicates.add(criteriaBuilder.like((Expression) rootCount.get("serieList").get("subTitle1"),
                "%" + text + "%"));
        predicates.add(criteriaBuilder.like((Expression) rootCount.get("serieList").get("subTitle2"),
                "%" + text + "%"));
        predicates.add(criteriaBuilder.like((Expression) rootCount.get("orgNotes"), "%" + text + "%"));
        predicates.add(criteriaBuilder.like((Expression) rootCount.get("recips"), "%" + text + "%"));
        predicates.add(criteriaBuilder.like((Expression) rootCount.get("researcher"), "%" + text + "%"));
        predicates.add(criteriaBuilder.like((Expression) rootCount.get("senders"), "%" + text + "%"));

        //If we omiss criteriaBuilder.or every predicate is in conjunction with others  
        criteriaQueryCount.where(criteriaBuilder.or(predicates.toArray(new Predicate[] {})));

        TypedQuery typedQueryCount = getEntityManager().createQuery(criteriaQueryCount);
        page.setTotal(new Long((Long) typedQueryCount.getSingleResult()));
    }

    CriteriaQuery<Volume> criteriaQuery = criteriaBuilder.createQuery(Volume.class);
    Root<Volume> root = criteriaQuery.from(Volume.class);

    //We need to duplicate predicates beacause they are link to Root element
    List<Predicate> predicates = new ArrayList<Predicate>();
    predicates.add(criteriaBuilder.like((Expression) root.get("serieList").get("title"), "%" + text + "%"));
    predicates.add(criteriaBuilder.like((Expression) root.get("serieList").get("subTitle1"), "%" + text + "%"));
    predicates.add(criteriaBuilder.like((Expression) root.get("serieList").get("subTitle2"), "%" + text + "%"));
    predicates.add(criteriaBuilder.like((Expression) root.get("orgNotes"), "%" + text + "%"));
    predicates.add(criteriaBuilder.like((Expression) root.get("recips"), "%" + text + "%"));
    predicates.add(criteriaBuilder.like((Expression) root.get("researcher"), "%" + text + "%"));
    predicates.add(criteriaBuilder.like((Expression) root.get("senders"), "%" + text + "%"));

    //If we omiss criteriaBuilder.or every predicate is in conjunction with others  
    criteriaQuery.where(criteriaBuilder.or(predicates.toArray(new Predicate[] {})));
    criteriaQuery.orderBy(criteriaBuilder.asc(root.get("summaryId")));

    // Set values in predicate's elements  
    TypedQuery<Volume> typedQuery = getEntityManager().createQuery(criteriaQuery);
    typedQuery.setFirstResult(paginationFilter.getFirstRecord());
    typedQuery.setMaxResults(paginationFilter.getLength());
    page.setList(typedQuery.getResultList());

    return page;
}

From source file:org.niord.core.area.AreaService.java

/**
 * Searches for areas matching the given search params
 *
 * @param params the sesarch params//  w  ww .  j a v a 2  s.  c om
 * @return the search result
 */
@SuppressWarnings("all")
public List<Area> searchAreas(AreaSearchParams params) {

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Area> areaQuery = cb.createQuery(Area.class);

    Root<Area> areaRoot = areaQuery.from(Area.class);

    // Build the predicate
    CriteriaHelper<Area> criteriaHelper = new CriteriaHelper<>(cb, areaQuery);

    // Match the name
    Join<Area, AreaDesc> descs = areaRoot.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) {
        areaRoot.join("parent", JoinType.LEFT);
        Path<Area> parent = areaRoot.get("parent");
        criteriaHelper.equals(parent.get("id"), params.getParentId());
    }

    // Assemple lineage filters from search domain and areas
    Set<String> lineages = new HashSet<>();

    // Optionally, filter by the areas associated with the specified domain
    if (StringUtils.isNotBlank(params.getDomain())) {
        Domain d = domainService.findByDomainId(params.getDomain());
        if (d != null && d.getAreas().size() > 0) {
            d.getAreas().forEach(a -> lineages.add(a.getLineage()));
        }
    }

    // Optionally, filter by area subtrees
    if (params.getAreaIds() != null && !params.getAreaIds().isEmpty()) {
        getAreaDetails(params.getAreaIds()).forEach(a -> lineages.add(a.getLineage()));
    }

    // If defined, apply the area lineage filter
    if (!lineages.isEmpty()) {
        Predicate[] areaMatch = lineages.stream()
                .map(lineage -> cb.like(areaRoot.get("lineage"), lineage + "%")).toArray(Predicate[]::new);
        criteriaHelper.add(cb.or(areaMatch));
    }

    // Optionally, search by type
    if (params.getType() != null) {
        criteriaHelper.add(cb.equal(areaRoot.get("type"), params.getType()));
    }

    // Optionally, require that the area has an associated geometry
    if (params.isGeometry()) {
        criteriaHelper.add(cb.isNotNull(areaRoot.get("geometry")));
    }

    // Optionally, require that the area has an messageSorting type
    if (params.isMessageSorting()) {
        criteriaHelper.add(cb.isNotNull(areaRoot.get("messageSorting")));
    }

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

    // Compute the sort order
    List<Order> sortOrders = new ArrayList<>();
    if (TREE_SORT_ORDER.equals(params.getSortBy())) {
        Arrays.asList("treeSortOrder", "siblingSortOrder", "id").forEach(field -> {
            if (params.getSortOrder() == PagedSearchParamsVo.SortOrder.ASC) {
                sortOrders.add(cb.asc(areaRoot.get(field)));
            } else {
                sortOrders.add(cb.desc(areaRoot.get(field)));
            }
        });
    }

    // Complete the query
    areaQuery.select(areaRoot).distinct(true).where(criteriaHelper.where()).orderBy(sortOrders);

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