Java JPQL 类似大小写不敏感

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37178520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:05:01  来源:igfitidea点击:

JPQL Like Case Insensitive

javaspringjpaspring-data-jpajpql

提问by windupurnomo

I want to search data in User table by name case insensitive.

我想按名称不区分大小写搜索用户表中的数据。

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

  @Query("select u from User u where lower(u.name) like %lower(?1)%")
  public List<User> findByNameFree(String name);

}

I got an error: unexpected token: %. Where should I place '%'?

我收到一个错误:意外令牌:%。我应该把“%”放在哪里?

采纳答案by Wim Deblauwe

You can use the concat operator:

您可以使用 concat 运算符:

@Query("select u from User u where lower(u.name) like lower(concat('%', ?1,'%'))")
public List<User> findByNameFree(String name);

or with a named parameter:

或使用命名参数:

@Query("select u from User u where lower(u.name) like lower(concat('%', :nameToFind,'%'))")
public List<User> findByNameFree(@Param("nameToFind") String name);

(Tested with Spring Boot 1.4.3)

(使用 Spring Boot 1.4.3 测试)

回答by Nicholas

You can use wildcard matching.

您可以使用wildcard matching.

for example, i want to search name like haha,

例如,我想搜索名称,例如haha

@Query("select u from User u where lower(u.name) like :u_name")
public List<User> findByNameFree(@Param("u_name") String name);
List<User> users = userDao.findByNameFree("%haha");

回答by M. Deinum

If that is only what you want and you are using Spring Data JPA you don't need to write a query.

如果这只是您想要的并且您正在使用 Spring Data JPA,则不需要编写查询。

List<User> findByNameContainingIgnoreCase(String name);

Else you need to wrap the nameattribute with %before you pass it to the method (putting those directly in the query will simply not work). Or don't use a query but use a specification or the Criteria API to create the query.

否则,您需要在将name属性%传递给方法之前对其进行包装(将它们直接放在查询中是行不通的)。或者不使用查询,而是使用规范或 Criteria API 来创建查询。