MyBatis多参数批量操做

问题描述:有时候进行批量操做的时候,须要携带条件等信息,这个时候循环的部分就须要改变一下写法,不然会报异常,这里直接列出解决方案数组

1. 普通多参数传递:

dao接口:app

// xml中接收参数的顺序要与这里保持一致
User selectUser(String classId, String userId);

mapper.xml:ide

<select id="selectUser" resultMap="BaseResultMap">  
    select  *  from user   where class_id = #{0} and user_id = #{1}  
</select>

2.带数组或集合的参数传递

2.1 方式一

dao接口:code

// xml中接收参数的顺序要与这里保持一致
TestInfo selectAll(String classId, String[] userIds);

mapper.xml,注意foreach中collection的值"userIds"要与Dao中第二个参数的名称一致,且顺序也一致:xml

<select id="selectAll" resultMap="BaseResultMap">
    select * from
        test_info 
    where
        class_id = #{classId,jdbcType=VARCHAR}
        and user_id in
        <foreach collection="userIds" item="item" index="index" open="(" separator="," close=")">
            #{item}
        </foreach>
</select>

如图:blog

MyBatis多参数批量操做

2.2 方式二

2.2.1 service接口:接口

...
public TestInfo selectAll(String classId, String[] userIds) {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("classId", classId);
    map.put("userIds", userIds);
    // 调用dao
    userInfoDao.selectAll(map);
    ...
}

2.2.2 dao接口:get

TestInfo selectAll(Map<String, Object> map);

2.2.3 mapper.xml,其中的参数名称要与map中的key一致:it

<select id="selectAll" resultMap="BaseResultMap">
    select * from
        test_info 
    where
        class_id = #{classId,jdbcType=VARCHAR}
        and user_id in
        <foreach collection="userIds" item="item" index="index" open="(" separator="," close=")">
            #{item}
        </foreach>
</select>

3. 扩展

MyBatis批量操做io

相关文章
相关标签/搜索