MyBatis inserts data in batches and returns the primary key. mybatis returns the primary key.
Many people on the Internet say that MyBatis does not support batch insertion and the primary key is returned. This is a misunderstanding. If you want MyBatis to directly return a list containing the primary key, that is, the return value of the batch insert method in the mapper interface is List <Integer>.
For example, enter the Student Score
Database: mysql
// Incorrect syntax: public List <Integer> batchInsert (List <Student> students );
This idea is wrong. To make it clear, let's first look at how the primary key is returned when a single entry is inserted. below is the official MyBatis documentation.
That is to say, you only need to add useGeneratedKeys = "true" and keyProperty = "id" to the insert tag. The mapper interface writes
public int insert(Student student);
Xml
<insert id="insert" useGeneratedKeys="true" keyProperty="id"> insert into student (name, score) values (#{name}, #{score})</insert>
After running, you will find that the returned value is always 1, that is, the returned value is the number of affected rows. The returned primary key is actually mapped to the id attribute of the student parameter. You only need student. getId () to obtain
Student student = new Student ("James", 77); int line = mapper. insert (student); System. out. println ("affected rows:" + line); System. out. println ("Returned primary key:" + student. getId ());
Running result:
Next we will talk about the same principle of batch insert. The following is the official document. Using foreach for batch insert, the method for returning the primary key is still the same.
Mapper Interface
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>
Test 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 ("affected rows:" + line); for (Student student: students) {System. out. println ("Returned primary key:" + student. getId ());}
Running result
In summary, MyBatis can be inserted in batches and return the primary key. However, the returned primary key is mapped to the parameter id attribute instead of in the return value of the mapper interface (which is a bit difficult. Therefore, the keyProperty value must be consistent with the primary key attribute of the parameter.
Original article, reprinted please indicate the source