Mybatis批量插入返回自增主鍵(轉)


我們都知道Mybatis在插入單條數據的時候有兩種方式返回自增主鍵:


1、對於支持生成自增主鍵的數據庫:useGenerateKeys和keyProperty。

2、不支持生成自增主鍵的數據庫:<selectKey>。


但是怎對批量插入數據返回自增主鍵的解決方式網上看到的還是比較少,至少百度的結果比較少。


Mybatis官網資料提供如下:


First, if your database supports auto-generated key fields (e.g. MySQL and SQL Server), then you can simply set useGeneratedKeys="true" and set the Authortable above had used an auto-generated column type for the id, the statement would be modified as follows:

 
         
1 <insert id="insertAuthor" useGeneratedKeys="true"
2     keyProperty="id">
3   insert into Author (username,password,email,bio)
4   values (#{username},#{password},#{email},#{bio})
5 </insert>
 

If your database also supports multi-row insert, you can pass a list or an array of 

1 <insert id="insertAuthor" useGeneratedKeys="true"
2     keyProperty="id">
3   insert into Author (username, password, email, bio) values
4   <foreach item="item" collection="list" separator=",">
5     (#{item.username}, #{item.password}, #{item.email}, #{item.bio})
6   </foreach>
7 </insert>

 

從官網資料可以看出Mybatis是支持批量插入時返回自增主鍵的。(百度上說不支持的,多打臉 開玩笑的)


但是在本地測試的時候使用上述方式確實不能返回自增id,而且還報錯(不認識keyProperty中指定的Id屬性),然后在網上找相關資料。終於在Stackoverflow上面找到了一些信息。


解決辦法:

1、升級Mybatis版本到3.3.1。

2、在Dao中不能使用@param注解。

3、Mapper.xml中使用list變量接受Dao中的集合。


參考地址:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM