Viktoriia Viktoriia - 1 year ago 79
SQL Question

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 queryto the method but it even doesn't deploy.

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download