MYBATIS+MYSQL 批量操作数据库

批量操作数据库可减少数据库连接次数,大大提高运行速率。

一、批量插入:

Mapper.xml

 "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>
  

Mapper.java

int insertList(List list);

二、批量筛选
Mapper.xml

<select id="selectByPrimaryKeyList" resultMap="BaseResultMap" >
    select 
    "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

"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>  
     

Mapper.java

Integer updateByList(List<EntryA> list);

你可能感兴趣的:(Web-sql)