Mybatis批量insert,返回主键id列表

 

1.第一种方式:

    <insert id="insertStudents" useGeneratedKeys="true" keyProperty="studId" 
    parameterType="java.util.ArrayList">
		INSERT INTO
		STUDENTS(STUD_ID, NAME, EMAIL, DOB, PHONE)
		VALUES
	<foreach collection="list" item="item" index="index" separator=","> 
        	(#{item.studId},#{item.name},#{item.email},#{item.dob}, #{item.phone}) 
    	</foreach> 
	</insert>

Mapper.xml中keyProperty和parameterType属性之间的关系

useGeneratedKeys="true" keyProperty="studId" parameterType="Student"

上述xml配置,含义为,属性studId是参数类型Student对象的主键属性。毫无疑问,Student对象中有studId属性。

useGeneratedKeys="true" keyProperty="studId" parameterType="java.util.ArrayList"

含义为:ArrayList集合中的元素的studId属性。所以,keyProperty和parameterType之间的关系,有时是直接关系,有时是间接关系。明白这个道理之后,我们就可以开始进一步阅读源码了。

SimpleExecutor和ReuseExecutor可以正确返回foreach批量插入后的id列表

配置Executor

<setting name="defaultExecutorType" value="SIMPLE" />

 2.第二种方式:使用注解

public interface UserMapper
{
    @Insert("insert into tbl_user (name, age) values (#{name}, #{age})")
    @Options(useGeneratedKeys=true, keyProperty="userId", keyColumn="id")
    void insertUser(User user);
} 

 

转载于:https://my.oschina.net/u/3644969/blog/1858257

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值