首页 > 解决方案 > 如何在 Spring 中搜索名称中的一个单词而不是全名?

问题描述

写了一个搜索 Spring 站点。搜索按标题搜索文章,但它只搜索确切的标题,我需要它来找到它,即使在文章标题的搜索中输入了一个单词。例如,如果我有一篇文章“地球为什么是圆的?”,现在如果你输入“地球为什么是圆的?”,他就会找到这篇文章。在搜索中,但如果您只输入“为什么”这个词,他将找不到任何东西。请告诉我如何做标题中的单词会找到的东西。

我的存储库

public interface PostRepository extends JpaRepository<Post, Long> {
 Iterable<Post> findByTitle(String title) throws Exception;
}

我的服务是为这个存储库编写的(顺便说一句,告诉我,我把它抽象化以便只在其中实现 findByTitle 吗?)

@Service
public abstract class PostService implements PostRepository {

public PostRepository postRepository;

@Override
public Iterable<Post> findByTitle(String title) throws Exception {
    Iterable<Post> searchResult = postRepository.findByTitle(title);
    if(searchResult != null){
        throw new Exception("Пост не найден");
    }

    return searchResult;
}
}

我的控制器

@Controller
public class SearchController {

@Autowired
PostRepository postRepository;

@GetMapping("/search")
public String searchPage(){
    return "/search";
}

@PostMapping("search")
public String searchPage(@RequestParam("searchString") String searchString, Model model){
    if(searchString != null){
        try {
            Iterable<Post> searchResult = postRepository.findByTitle(searchString);
            model.addAttribute("searchResult", searchResult);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return "search";
}
}

标签: javaspringspring-bootspring-data-jpaspring-data

解决方案


如果您有一条值为“aaabbbccc”的记录,并且您希望在搜索时返回此记录,bc那么您需要使用包含

Containing将您的搜索字符串包装在%%其中结果为like %bc%.

此外,您可以使用 IgnoreCase 来 - 是的 - 忽略大小写;)

所以你需要使用:

postRepository.findByTitleContainingIgnoreCase(searchString);

编辑:有关更多详细信息,将搜索字符串包装在 '%searchString%' 中意味着:忽略搜索字符串前后的所有内容,以便搜索字符串可以位于字符串中的某个位置。


推荐阅读