java - 如何在 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";
}
}
解决方案
如果您有一条值为“aaabbbccc”的记录,并且您希望在搜索时返回此记录,bc
那么您需要使用包含。
Containing
将您的搜索字符串包装在%%
其中结果为like %bc%
.
此外,您可以使用 IgnoreCase 来 - 是的 - 忽略大小写;)
所以你需要使用:
postRepository.findByTitleContainingIgnoreCase(searchString);
编辑:有关更多详细信息,将搜索字符串包装在 '%searchString%' 中意味着:忽略搜索字符串前后的所有内容,以便搜索字符串可以位于字符串中的某个位置。
推荐阅读
- javascript - 如何将此promise对象转换为带有结果的数组
- java - 在 SharedPreferences 中加密和解密 Android 字符串
- python - 如何在 Python 中获得多类分类问题的相邻准确度分数?
- node.js - 如何防止 npm 为软件包安装 demo/sample/example/test 代码?
- python - 如何捕获仅记录的错误?
- python - 如何重复输入命令?
- java - 为什么 Java BitSet 被打包成 6 个字节?
- android - 从 Firestore 中删除文档
- oracle - Oracle Database 19c 示例模式 :: 从 Oracle SQL Developer GUI 导入示例而不是命令行
- javascript - 无法将 Laravel 刀片文件中的道具传递给 Vue 组件