springboot中使用动态sql约束查询
最近遇到个新功能,就是需要进行动态sql的查询,因为不确定会有多少个查询条件,所以就搜集各种资料,发现springboot中有两种方式,一种是注解形式,一种是xml的形式,我用的是注解的形式,xml的可以参考https://blog.csdn.net/qq_61903414/article/details/130650153
在mapper文件中写上
@Select({
"<script>",
"select * from invoiceinfo",
"<where>",
"<if test=\"null != state\">",
"and state=#{state}",
"</if>",
"<if test=\"null != invoiceReportType\">",
"and invoiceReportType=#{invoiceReportType}",
"</if>",
"<if test=\"null != invoiceNumber\">",
"and invoiceNumber like CONCAT('%',#{invoiceNumber},'%')",
"</if>",
"<if test=\"null != invoiceReportDepartment\">",
"and invoiceReportDepartment like CONCAT('%',#{invoiceReportDepartment},'%')",
"</if>",
"<if test=\"null != invoiceReporter\">",
"and invoiceReporter like CONCAT('%',#{invoiceReporter},'%')",
"</if>",
"<if test=\"null != startDate\">",
"and date>=#{startDate}",
"</if>",
"<if test=\"null != endDate\">",
"and date<=#{endDate}",
"</if>",
"</where>",
"</script>"
})
List<Map<String, Object>> toBackSelectInvoice(String invoiceNumber,String state,String invoiceReportDepartment, String invoiceReporter,String invoiceReportType,String startDate,String endDate, Integer page);
其中的if就是判断这个参数是否为null,如果是null就不执行,注意:一定是需要前端传过来的值是null才可以, '' 这种空值的话也是会被当作有值的。
这样就可以使用多条查询条件进行动态的sql查询了。
意思是当sql语句的查询条件需要满足某种条件才能生效时,我们可以使用if标签和choose标签来实现sql查询条件的动态变化,if标签是与(and)的关系,choose是或(or)的关系。
使用if标签时,只有test条件成立,才会动态添加sql语句。test中的条件需要用\"括起来。大于号和小于号属于特殊字符,使用时需要用>和<代替
具体的语法请参考这位博主
参考:https://blog.csdn.net/WZh0316/article/details/105637829
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律