龙哥网

龙哥网

Mybatis注解方式完成输入参数为list的SQL语句拼接方式_java
2022-03-01

目录
  • Mybatis注解完成输入参数为list的SQL语句拼接
  • 拼接查询条件为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函数来实现

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设为传入的变量

最后得到

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

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;
}
免责声明
本站部分资源来源于互联网 如有侵权 请联系站长删除
龙哥网是优质的互联网科技创业资源_行业项目分享_网络知识引流变现方法的平台为广大网友提供学习互联网相关知识_内容变现的方法。