how to get each entity's id when batch insert

2019-07-18 12:53发布

问题:

it is know that when we save an entity using mybatis,we can use the keyProperty and useGeneratedKeys attribute to get the entity's id.but how I can get each entity's id when I batch insert entities using just like below:

<insert id="inserts" keyProperty="id" useGeneratedKeys="true">
        insert into t_ext_wk_agent (agent_code,agent_name,agent_type,icon,agent_url_state,description,target,
        state,create_time,modify_time)
        values
        <foreach collection="list" separator="," item="item">
            (#{item.agentCode},#{item.agentName},#{item.agentType},#{item.icon},#{item.agentUrlState},#{item.description},
            #{item.target},#{item.state},#{item.createTime},#{item.modifyTime})
        </foreach> 
    </insert>

回答1:

I have just posted a related answer here.

Just execute a simple Insert statement in a Java Foreach loop instead of iterating over collection in Mybatis XML. The most important thing is the session Executor type (REUSE or BATCH). You then come back to the simple insert / get generated key case