JPQL Like Case Insensitive

前端 未结 4 1721
醉梦人生
醉梦人生 2020-12-06 09:00

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

@Repository
public interface UserRepository extends JpaRepository {

  @Query         


        
相关标签:
4条回答
  • 2020-12-06 09:30

    I am using Spring Boot 2.1.6, You can define query methods using Containing, Contains, and IsContaining as below:

    List<User> findByNameContaining(String name);
    List<User> findByNameContains(String name);
    List<User> findByNameIsContaining(String name);
    

    Case Insensitivity:

    List<User> findByNameContainingIgnoreCase(String name);
    

    OR you can also define as below as well:

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

    The @Param annotation is important here because we're using a named parameter.

    0 讨论(0)
  • 2020-12-06 09:33

    You can use the concat operator:

    @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)

    0 讨论(0)
  • 2020-12-06 09:38

    You can use wildcard matching.

    for example, i want to search name like 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");
    
    0 讨论(0)
  • 2020-12-06 09:42

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

    List<User> findByNameContainingIgnoreCase(String name);
    

    Else you need to wrap the name attribute 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.

    0 讨论(0)
提交回复
热议问题