1. 程式人生 > >MYBATIS+MYSQL 批量操作資料庫

MYBATIS+MYSQL 批量操作資料庫

批量操作資料庫可減少資料庫連線次數,大大提高執行速率。

一、批量插入:

Mapper.xml

 <insert id="insertList" useGeneratedKeys="true" parameterType="java.util.List" >
    insert into tableA (parent_category, category, cate_type, parent_cate_id, cate_id)
    values
    <foreach collection="list" item="item" index="index" separator=","
> (#{item.parentCategory},#{item.category},#{item.cateType}, #{item.parentCateId},#{item.cateId}) </foreach> </insert>

Mapper.java

int insertList(List<EntryA> list);

二、批量篩選
Mapper.xml

<select id="selectByPrimaryKeyList" resultMap="BaseResultMap" >
    select
<include refid="Base_Column_List" /> from case_description where id in( <foreach item="item" index="index" collection="list" separator=","> #{item} </foreach>) </select>

Mapper.java

List<BaseResultMap> selectByPrimaryKeyList(List<Integer>
list);

三、多引數批量篩選
Mapper.xml

<select id="selectByMap" parameterType="java.util.Map"  resultType="java.lang.Integer">
    SELECT desc_id from tableA
    where 
    subtask_id=#{subTaskId,jdbcType=INTEGER}
    and
    desc_id in(
    <foreach collection="list" item="item" index="index" separator=",">
        #{item}
    </foreach>
    )
  </select>

Mapper.java

List<Integer> selectByMap(Map<String, Object> map);

Service略
在Controller中組裝Map

Map<String, Object> paramMap = new LinkedHashMap<String, Object>();
paramMap.put("subTaskId", subtaskid);
paramMap.put("list", idList);

四、批量更新
Mapper.xml

<update id="updateByList"  parameterType="java.util.List">  
     <foreach collection="list" item="item" index="index" open="" close="" separator=";">  
         update tableA   
                <set>  
                  cate_id=#{item.cateId}
                </set>  
                where app_id = #{item.appId}
      </foreach>  
    </update> 

Mapper.java

Integer updateByList(List<EntryA> list);