简体   繁体   中英

Spring Data CrudRepository @Query With LIKE and IgnoreCase

I need to retrieve some Entity fields from CrudRepository:

public class User {
    private String name;

    // getters and setters
}

public interface UserRepository extends CrudRepository<User, Long> { 

   @Query("SELECT U.name FROM User U WHERE LOWER(U.name) LIKE LOWER(?1)")
   List<String> findByName(String matchPhrase);
}

Basically, I want to get equivalent of SQL query:

SELECT u.name FROM user u WHERE LOWER(u.name) LIKE LOWER('match%')

The problem is that @Query doesn't works (empty list returned), hibernate generates log:

Hibernate: select user0_.name as col_0_0_ from user user0_ where lower(user0_.name) like lower(?)

I actually didn't get how to specify a parameter bound with appended %.

// also fails at compile-time
@Query("SELECT U.name FROM User U WHERE LOWER(U.name) LIKE LOWER(?1%)")

org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: null near line ...

This works fine but returns whole Entity, what may produce long response because I need retrieve only specific fields:

List<User> findByNameStartingWithIgnoreCase(String match);

Try this

@Query("SELECT U.name FROM User U WHERE LOWER(U.name) LIKE LOWER(concat(?1, '%'))")
List<String> findByName(String matchPhrase);

If you need the format like %name% (instead of like name% ) you can expand the accepted answer as follows:

@Query("SELECT U.name FROM User U WHERE LOWER(U.name) LIKE LOWER(concat('%', concat(?1, '%')))")
List<String> findByName(String matchPhrase);

have you try this syntax:

@Query("SELECT U.name FROM User U WHERE LOWER(U.name) LIKE LOWER(?1)%") and the just give the name or the beginning of the name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM