mybatis plus动态sql之in采坑记

178 阅读1分钟

整数型数组参数

Integer[] executorIdArr

错误用法

先将整数型数组转换成字符串,然后直接拼接

    @Select("select unionid from "+tableName +" where corpId = #{companyId} and userID in (#{userArrIds})")
    List<String> getUnionIdByUserIdAndCompany(String companyId, String executorIdArr);

你以为最终是这样的

SELECT unionid FROM `t_cmp_dinguser` WHERE corpId = 'dinge6d7d42efe0e4ff3' and  userID IN (57,25,26,27,28,29,30) ;

其实最终是这样的

SELECT unionid FROM `t_cmp_dinguser` WHERE corpId = 'dinge6d7d42efe0e4ff3' and  userID IN ('57,25,26,27,28,29,30') ;

坑你没商量

image.png

方法一(推荐)

package com.zl.zubus.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zl.zubus.model.DingUserDo;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface DingUserMapper extends BaseMapper<DingUserDo> {
    String tableName = "t_cmp_dinguser";

    @Select("<script> " +
            "select unionid from " + tableName + " where corpId = #{companyId} and userID " +
            "in <foreach item='item' index='index' collection='executorIdArr' open='(' separator=',' close=')'> #{item} </foreach> " +
            "</script>")
    List<String> getUnionIdByUserIdAndCompany(String companyId, Integer[] executorIdArr);

}

方法二

整型数组转字符串

  /**
     * [1,2,3] to 1,2,3
     *
     * @return
     */
    public static String intArrToString(Integer[] arr) {
        return StringUtils.join(arr, ",");
    }

QueryWrapper直接上

List<DingUserDo> unionIdList = dingUserMapper.selectList
    (new QueryWrapper<DingUserDo>().eq("corpId",companyId)
     .inSql("userID",result).select("unionId"));

缺点,返回值固定为DingUserDo,使用需要自行转换