• Mybatis中的foreach


    foreach一共有List,array,Map三种类型的使用场景。
    foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。
        item表示集合中每一个元素进行迭代时的别名,
        index指定一个名字,用于表示在迭代过程中,每次迭代到的位置,
        open表示该语句以什么开始,
        separator表示在每次进行迭代之间以什么符号作为分隔 符,
        close表示以什么结束。
    1.List类型插入:
     
    <insert id="batchInsertClientDeviceList" parameterType="java.util.List" >
        INSERT INTO t_client_device_list (order_no,mac_id,client_code,status,order_time)
        <foreach collection="list" item="item" index="index" separator="union all">
             select #{item.orderNo, jdbcType=VARCHAR},#{item.macId, jdbcType=VARCHAR}
             from dual
        </foreach>
    </insert>
    1.1 List类型查询:
     
    <select id="getClientDeviceList" parameterType="java.util.List" resultType="Device">
        select * from t_devices where id in
        <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
    </select>
    2.参数array类型查询:
     
    <select id="getClientDeviceList" parameterType="java.util.ArrayList" resultType="Device">
         select * from t_devices where id in
         <foreach collection="array" index="index" item="item" open="(" separator="," close=")">
              #{item}
         </foreach>
    </select>   
    3.参数Map类型查询:
     
    map中存放了一个元素key为ids,value为List<String>用于id in的条件
     
    <select id="getClientDeviceList" parameterType="java.util.HashMap" resultType="Device">
        select * from t_devices where mac like "%"#{mac}"%" and id in
        <foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
    </select>
  • 相关阅读:
    Java多线程(二)关于多线程的CPU密集型和IO密集型这件事
    Java 过一下基础
    日历打印用java实现
    DAY8-打卡第八天-2018-1-18
    web-day1-初识标识符
    DAY7-图形界面第一弹-2018-1-17
    四种排序方法用java实现
    DAY6-小变化(java提示框)-2018-1-16
    DAY5-小别-2018-1-15
    DAY4-打卡第四天-2018-1-12
  • 原文地址:https://www.cnblogs.com/lemperor/p/16427234.html
Copyright © 2020-2023  润新知