JPQL Like Case Insensitive
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 '%'?
Solution 1:
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)
Solution 2:
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.
Solution 3:
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.