Mybaits insertion summary and mybaits insertion Summary
When we insert data in batches, we need to obtain the id of the inserted data.
In this way:
<insert id="insertUser" parameterType="gys.entity.User" keyProperty="userId" useGeneratedKeys="true"> INSERT INTO `user` (userName) VALUES (#{userName}) </insert>
This is okay.
But sometimes it involves batch inserts and obtains the inserted id.
Write as follows:
<insert id="insertUserBatch1" keyProperty="userId" useGeneratedKeys="true"> INSERT INTO `user` (userName) VALUES <foreach collection="list" separator="," item="item"> (#{item.userName}) </foreach> </insert>
In this way, an exception occurs.
This is because the version of mybatis you are using is too low. For example, I am using version 3.2.2, which is a bug in mybatis.
If you change to 3.4.4, there will be no problem.
An exception will be reported when the preceding SQL statement is written in another way (insert is surrounded by foreach)
For example:
<insert id="insertUserBatch2"> <foreach collection="list" separator=";" item="item"> INSERT INTO `user` (userName) VALUES (#{item.userName}) </foreach> </insert>
In the same way, batch update of update also has this problem.
<update id="updateUserBatch"> <foreach collection="list" item="item" separator=";"> update `user` set userName=#{item.userName} where userId=#{item.userId} </foreach> </update>
This is because mybatis can only execute one SQL statement by default,
You can add parameters when linking the path to execute multiple SQL statements.AllowMultiQueries = true
Jdbc: mysql: // 127.0.0.1: 3306/book? AllowMultiQueries = true