将任何文本匹配到搜索框中

问题描述

我使用此搜索规范来尝试按标题搜索文本。如果我输入确切的搜索字符串,它就可以正常工作:

public Page<ClassCategoriesFullDTO> findClasses(ClassCategoriesSearchParams params,Pageable pageable) {
        Specification<Product> spec = (root,query,cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (params.getTitle() != null) {
                predicates.add(cb.equal(root.get("title"),params.getTitle()));
            }
            if (params.getType() != null) {
                predicates.add(cb.equal(root.get("type"),params.getType()));
            }
            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        return classCategoriesService.findAll(spec,pageable).map(classCategoriesMapper::toFullDTO);
    }

如何修改代码以使用我在数据库表中键入的每个文本搜索数据库

解决方法

您可以使用标准构建器 (cb) 就像一种搜索“an”来获取“姓氏”的方法

static Specification<ClassCategoriesFullDTO> titleContains(String title) {
    return (root,cq,cb) -> cb.like(root.get("title"),"%" + title + "%");
}

如果您想忽略大小写,请使用:

static Specification<ClassCategoriesFullDTO> titleContains(String title) {
    return (root,cb) -> cb.like(cb.lower(root.get("title")),"%" + title.toLowerCase() + "%");
}