mybatis获取批量插入的主键自增id
一、写一个实体类
public class UserInfo { private long userId; private String userAccount; private String userPassword; private String userName; private int userStatus; private String userCreateDatetime; private String userRegisterIp; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public long getUserId() { return userId; } public void setUserId(long userId) { this.userId = userId; } public String getUserAccount() { return userAccount; } public void setUserAccount(String userAccount) { this.userAccount = userAccount; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } public int getUserStatus() { return userStatus; } public void setUserStatus(int userStatus) { this.userStatus = userStatus; } public String getUserCreateDatetime() { return userCreateDatetime; } public void setUserCreateDatetime(String userCreateDatetime) { this.userCreateDatetime = userCreateDatetime; } public String getUserRegisterIp() { return userRegisterIp; } public void setUserRegisterIp(String userRegisterIp) { this.userRegisterIp = userRegisterIp; } }
二、插入的mybatis insert语句
<insert id="batchInsert" parameterType="list" keyProperty="userId" keyColumn="user_id" useGeneratedKeys="true"> insert into system_user( user_account, user_password, user_name, user_status, user_create_datetime, user_register_ip ) values <foreach collection="list" item="item" index="index" separator=","> ( #{item.userAccount}, #{item.userPassword}, #{item.userName}, #{item.userStatus}, #{item.userCreateDatetime}, #{item.userRegisterIp} ) </foreach> </insert>
三、dao接口
int batchInsert(List<UserInfo> data);
然后再遍历data list里面的UserInfo实例,发现属性userId已经赋值为自增的id的值
第二种方法,单参数是map的时候。参数不是一个实体。
<!-- 添加 -->
<insert id="insert" parameterType="map" keyProperty="operlog_id" useGeneratedKeys="true">
insert into system_oper_log
(
user_account,
operlog_url,
operlog_status,
operlog_ip,
operlog_exception,
operlog_type,
operlog_before,
operlog_after
)values(
#{user_account},
#{operlog_url},
#{operlog_status},
#{operlog_ip},
#{operlog_exception},
#{operlog_type},
#{operlog_before},
#{operlog_after}
)
</insert>
然后再返回的map参数里面,返现多了一个键,叫做operlog_id