spring data jpa 使用@Query 动态参数查询案例分析
1、目的要做复杂的动态查询,需要判断是否非空的查询参数,当参数为空时,跳过该参数,继续查找不为空的参数进行查询。2、代码分析nativeQuery = true:表示使用原生的sql语句判断语句的格式:if(‘参数’ is not nulland ‘参数’=’’,查找的条件 ),如下判断语句if(?1 is not null and ?1!=’’,video_id=?1,1=1)其中?1表示方法中
·
1、目的
要做复杂的动态查询,需要判断是否非空的查询参数,当参数为空时,跳过该参数,继续查找不为空的参数进行查询。
2、代码分析
nativeQuery = true:表示使用原生的sql语句
判断语句的格式:if(‘参数’ is not null and ‘参数’=’’,查找的条件 ),如下判断语句
if(?1 is not null and ?1!=’’,video_id=?1,1=1)
其中?1表示方法中的第一个参数,如下面的videoId,以此类推
在查找的条件中,我们可以进行模糊查找video_title like concat(’%’,?2,’%’),等值判断video_id=?1,具体看需要
List findVideoByLike(Integer videoId,String videoTitle);
@Query(nativeQuery = true,value = "select * from video where if(?1 is not null and ?1!='',video_id=?1,1=1) and if(?2 is not null and ?2!='',video_title like concat('%',?2,'%'), 1=1)")
List<Video> findVideoByLike(Integer videoId,String videoTitle);
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)