【问题标题】:Mysql 'Like' search in Spring boot and hibernateMysql'Like'在Spring boot和hibernate中搜索
【发布时间】:2017-03-22 20:36:50
【问题描述】:

我正在使用 Spring boot + Hibernate 在我的应用程序中创建搜索功能。数据库是 MySQL。 我需要在我的实体中的几个字段上执行数据搜索。我还想做部分数据匹配,基本上就是 MySQL 'LIKE' 所做的。

例如:...

 WHERE name LIKE '%searchText%' OR description LIKE '%searchText%'.

我知道我可以使用@Query 或 findByNameContaining。但这不会随着数据的增加而优化。

我以此为例进行搜索:

http://blog.netgloo.com/2014/11/23/spring-boot-and-hibernate-search-integration/

这对我来说非常适合完整的数据匹配。但我无法弄清楚如何将其用于部分数据匹配。

编辑:添加示例数据和更多描述

示例:如果我有以下行:

id     | name        | description                       | type

1      | sample      | this is a sample description      | Y

2      | samples     | this is a description for samples | Y

3      | not a match | this should not match             | Y

4      | not a match | this should also not match        | Y

结果:

1      | sample      | this is a sample description      | Y

2      | samples     | this is a description for samples | Y

所以,当我搜索样本时,它应该匹配“样本”和“样本”的前两行,如果在名称或描述中找到“样本”子字符串,则匹配更多行。

另外,我想在搜索子句中添加更多字段。示例:仅搜索 'type' 为 'Y' 的那些行

请帮帮我。

提前致谢。

【问题讨论】:

  • 部分匹配是什么意思.. 更新您的问题并添加适当的数据样本和预期结果
  • @scaisEdge 添加了数据样本

标签: mysql hibernate spring-boot


【解决方案1】:

您可以将Restriction.ilike 与Restriction.or 一起使用,并会得到您想要的结果:

Criterion cond1= Restrictions.ilike("name","%"+searchText+"%");
Criterion cond2= Restrictions.ilike("description", "%"+searchText+"%");
criteria.add(Restrictions.or(cond1, cond2));

【讨论】:

    猜你喜欢
    • 2014-10-17
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    • 2014-11-04
    • 2018-06-08
    相关资源
    最近更新 更多