【问题标题】:How to make a search in Spring look for one word in the name and not for the full name?如何在 Spring 中搜索名称中的一个单词而不是全名?
【发布时间】: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


【解决方案1】:

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

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

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

所以你需要使用:

postRepository.findByTitleContainingIgnoreCase(searchString);

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

【讨论】:

  • 非常感谢。我喜欢这个网站,我在这里学到的东西比从所有教科书或教程中学到的更多。再次感谢你,当我成为你这种水平的程序员时,我也会在这个网站上帮助像我这样的人=)
猜你喜欢
  • 1970-01-01
  • 2021-10-06
  • 1970-01-01
  • 1970-01-01
  • 2016-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-27
相关资源
最近更新 更多