MYBATIS+MYSQL 批量操作数据库

本文介绍如何通过批量插入、筛选及更新等操作来提高数据库处理效率。包括使用MyBatis进行批量插入、多条件筛选和更新的具体实现方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

一、批量插入:

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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值