【问题标题】:Case insensitive Query with Spring CrudRepository使用 Spring CrudRepository 进行不区分大小写的查询
【发布时间】:2014-04-29 16:28:11
【问题描述】:

使用 Spring CrudRepository 查询;我想选择具有“名称”属性的“设备类型”实体。但以下查询以区分大小写的方式选择权利。我如何使它不区分大小写。谢谢。

public interface DeviceTypeRepository extends CrudRepository<DeviceType, Integer>, JpaSpecificationExecutor<DeviceType> {

    public Iterable<DeviceType> findByNameContaining(String name);

}  

【问题讨论】:

  • 你试过public Iterable&lt;DeviceType&gt; findByNameIgnoreCaseContaining(String name);吗?
  • 如果您对 Query 感兴趣,请试试这个,LIKE @Query(value= "select dt from DeviceType as dt where lower(dt.name ) like lower(:name)") public Iterable<devicetype> anyMethodNameGoesHere(@Param(name) String name);</devicetype>

标签: spring spring-data-jpa


【解决方案1】:

对于那些使用自定义 JPA 查询 Upper 关键字和 toUpperCase 的人有帮助。以下代码适用于我

 return  entityManager.createQuery("select q from "table " q  where upper(q.applicant)=:applicant")
    .setParameter("applicant",applicant.toUpperCase().trim()).getSingleResult();

【讨论】:

  • 使用'upper(q.applicant)'时要小心。在 Postgres 中,当 q.applicant 为空时,它会导致 '.PSQLException: ERROR: function upper(bytea) does not exist'
【解决方案2】:

在我的情况下,添加 IgnoreCase 根本不起作用。

我发现也可以为正则表达式提供选项:

@Query(value = "{'title': {$regex : ?0, $options: 'i'}}")
Foo findByTitleRegex(String regexString);

i 选项使查询不区分大小写。

【讨论】:

    【解决方案3】:

    以下 Spring 数据 mongo 查询适用于我。我更喜欢使用List 而不是Iterator

    public interface DeviceTypeRepository extends CrudRepository<DeviceType,Integer>, JpaSpecificationExecutor<DeviceType> {
        List<DeviceType> findByNameIgnoreCase(String name);
    } 
    

    【讨论】:

      【解决方案4】:

      正如评论中提到的@Peter,只需添加IgnoreCase

      public interface DeviceTypeRepository 
          extends CrudRepository<DeviceType, Integer>, JpaSpecificationExecutor<DeviceType> {
      
          public Iterable<DeviceType> findByNameContainingIgnoreCase(String name);
      }  
      

      请参阅 documentation 以获取方法名称中所有受支持的关键字的列表。

      【讨论】:

      • 非常感谢您的回答;当然我会参考该文档。五月谢谢。玩得开心!
      • 它对我有用。我正在使用 JPA 查询。因此,根据文档,UPPER(x.firstame) = UPPER(?1) 工作的地方。
      • @sunitha 你知道我们有什么办法可以修改这种行为,比如让它变低吗?我的数据库有基于小写的索引
      • @SudipBhandari:当然可以。
      • 对于多个属性重复 IgnoreCase 像这样:List&lt;Account&gt; findByUsernameIgnoreCaseAndDomainIgnoreCase(String username, String domain);
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-08
      • 1970-01-01
      • 2019-05-21
      • 2018-06-14
      • 2017-06-04
      • 1970-01-01
      相关资源
      最近更新 更多