【问题标题】:spring data JPA searching ignoring words order春季数据JPA搜索忽略单词顺序
【发布时间】:2019-01-23 19:07:01
【问题描述】:

使用命名方法dao.findByNameContains("hotel sheraton"),可以得到名称中包含hotel sheraton的酒店列表。但如果酒店的名称是sheraton hotel,则不会返回该酒店。

所以我想知道如果字符串由单词列表组成,如何忽略单词顺序进行搜索。

【问题讨论】:

    标签: spring-boot spring-data-jpa


    【解决方案1】:

    您不能使用派生查询(即从方法名称派生的查询)来做到这一点。

    可能最好的方法是使用Specifications as described in the linked article

    然后,您可以使用一种方法将 Strings 列表转换为 Specification,它是 Like-Specifications 的组合:

    public MySpecifications {
    
        public static Specification<???> nameContains(String namePart) {
    
            return new Specification<Customer> {
    
                 public Predicate toPredicate(Root<T> root, CriteriaQuery query, CriteriaBuilder cb) {
                     return cb.like(root.get("name"), "%" + namePart + "%");
                 }
            };
        }
    
        public static Specification<???> nameContainsAny(Collection<String> nameParts) {
    
            Specification spec = Specification.where();
    
            for (String namePart : nameParts) {
                spec = spec.or(nameContains(String namePart)
            }
    
            return spec;
        }
    }
    

    注意:代码中的错误仅供读者练习。

    【讨论】:

      猜你喜欢
      • 2021-03-14
      • 2019-06-09
      • 1970-01-01
      • 2016-01-30
      • 1970-01-01
      • 2013-11-12
      • 1970-01-01
      • 2020-02-20
      • 1970-01-01
      相关资源
      最近更新 更多