我是靠谱客的博主 真实苗条,这篇文章主要介绍Mybatis注解方式完成输入参数为list的SQL语句拼接方式,现在分享给大家,希望可以做个参考。

Mybatis注解完成输入参数为list的SQL语句拼接

首先将list集合拼接成一个"1,2,3,4"格式的字符串

然后将这个字符串封装到一个类中:TyreInfoIdStr

这里的@SelectProvider是调用一个外部的类的方法的返回值作为sql语句。

在这个方法中拼接SQL语句与list集合的字符串,我这里是提前拼接过了。

拼接查询条件为list集合的sql函数

当deptId 为1时 sql语句不做更改

当deptId 为其他数字时 list中的id项作为sql查询条件

刚开始编写的时候思路是用or语句进行循环遍历 重复加上or的sql语句来查询

发现比较复杂 最后采取了sql的in函数来实现

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public String getDeptIdSql(List<Long> deptIdList){ Iterator<Long> it = deptIdList.iterator(); //当部门id为1时 不采用筛选 while(it.hasNext()){ Long deptId = it.next(); if(deptId == 1){ return ""; } } //拼接in条件语句 String s = ""; for(int i = 0; i < deptIdList.size();i++){ if(i!=(deptIdList.size()-1)){ s += deptIdList.get(i) + ","; }else{ s += deptIdList.get(i); } } String sql = " and mtMaintenanceStandard.dept_Id in (" + s + ") "; return sql; }

编写完成后发现函数有可以提高函数的复用性,将mtMaintenanceStandard.dept_Id设为传入的变量

最后得到

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public String getDeptIdSql(String condition,List<Long> deptIdList){ Iterator<Long> it = deptIdList.iterator(); //当部门id为1时 不采用筛选 while(it.hasNext()){ Long deptId = it.next(); if(deptId == 1){ return ""; } } //拼接in条件语句 String s = ""; for(int i = 0; i < deptIdList.size();i++){ if(i!=(deptIdList.size()-1)){ s += deptIdList.get(i) + ","; }else{ s += deptIdList.get(i); } } String sql = " and " + condition + " in (" + s + ") "; return sql; }

更为通用的版本是不用判断deptId是否为1

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
public String getDeptIdSql(String condition,List<Long> deptIdList){ String s = ""; for(int i = 0; i < deptIdList.size();i++){ if(i!=(deptIdList.size()-1)){ s += deptIdList.get(i) + ","; }else{ s += deptIdList.get(i); } } String sql = " and " + condition + " in (" + s + ") "; return sql; }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持靠谱客。

最后

以上就是真实苗条最近收集整理的关于Mybatis注解方式完成输入参数为list的SQL语句拼接方式的全部内容,更多相关Mybatis注解方式完成输入参数为list内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(154)

评论列表共有 0 条评论

立即
投稿
返回
顶部