带有 LIKE 的 Spring JPA @Query [英] Spring JPA @Query with LIKE
问题描述
我正在尝试在 CrudRepository 中创建一个方法,该方法能够为我提供用户列表,其用户名类似于输入参数(不仅以开头,还包含它).我尝试使用方法 "findUserByUsernameLike(@Param("username") String username)"
但正如 Spring 文档中所说,此方法等于 where user.username like ?1
".这对我不利,因为我已经告诉过我正在尝试让所有用户名包含 ...
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?
推荐答案
尝试使用以下方法(对我有用):
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);
注意:JPQL中的表名必须以大写字母开头.
Notice: The table name in JPQL must start with a capital letter.
这篇关于带有 LIKE 的 Spring JPA @Query的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!