aloplop85
aloplop85

Reputation: 922

MyBatis-Spring insert a list of objects and retrieve their new IDs

I am working with MyBatis-Spring and a MySql database. Currently, I am inserting some lists into one of the tables using the following code:

<insert id="insertList" parameterType="java.util.List" useGeneratedKeys="true">
        INSERT INTO myTable (field1, field2, field3)
        VALUES
        <foreach collection="list" item="item" separator=",">
            (#{item.field1}, #{item.field2}, #{item.field3})
        </foreach>
    </insert>

At this point, I would like to return the new IDs generated after inserting the new items without making a new query: SELECT * FROM myTable.

Is this possible? Thanks in advance.

Upvotes: 0

Views: 2288

Answers (1)

Larry.Z
Larry.Z

Reputation: 3724

If the list size is not too large, do loop insert in java code

for(Bean bean : list){
   list.insert(bean);
}

In mapper.xml insert method should add

<selectKey keyProperty="ID" order="AFTER" resultType="java.lang.Integer">
    SELECT LAST_INSERT_ID()
</selectKey>

Upvotes: 1

Related Questions