Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

like image 722
Viktoriia Avatar asked Jan 30 '14 12:01

Viktoriia


People also ask

Is it possible to define a sort type in @query annotation using Spring JPA?

Using a Sort Object With Spring Data JPA, you can also add a parameter of type Sort to your method definition. Spring Data JPA will then generate the required ORDER BY clause. That is the same approach as you can use in a derived query.

What is the use of @query in JPA?

In order to define SQL to execute for a Spring Data repository method, we can annotate the method with the @Query annotation — its value attribute contains the JPQL or SQL to execute. The @Query annotation takes precedence over named queries, which are annotated with @NamedQuery or defined in an orm. xml file.

What is difference between PagingAndSortingRepository and JpaRepository?

PagingAndSortingRepository provides methods to do pagination and sort records. JpaRepository provides JPA related methods such as flushing the persistence context and delete records in a batch.


1 Answers

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.

like image 150
Mark Avatar answered Sep 30 '22 17:09

Mark