CriteriaBuilder,实现Mysql 的 find_in_set 函数

实现方式:主要用到 CriteriaBuilder 接口中的function方法

1、单个参数实现

xxxRepository.findAll((root, query, cb) -> {
       //查询条件集合
       List<Predicate> predicateList = new ArrayList<>();
 
        //根据单个参数查询
        //param 为查询的参数  targetColName 为数据库中表的字段名
        if (StringUtils.isNotBlank(param)) {
            //返回参数在数据库中该字段的位置
            Expression<Integer> findInSetFun = cb.function("FIND_IN_SET", Integer.class,             
                                cb.literal(param), root.get("targetColName"));
            //设置条件 只要返回值 >0 则说明该参数存在于目标字符串中
            predicateList .add(cb.greaterThan(findInSetFun, 0));
        }
    }, pageable);

2、多个参数实现,原理同上,具体见下面截图

CriteriaBuilder,实现Mysql 的 find_in_set 函数