Mybaits insertion summary and mybaits insertion Summary

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.