As we all know, there are two ways to return a MyBatis key when inserting a single piece of data:
1. For databases that support the generation of self-added primary keys: Usegeneratekeys and Keyproperty.
2, does not support the generation of:<selectkey> primary key database.
But how to bulk insert data back to the solution of the primary key to see the online or relatively few, at least Baidu's results are less.
MyBatis official website information provided as follows:
The If your database supports auto-generated key fields (e.g. MySQL and SQL Server), then you can simply set Usegenerat Edkeys= "true" and set the Keyproperty to the target property and you are done. For example, if the authortable above had used. auto-generated column type for the ID, the statement would is modified a S follows:
<insert id= "Insertauthor" usegeneratedkeys= "true"
keyproperty= "id" >
INSERT INTO Author (username, Password,email,bio)
values (#{username},#{password},#{email},#{bio})
</insert>
If your database also supports multi-row INSERT, can pass a list or an array of Authors and retrieve the Auto-generate D keys.
<insert id= "Insertauthor" usegeneratedkeys= "true"
keyproperty= "id" >
INSERT INTO Author (username, Password, email, bio) values
<foreach item= "item" collection= "List" separator= "," >
(#{item.username}, # {Item.password}, #{item.email}, #{item.bio})
</foreach>
</insert>
From the official website data can be seen MyBatis is to support bulk inserts when the return of the primary key. (Baidu said no support, more face joking)
However, using this method in the local test does not return the ID, and also reported the error (not knowing the id attribute specified in keyproperty), and then find the relevant information on the Internet. Finally found some information on the StackOverflow.
Solution:
1, upgrade MyBatis version to 3.3.1.
2. @param annotations cannot be used in DAO.
3, use the list variable in Mapper.xml to accept the collection in DAO.
Reference Address:
Http://stackoverflow.com/questions/18566342/mybatis-use-generated-keys-for-batch-insert http:// Stackoverflow.com/questions/28453475/mybatis-getting-id-from-inserted-array-of-object-returns-error https:// github.com/mybatis/mybatis-3/pull/324 http://stackoverflow.com/questions/28453475/ mybatis-getting-id-from-inserted-array-of-object-returns-error# https://github.com/abel533/mybatis-3/blob/ Master/src/main/java/org/apache/ibatis/executor/keygen/jdbc3keygenerator.java