问题
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);
回答1:
Try this
@Query("SELECT U.name FROM User U WHERE LOWER(U.name) LIKE LOWER(concat(?1, '%'))")
List<String> findByName(String matchPhrase);
回答2:
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);
回答3:
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
来源:https://stackoverflow.com/questions/40356565/spring-data-crudrepository-query-with-like-and-ignorecase