参考文档:

mybatis之foreach使用方式

第一种方式-mapper接口没有使用@Param("keyName")来设置键:

mybatis更新sql语句:

<update id="updateUsers" parameterType="Map">
update user
set update_time  = ${updateDate},
    opetation_id = ${updateUser}
where id in
<foreach collection="userIds" item="id" separator="," open="(" close=")">
  ${id}
</foreach>
</update>

在mapper接口没有使用@Param("keyName")来设置键的情况下,foreach标签的collection取的是传递过来的map中的key值;若是传递的是List集合,mybatis底层默认构建的map的key值为“list”;若传递的是array数组,mybatis底层默认构建的map的key为“array”。

传入map参数类型:

map的value类型最好是object,比如limit语句使用的参数为int类型,此时value类型是object,使用#{}方式则会传入int类型,否则sql会报错。

HashMap<String,Object> map = new HashMap<String, Object>();
map.put("updateDate", "2021-1-1");
map.put("updateUser", "3");
String[] ids = {"1","2"};
map.put("userIds", ids );

第一种方式-mapper接口使用@Param("keyName")来设置键:

mapper接口:

List<User> findUsers(@Param("params") Map<String, Object> map);

mybatis查询sql语句:

<select id="findUsers" parameterType="Map" resultType="cn.com.xx.entity.User">
select * from user
        where 1=1 
        <if test="params.userName!=null and params.userName!=''">
            and user_name like '%${params.userName}%'
        </if>
        <if test="params.userIds!=null and params.userIds.size() > 0">
           and id in
        <foreach collection="params.userIds" item="id" separator="," open="(" close=")">
              ${id}
        </foreach>
        </if>
</select >

传入map参数类型:

map的value类型最好是object,比如limit语句使用的参数为int类型,此时value类型是object,使用#{}方式则会传入int类型,否则sql会报错。

HashMap<String,Object> map = new HashMap<String, Object>();
map.put("userName", "张三");
String[] ids = {"1","2"};
map.put("userIds", ids );
posted on 2021-10-13 10:49  哑吧  阅读(3001)  评论(0编辑  收藏  举报