SpringDataJPA之@Query LIKE模糊查询特殊处理方式

对于JPA来说,like查询是不友好的,,例如这么查,是查不出来东西的

@Query("select u from user u where u.username like '%username%'")
List findUserByUsernameLike(@Param("username") String username);
1
2
@Query("select u from user u where u.username like '%?1%'")
List findUserByUsernameLike(String username);
1
2
=。=这个时候可以用CONCAT函数来帮忙,用column like CONCAT(‘%’,?1,’%’) 进行拼接。如下

@Query("SELECT u.username FROM User u WHERE u.username LIKE CONCAT('%',:username,'%')")
List findUsersWithPartOfName(@Param("username") String username);
1
2
核心就是mysql的concat函数,CONCAT()函数用于将多个字符串连接成一个字符串,是最重要的mysql函数之一

 CONCAT('%',?1,'%') 
1
再这里感谢stackoverflow大神的回答与启示 
https://stackoverflow.com/questions/21456494/spring-jpa-query-with-like

最后,放出一段实战@Query查询

(e.event_title like CONCAT(‘%’,?1,’%’) or ?1 is null) 
代表不存在则不查询,存在则进行模糊查询

@Query(value = " select * from event e "
            + " where (e.event_title like CONCAT('%',?1,'%')  or ?1 is null) "
            + " and (to_days(e.register_time)=to_days(?2) or ?2 is null) "
            + " and e.status = '1' "
            + " order by e.register_time desc limit ?3,?4 ",nativeQuery = true)
    List findAllList(String eventTitle,Timestamp registerTime,Integer pageNumber,Integer pageSize);

https://blog.csdn.net/moshowgame/article/details/80681502

你可能感兴趣的:(SpringDataJPA之@Query LIKE模糊查询特殊处理方式)