【发布时间】:2021-05-18 10:03:44
【问题描述】:
写了一个 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";
}
}
【问题讨论】:
-
将您的
findByTitle重命名为findByTitleLikeIgnoreCase。见docs.spring.io/spring-data/jpa/docs/current/reference/html/…。关于您的服务,您甚至没有使用它,但它不应该abstract(您不能使用abstract类的实例)并且您的方法也有缺陷(如果有结果抛出异常?) . -
你可以多写点我的抽象类,我不太明白你的意思……
-
你根本没有使用它,所以放弃它,接下来它在多个层面上也存在缺陷(实现接口、抽象、错误的结果检查到名称 3)。
-
我什么都明白了,抽象类什么也没做,一切都是从存储库中完成的。谢谢。我按照你的建议做了(findByTitleLikeIgnoreCase),但搜索继续搜索,因为我正在搜索。我一次找不到一个词...
-
如果您有一条值为“aaabbbccc”的记录,并且在搜索“bc”时应返回此记录,那么您需要使用包含将您的搜索字符串包装在“%%”中,这会导致
like %bc%。此外,您可以使用 IgnoreCase 来 - 是的 - 忽略大小写 ;) 所以它就像postRepository.findByTitleContainingIgnoreCase(searchString);
标签: java spring spring-boot spring-data-jpa spring-data