網上有很多人說MyBatis不支持批量插入並且返回主鍵,其實這種說法有一定的誤解,如果你想讓MyBatis直接返回一個包含主鍵的list,即mapper接口中批量插入方法的返回值為List<Integer>,這樣的確是不行的
例如:錄入學生成績
數據庫:mysql
//錯誤的寫法 public List<Integer> batchInsert(List<Student> students);
這種想法是錯誤的,為了把這個錯誤解釋得明白一點,我們還是先看看單條插入的時候是如何返回主鍵的吧,下面是MyBatis官方文檔
也就是說只要在insert標簽里加入useGeneratedKeys="true"和keyProperty="id"即可,mapper接口這樣寫
public int insert(Student student);
xml
<insert id="insert" useGeneratedKeys="true" keyProperty="id"> insert into student (name, score) values (#{name}, #{score}) </insert>
運行之后會發現,返回值始終是1,也就是返回值是受影響的行數。返回的主鍵實際上被映射到了參數student的id屬性中,只需student.getId()即可得到
Student student = new Student("小明", 77); int line = mapper.insert(student); System.out.println("受影響的行數:" + line); System.out.println("返回的主鍵:" + student.getId());
運行結果:
接下來說批量插入,其實一樣的原理,下面是官方文檔,使用foreach批量插入,返回主鍵的方法還是那樣
mapper接口
public int batchInsert(List<Student> students);
xml
<insert id="batchInsert" useGeneratedKeys="true" keyProperty="id"> insert into student (name, score) values <foreach collection="list" item="item" index="index" separator=","> (#{item.name}, #{item.score}) </foreach> </insert>
測試插入
List<Student> students = new ArrayList<Student>(); Student tom = new Student("Tom", 88); Student jerry = new Student("Jerry", 99); students.add(tom); students.add(jerry); int line = mapper.batchInsert(students); System.out.println("受影響的行數:" + line); for (Student student : students) { System.out.println("返回的主鍵:" + student.getId()); }
運行結果
綜上,MyBatis是可以批量插入並返回主鍵的,不過返回的主鍵不是在mapper接口的返回值里面(有點繞,其實很簡單),而是映射到了參數的id屬性里面。因此keyProperty的值必須和參數的主鍵屬性保持一致。
內容轉自 https://www.cnblogs.com/zephyrus/archive/2017/08/21/7403127.html