使用谓词和条件API的不区分大小写的搜索 [英] Case insensitive search with Predicate and Criteria API

查看:70
本文介绍了使用谓词和条件API的不区分大小写的搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前已经实现了一个动态查询构建器,如果我的查询条件拼写正确,该构建器可以完美地工作.由于可能并非总是如此,因此我需要一个足够灵活的解决方案来适应条件的任何变化,主要是支持不区分大小写.

I have currently implemented a dynamic query builder that works perfectly if my query conditions are spelled correctly. Since this might not be always the case I need a solution that is flexible enough to take any variation of the condition, primarily supporting case insensitivity.

当前规范的toPredicate方法覆盖代码如下:

Current specification's toPredicate method override code looks like this:

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

    Path<String> username = root.get("username");
    Path<String> agentCode = root.get("agentCode");
    Path<EntityStatus> status = root.get("status");
    Path<String> firstname = root.get("firstName");
    Path<String> lastname = root.get("lastName");
    Path<String> email = root.get("eMail");


if(criteria.getUsername()!=null && !criteria.getUsername().isEmpty()) {
      predicates.add(cb.equal(username, criteria.getUsername()));
    }

    if(criteria.getAgentCode()!=null && !criteria.getAgentCode().isEmpty()) {
      predicates.add(cb.equal(agentCode, criteria.getAgentCode()));
    }

    if(criteria.getFirstName()!=null && !criteria.getFirstName().isEmpty()) {
      predicates.add(cb.like(firstname, "%"+criteria.getFirstName()+"%"));
    }

    if(criteria.getLastName()!=null && !criteria.getLastName().isEmpty()) {
      predicates.add(cb.equal(lastname, criteria.getLastName()));
    }

    if(criteria.getEMail()!=null && !criteria.getEMail().isEmpty()) {
      predicates.add(cb.equal(email, criteria.getEMail()));
    }

    if(criteria.getStatus()!=null) {
      predicates.add(cb.equal(status, criteria.getStatus()));
    }

    return cb.and(predicates.toArray(new Predicate[predicates.size()]));
  }

从服务层调用的我的存储库接口看起来像这样.

And my repository interface that is being called from the service layer looks like this.

public interface UserRepo extends PagingAndSortingRepository<User, Long> {
     List<User> findAll(Specification spec);
}

谢谢您的帮助

推荐答案

通常,使用方法但是,在这种情况下,您只是解析要比较的值,而没有实现比较本身.因此,您可以使用方法

However in this case you just parse values to be compared without implementing the comparison itself. Thus you can parse all the values in lower-case using the method toLowerCase() forcing them to be compared case insensitively.

predicates.add(cb.equal(email.toLowerCase(), criteria.getEMail().toLowerCase()));


我看了看CriteriaBuilder的JavaEE文档,发现了方法


I have taken a look on the JavaEE documentation of CriteriaBuilder and found the method lower() which may be helpful.

这篇关于使用谓词和条件API的不区分大小写的搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆