mybatis中foreach的应用

516 阅读1分钟

官方文档中的用法

中文官方文档连接:mybatis.org/mybatis-3/z…

官方介绍

将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。 当使用可迭代对象或者数组时,index是当前迭代的序号,item的值是本次迭代获取到的元素。 当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。

常用代码举例

<select id="selectPostIn" resultType="domain.blog.Post">
  SELECT *
  FROM POST P
  <where>
    <foreach item="item" index="index" collection="list"
        open="ID in (" separator="," close=")" nullable="true">
          #{item}
    </foreach>
  </where>
</select>

上述代码解释

<select id="selectPostIn" resultType="domain.blog.Post"> id="selectPostIn"--需要对应dao接口的方法名resultType="domain.blog.Post"--返回结果为Post对象

SELECT * FROM POST P <where> <foreach item="item" index="index" collection="list" open="ID in (" separator="," close=")" nullable="true"> #{item} </foreach> </where>
相当于 SELECT * FROM POST P where ID in (item1,item2,item3...) (item1,item2,item3...)指的是list中的所有元素

提升:如何传入一个int型的值以及一个数组呢

dao层对应的方法--com.kkk.mapper.UserDao:

int save2(@Param("roleIds")Long[] roleIds,@Param("userId") Long userId);
//首先明确@Param是为SQL语句中参数赋值而服务的。
//@Param的作用就是给参数命名,比如在mapper里面某方法A(int id),当添加注解后A(@Param("userId") int id),也就是说外部想要取出传入的id值,只需要取它的参数名userId就可以了。将参数值传如SQL语句中,通过#{userId}进行取值给SQL的参数赋值。

sqlMapper-user.xml对应的sql语句:

<mapper namespace="com.kkk.mapper.UserDao">
    <insert id="save2" >
        insert into sys_user_role(userId,roleId)
        values
            <foreach collection="roleIds"  item="roleId" separator=",">
                (#{userId},#{roleId})
            </foreach>
    </insert>
</mapper>

collection就传入@Param("roleIds")中对应的参数名即可--collection="roleIds"