zoukankan      html  css  js  c++  java
  • mybatis where 中in的使用

    当我们使用mybatis时,在where中会用到 in 如:

    where name in ('Jana','Tom');

    我们可以在sql中直接写 name in ('Jana','Tom') 或者 name in (${names})  (备注:String names = "'Jana','Tom'"; 使用$时会引起sql注入安全问题)

    但是我们无法在sql中直接写 name in (#{names});

    会报参数个数错误,因为'Jana','Tom'会被解析成两个传参

    String[] names={"Jana","Tom"};

    此时要用foreach函数:

    name in
    <foreach collection="names" item="name" index="index" open="(" close=")" separator=",">
        #{name}
    </foreach>

    解析为:

    name in (?,?),然后利用names传入参数

    关于参数的形式,可以是数组形式可以是List形式:

    1.当只传入names变量时,collection必须指定array或list类型:

    public List<User> findInfos(String[] names);
    
    <select id="findInfos" resultMap="UserMap">
        SELECT * FROM t_user
        WHERE id IN
        <foreach collection="array" item="name" index="index" open="(" close=")" separator=",">
          #{name}
        </foreach>
    </select>
    public List<User> findInfos(List<String> names);
    
    <select id="findInfos" resultMap="UserMap">
        SELECT * FROM t_user
        WHERE id IN
        <foreach collection="list" item="name" index="index" open="(" close=")" separator=",">
          #{name}
        </foreach>
    </select>

     注意:array传入的时候parameterType可以是"Integer[]" ,可以是"int[]",但不可以是"String[]"

    报错 Could not resolve type alias 'string[]'. Cannot find class: string[]

    2.当有其他变量时,利用map传入参数集时,可以直接将变量写在collection中

    Map<String,Object> params = new HashMap<>();
    params.put("class",class);
    params.put("names",names);
    <select id="findInfos" resultMap="UserMap">
        SELECT * FROM t_user
        WHERE id IN
        <foreach collection="names" item="name" index="index" open="(" close=")" separator=",">
          #{name}
        </foreach>
    </select>
  • 相关阅读:
    declaration may not appear after executable statement in block
    linux 管道通信
    用c语言创建双向环形链表
    bash: ./LM35_make_fs: Permission denied 解决办法
    sunzl is not in the sudoers file.This incident will be reported
    基于嵌入式linux路由转发功能的实现
    关于eth0 eth0:1 和eth0.1关系介绍
    软重启
    Android中Serializable和Parcelable序列化对象详解
    公共技术点(Android 动画基础)
  • 原文地址:https://www.cnblogs.com/blog-yuesheng521/p/11097222.html
Copyright © 2011-2022 走看看