Home > Database > Mysql Tutorial > body text

How to operate mybaits batch insert

PHP中文网
Release: 2017-06-21 16:04:12
Original
1301 people have browsed it

When we insert data in batches, we need to get the id of the inserted data.

This way:

 <insert id="insertUser" parameterType="gys.entity.User" keyProperty="userId" useGeneratedKeys="true">INSERT INTO `user`
        (userName)
        VALUES
        (#{userName})</insert>
Copy after login

This is no problem.

But sometimes it involves batch insertion, and to get the inserted id

write like this:

<insert id="insertUserBatch1" keyProperty="userId" useGeneratedKeys="true">INSERT INTO `user`
        (userName)
        VALUES<foreach collection="list" separator="," item="item">(#{item.userName})</foreach></insert>
Copy after login

An exception will occur after running like this.

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 switch to version 3.4.4, there will be no problem.

If the above sql statement is written differently, an exception will be reported again (enclose insert in foreach)

For example:

<insert id="insertUserBatch2"> <foreach collection="list" separator=";" item="item"> INSERT INTO `user`
                (userName)
            VALUES
                (#{item.userName})         </foreach></insert>
Copy after login

Similarly, there is also update Batch 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>
Copy after login

This is because mybatis can only execute one sql statement by default.

You can add parameters when linking the path. Multiple sql statements were executed.allowMultiQueries=true

The above is the detailed content of How to operate mybaits batch insert. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template