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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With