Mybatis批量添加实现

10 篇文章 1 订阅
6 篇文章 0 订阅

一、引言

Mybatis可以直接传入一个集合,通过标签将集合中的数据遍历出来实现批量新增

不同的数据库批量新增有区别,如下实现两种方式的批量新增

二、实现


2.1映射文件

 <!--单条插入  -->
  <insert id="insertOne" parameterType="com.imooc.bean.CommandContent">
  	insert command_content(content,command_id) values(#{content},#{commandId))
  </insert>
  
  <!-- mysql 批量添加
  	批量插入的时候,只要在values后边拼接多个需要插入的值便可
  	insert command_content(content,command_id) values(?,?),(?,?),(?,?)
  -->
  <insert id="insertBatchForMysql" parameterType="java.util.List">
  	insert command_content(content,command_id) values
  	<foreach collection="list" item="item" separator=",">
  		(#{content},#{commandId})
  	</foreach>
  </insert>
  
  <!-- oracle批量增加实现 
  	oracle批量插入的时候,可以使用子查询的方式插入
  		insert command_content(content,commandId) values
  		(
  			select ?,? from dual union all
  			select ?,? from dual union all
  			select ?,? from dual union all
  		)
  		
  		select ?,? from dual union all 执行结果就是"?"的值
  -->
    <insert id="insertBatchForOracle" parameterType="java.util.List">
  	insert command_content(content,commandId) values
  	<foreach collection="list" item="item" separator="union all">
  		select 
  		#{item.id,jdbcType=VARCHAR},
  		#{item.commandId,jdbcType=VARCHAR}
  		from dual
  	</foreach>
  </insert>

2.2接口

package com.imooc.dao;

import java.util.List;

import com.imooc.bean.CommandContent;

public interface ICommandContentDao {
	/*
	 * 单条插入
	 * */
	public void insertOne(CommandContent commandContent);
	
	/*
	 * oracle批量插入
	 * */
	public void insertBatchForOracle(List<CommandContent> commandContentList);
	
	/*
	 * mysql批量插入
	 * */
	public void insertBatchForMysql(List<CommandContent> commandContentList);
}


3.3批量添加实现

package com.imooc.dao;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.imooc.bean.CommandContent;
import com.imooc.bean.Message;
import com.imooc.db.DBAccess;

public class CommandContentDao {

	DBAccess dbAccess = new DBAccess();
	
	//批量新增
	public void insertBatch(List<CommandContent> contentList) throws Exception{
		SqlSession session = null;
		try {
			session = dbAccess.getSqlSession();
			/*for(CommandContent commandContent:contentList){ //效率比较低,在jdbc实现的时候是使用batch
				ICommandContentDao iCommandContentDao = session.getMapper(ICommandContentDao.class);
				iCommandContentDao.insertOne(commandContent);
			}*/
			//高效率的,直接传入list
			ICommandContentDao iCommandContentDao = session.getMapper(ICommandContentDao.class);
			iCommandContentDao.insertBatchForOracle(contentList);
			session.commit();
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}
}

注:本案例思想由慕课网提供

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值