Spring JPA @Query with LIKE Spring JPA @Query with LIKE sql sql

Spring JPA @Query with LIKE


Try to use the following approach (it works for me):

@Query("SELECT u.username FROM User u WHERE u.username LIKE CONCAT('%',:username,'%')")List<String> findUsersWithPartOfName(@Param("username") String username);

Notice: The table name in JPQL must start with a capital letter.


Using Query creation from method names, check table 4 where they explain some keywords.

  1. Using Like: select ... like :username

     List<User> findByUsernameLike(String username);
  2. StartingWith: select ... like :username%

     List<User> findByUsernameStartingWith(String username);
  3. EndingWith: select ... like %:username

     List<User> findByUsernameEndingWith(String username);
  4. Containing: select ... like %:username%

     List<User> findByUsernameContaining(String username);

Notice that the answer that you are looking for is number 4. You don't have to use @Query


Another way: instead CONCAT function we can use double pipe: :lastname || '%'

@Query("select c from Customer c where c.lastName LIKE :lastname||'%'")List<Customer> findCustomByLastName( @Param("lastname") String lastName);

You can put anywhere, prefix, suffix or both

:lastname ||'%'  '%' || :lastname  '%' || :lastname || '%'