---
title: "myBatis批量新增__Oracle数据库"
author: "listen-raining"
date: "2014-09-25T23:48:05Z"
tags: []
categories: ["企业架构"]
slug: "mybatis-oracle"
draft: false
lastmod: "2014-09-25T23:49:32Z"
id: 2121972
url: "https://listen-raining.iteye.com/blog/2121972"
---

项目中用MyBatis作为DAO层，用Oracle数据库进行存储。用户需要一个批量新增的功能，刚开始打算用Mybatis的批量新增，调试了好长时间，一直没调试出来，老报错，结果就先采用单条新增进行循环的方式来处理。 这几天有时间，正好又要优化上次的批量功能，就继续来弄一下Mybatis的批量新增功能。

     几经折腾，按照网上说的方法都试了一遍，还是不行，最后发现原来是数据库的问题。MyBatis的批量新增针对Oracle的写法和MySql的不一样。网上大部分都是MySql的写法。

下面贴出针对Oracle进行批量新增的写法。


Service层：

/*
	 * 插入北方来话统计数据(根据集合进行插入)
	 */
	public ServiceResult<BatchDataImportBean> insertTollNorthBatch(Long rateCycle,List list) {
		try {
			batchDataImportDao.insertTollNorthBatch(rateCycle,list);
		} catch (Exception e) {
			userContext.setSuccess(false);
			userContext.setMessage(e.getMessage());
		}
		return userContext;
	}






Dao层：


/*
	 * 在后台批量插入(根据集合来进行插入)
	 */
	public int insertTollNorthBatch(@Param("rateCycle")Long rateCycle, @Param("list")List list);




MyBatis配置：

  <insert id="insertTollNorthBatch" parameterType="map">  
  	 insert into d_toll_north_data_${rateCycle} (RATE_CYCLE_ORG, NF_PROV_ID, NF_AREA_CODE, BF_PROV_ID, BF_AREA_CODE, DURATIONS, FEES)
	 <foreach collection="list" item="item" index="index"  separator="union all">  
       select #{item.rateCycleOrg ,jdbcType=NUMERIC},
        #{item.nfProvId,jdbcType=NUMERIC},
        #{item.nfAreaCode,jdbcType=NUMERIC},
        #{item.bfProvId,jdbcType=NUMERIC},
        #{item.bfAreaCode,jdbcType=NUMERIC},
        #{item.durations,jdbcType=NUMERIC},
        #{item.fees,jdbcType=NUMERIC}  from dual
    </foreach>  
 </insert>  





  具体可以参考：http://www.cnblogs.com/dyllove98/archive/2013/08/03/3235546.html     



  @yongtaixincun.baiyunqu.guangzhou    2014-09-25 23:47