方法一:使用 Insert All into 实现
1.创建实体类(DemoBean)方便处理数据
public class DemoBean { private String demo1; private String demo2; private String demo3; private String demo4; public String getDemo1() { return demo1; } public void setDemo1(String demo1) { this.demo1 = demo1; } public String getDemo2() { return demo2; } public void setDemo2(String demo2) { this.demo2 = demo2; } public String getDemo3() { return demo3; } public void setDemo3(String demo3) { this.demo3 = demo3; } public String getDemo4() { return demo4; } public void setDemo4(String demo4) { this.demo4 = demo4; } }
2.mapper 中的批量插入接口方法
/** * 批量插入数据 入表(batch_demo) * @param list */ @Insert({"<script>" , "INSERT ALL ", "<foreach collection='list' item='element' index='index' separator=''>" , "INTO batch_demo(demo1,demo2,demo3,demo3,demo4) ", "VALUES(", "#{element.demo1,jdbcType=VARCHAR},", "#{element.demo2,jdbcType=VARCHAR},", "#{element.demo3,jdbcType=VARCHAR},", "#{element.demo4,jdbcType=VARCHAR})", "</foreach>", "SELECT * FROM dual", "</script>"}) void batchAddDemo(@Param("list") List<DemoBean> list);
3.调用即可
方法二:使用 insert into ... select ... from dual 实现;
相较于方法一效率快点
mapper 中的批量插入接口方法
/** * 批量插入数据 入表(batch_demo) * @param list */ @Insert({"<script>" , "INSERT INTO batch_demo(demo1,demo2,demo3,demo3,demo4) (", "<foreach collection='list' item='element' index='index' separator='union all'>" , " (select", "#{element.demo1,jdbcType=VARCHAR},", "#{element.demo2,jdbcType=VARCHAR},", "#{element.demo3,jdbcType=VARCHAR},", "#{element.demo4,jdbcType=VARCHAR}", "from dual)" "</foreach>", ")", "</script>"}) void batchAddDemo(@Param("list") List<DemoBean> list);