來看看正確執行的代碼:
<insert id="insertBatchXyFalse" parameterType="java.util.List">INSERT INTO JM_ZYK_XY_FALSE(ID, GCXH, HPHM, HPZL, HPYS, CSYS, CLXH, CLLX, CLPP, JDCSYR, SJHM, KKBH, FXLX, CDH, BDLJ, TP1, TP2, TP3, GCSJ, XZQH, CZR, XXLY, RKSJ, ZT, BY1, BY2, BY3)<foreach close=")" collection="list" item="item" index="index" open="(" separator="union"> select #{item.id,jdbcType=VARCHAR}, #{item.gcxh,jdbcType=VARCHAR},#{item.hphm,jdbcType=VARCHAR},#{item.hpzl,jdbcType=VARCHAR},#{item.hpys,jdbcType=VARCHAR},#{item.csys,jdbcType=VARCHAR},#{item.clxh,jdbcType=VARCHAR},#{item.cllx,jdbcType=VARCHAR},#{item.clpp,jdbcType=VARCHAR},#{item.jdcsyr,jdbcType=VARCHAR},#{item.sjhm,jdbcType=VARCHAR},#{item.kkbh,jdbcType=VARCHAR},#{item.fxlx,jdbcType=VARCHAR},#{item.cdh,jdbcType=INTEGER},#{item.bdlj,jdbcType=VARCHAR},#{item.tp1,jdbcType=VARCHAR},#{item.tp2,jdbcType=VARCHAR},#{item.tp3,jdbcType=VARCHAR},#{item.gcsj,javaType=String, jdbcType=TIMESTAMP},#{item.xzqh,jdbcType=VARCHAR},#{item.czr,jdbcType=VARCHAR},#{item.xxly,jdbcType=VARCHAR},sysdate,#{item.zt,jdbcType=INTEGER},#{item.by1,jdbcType=VARCHAR},#{item.by2,jdbcType=VARCHAR},#{item.by3,jdbcType=VARCHAR} from dual </foreach></insert>
這裡要注意對null值的處理,在mybatis-config.xml裡面配置:
<settings> <setting name="jdbcTypeForNull" value="NULL"/> </settings>
這裡要注意settings的位置,要放在properties之後,typeAliases之前.
然後寫一個單元測試:
@Testpublic void insertBatchXyFalseTest(){List<VehicleXyFalse> vflist = new ArrayList<VehicleXyFalse> ();for(int i = 0; i < 2000; i++){VehicleXyFalse vf = new VehicleXyFalse("1001"+i,"2001"+i,"湘AD1234","02","4301","1");vflist.add(vf);}IXyZykService xyZykService = (XyZykService)context.getBean("xyZykService");try {xyZykService.insertBatchXyFalse(vflist);} catch (ServiceException e) {e.printStackTrace();}}
測試通過,資料庫成功插入2000條資料.
但是這裡有一個坑,如果我們將一次插入的資料量升到5000,就會報錯"Cause: java.sql.SQLSyntaxErrorException: ORA-01745: 無效的主機/綁定變數名".網上說是語法錯誤.但是實質上是sql太長了,sql語句是有長度限制的.oracle文檔說是64KB,實際上會與很多環境有關:資料庫配置,磁碟空間,記憶體多少等等.
只能分批寫入了,這樣效能也會高些.