MyBatis 循环 Foreach

SegmentFault 思否 · · 1200 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

MyBatis 循环 Foreach

拾柒_

Mybatis之foreach用法----List、Array、Map三种类型遍历

原文地址

在mybatis的xml文件中构建动态sql语句时,经常会用到标签遍历查询条件。特此记录下不同情况下书写方式!-------仅供大家参考------

1. foreach元素的属性

  • collection: 需做foreach(遍历)的对象,作为入参时,list、array对象时,collection属性值分别默认用"list"、"array"代替,Map对象没有默认的属性值。但是,在作为入参时可以使用@Param(“keyName”)注解来设置自定义collection属性值,设置keyName后,list、array会失效;
  • item: 集合元素迭代时的别名称,该参数为必选项;
  • index: 在list、array中,index为元素的序号索引。但是在Map中,index为遍历元素的key值,该参数为可选项;
  • open: 遍历集合时的开始符号,通常与close=")"搭配使用。使用场景IN(),values()时,该参数为可选项;
  • separator: 元素之间的分隔符,类比在IN()的时候,separator=",",最终所有遍历的元素将会以设定的(,)逗号符号隔开,该参数为可选项;
  • close: 遍历集合时的结束符号,通常与open="("搭配使用,该参数为可选项;

2.foreach时,collection属性值的三种情况:

  • 如果传入的参数类型为List时,collection的默认属性值为list,同样可以使用@Param注解自定义keyName;
  • 如果传入的参数类型为array时,collection的默认属性值为array,同样可以使用@Param注解自定义keyName;
  • 如果传入的参数类型为Map时,collection的属性值可为三种情况:(1.遍历map.keys;2.遍历map.values;3.遍历map.entrySet()),稍后会在代码中示例;

3.代码示例:

3.1 collection属性值类型为List:

Mapper接口定义的方法:UserList为模拟返回的数据对象

List<UserList> getUserInfo(@Param("userName") List<String> userName);

Mapper.xml 动态sql构建,Mapper接口的方法名和xml文件的id值,必须一一对应,否则会报错:
-----建议做if test="xxxx !=null and xxxx.size()>0"的校验,比较严谨。array为.length();

 <select id="getUserInfo" resultType="com.test.UserList">
          SELECT
            *
          FROM user_info
            where
            <if test="userName!= null and userName.size() >0">
                USERNAME IN
                <foreach collection="userName" item="value" separator="," open="(" close=")">
                    #{value}
                </foreach>
            </if>
</select>

3.2 collection属性值类型为Array:
Mapper接口定义的方法:UserList为模拟返回的数据对象

List<UserList> getUserInfo(@Param("userName") String[] userName);

Mapper.xml 动态sql构建,Mapper接口的方法名和xml文件的id值,必须一一对应,否则会报错:
-----建议做if test="xxxx !=null and xxxx.length()>0"的校验,比较严谨。

     <select id="getUserInfo" resultType="com.test.UserList">
            SELECT
                *
            FROM user_info
            where
            <if test="userName!= null and userName.length() >0">
                USERNAME IN
                <foreach collection="userName" item="value" separator="," open="(" close=")">
                    #{value}
                </foreach>
            </if>
     </select>

3.3 collection属性值类型为Map:
近期在项目中,遇到这样一个需求,sql查询的条件之一是两个字段确定唯一的一个人,并且条件可能是多个人或者一个人。以往开发中,我们可能遇到只有一个字段的集合或者数组。进入正题:
接收前台传递的List,组装查询条件。其实也可以直接传一个List对象集合,但是实际开发中,List中的每一个对象包含了几十个字段,而我们只需要其中的两个,所以我选择数据组装传递。
实现类处理:

  Map<String, String> patientMap = userList.stream().filter(item -> StringUtils.hasText(item.getUserName()) &&
                    StringUtils.hasText(item.getAge())).collect(Collectors.toMap(UserList::getUserName, UserList::getAge));
                    

Mapper接口定义的方法:UserList为模拟返回的数据对象

List<UserList> getUserInfo(@Param("user") Map<String,String> user);

Mapper.xml 动态sql构建,Mapper接口的方法名和xml文件的id值,必须一一对应,否则会报错:
-----建议做 if test="xxxx !=null and xxxx.size()>0"的校验,比较严谨。
第一种:获取Map的键值对,多字段组合条件情况下,一定要注意书写格式:括号()

eg: SELECT * FROM user_info WHERE (USERNAME,AGE) IN (('张三','26'),('李四','58'),('王五','27'),......);
 <select id="getUserInfo" resultType="com.test.UserList">
            SELECT
                *
            FROM user_info
            where
            <if test="user!= null and user.size() >0">
                (USERNAME,AGE) IN
                <foreach collection="user.entrySet()" item="value" index="key" separator="," open="(" close=")">
                    (#{key},#{value})
                </foreach>
            </if>
</select>

第二种:参数Map类型,只需要获取key值或者value值
key:

 <select id="getUserInfo" resultType="com.test.UserList">
            SELECT
                *
            FROM user_info
            where
            <if test="user!= null and user.size() >0">
                (USERNAME) IN
                <foreach collection="user.keys" item="key"  separator="," open="(" close=")">
                    #{key}
                </foreach>
            </if>
</select>

value:

     <select id="getUserInfo" resultType="com.test.UserList">
            SELECT
                *
            FROM user_info
            where
            <if test="user!= null and user.size() >0">
                (USERNAME) IN
                <foreach collection="user.values" item="value"  separator="," open="(" close=")">
                    #{key}
                </foreach>
            </if>
</select>
  1. 一个方法实现插入或更新,必须有主键

https://blog.csdn.net/q957967519/article/details/88669552

<insert id="updateBatch" parameterType="java.util.List">
        insert into standard_relation(id,relation_type, standard_from_uuid,
        standard_to_uuid, relation_score, stat,
        last_process_id, is_deleted, gmt_created,
        gmt_modified,relation_desc)VALUES
        <foreach collection="list" item="item" index="index" separator=",">
            (#{item.id,jdbcType=BIGINT},#{item.relationType,jdbcType=VARCHAR}, #{item.standardFromUuid,jdbcType=VARCHAR},
            #{item.standardToUuid,jdbcType=VARCHAR}, #{item.relationScore,jdbcType=DECIMAL}, #{item.stat,jdbcType=TINYINT},
            #{item.lastProcessId,jdbcType=BIGINT}, #{item.isDeleted,jdbcType=TINYINT}, #{item.gmtCreated,jdbcType=TIMESTAMP},
            #{item.gmtModified,jdbcType=TIMESTAMP},#{item.relationDesc,jdbcType=VARCHAR})
        </foreach>
        ON DUPLICATE KEY UPDATE
        id=VALUES(id),relation_type = VALUES(relation_type),standard_from_uuid = VALUES(standard_from_uuid),standard_to_uuid = VALUES(standard_to_uuid),
        relation_score = VALUES(relation_score),stat = VALUES(stat),last_process_id = VALUES(last_process_id),
        is_deleted = VALUES(is_deleted),gmt_created = VALUES(gmt_created),
        gmt_modified = VALUES(gmt_modified),relation_desc = VALUES(relation_desc)
    </insert>
阅读 10.1k

本文来自:SegmentFault 思否

感谢作者:SegmentFault 思否

查看原文:MyBatis 循环 Foreach

1200 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传