spring data jpa 使用@Query 动态参数查询案例分析

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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值