JPA单独在同一列中搜索多个单词

时间:2019-07-10 12:03:36

标签: spring-boot jpa

是否可以在列中分别搜索多个单词-类似于:

@Query("SELECT a FROM Article a WHERE LOWER(a.text) LIKE LOWER(CONCAT('%',:word1,'%')) AND LOWER(a.text) LIKE LOWER(CONCAT('%',:word2,'%'))")

但是要使用多个单词ArrayList<String> words

1 个答案:

答案 0 :(得分:1)

是的,您可以通过使用Criteria API构建动态查询来实现。

您的规格可能如下:

Specification<Article> forWords(Collection<String> words) {
    if(words == null || words.isEmpty())
        throw new RuntimeException("List of words cannot be empty.");

    return (root, query, builder) -> words.stream()
            .map(String::toLowerCase)
            .map(word -> "%" + word + "%")
            .map(word -> builder.like(builder.lower(root.get("text")), word))
            .reduce(builder::or)
            .get();

}

,然后可以在启用了JpaSpecificationExecutor<Article>的存储库中执行:

List<String> words = ...; //your logic to get words
List<Article> matches = articleRepository.findAll(forWords(words));