javajquerysqlspringjpa

Spring JPA @Query with LIKE


I'm trying to make a method in CrudRepository that will be able to give me list of users, whose usernames are LIKE the input parameter(not only begin with, but also contains it). I tried to use method "findUserByUsernameLike(@Param("username") String username)" but as it is told in Spring documentation, this method is equal to "where user.username like ?1". It is not good for me, as I already told that I'm trying to get all users whose username contains ...

I wrote a query to the method but it even doesn't deploy.

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

    @Query("select u from user u where u.username like '%username%'")
    List<User> findUserByUsernameLike(@Param("username") String username);
}

Can anybody help me with this?


Solution

  • 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.