Mybatis在插入单条数据的时候有两种方式返回自增主键: mybatis3.3.1支持批量插入后返回主键ID,
首先对于支持自增主键的数据库:useGenerateKeys和keyProperty。
不支持生成自增主键的数据库:<selectKey>。
这里主要说下批量插入数据时如何返回主键ID(注意要将mybatis升到3.3.1)
public class UserInfo { private int userId; private String userName; private StringuserPwd; public long getUserId() { return userId; } public void setUserId(long userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPwd() { return userPwd; } public void setUserPwd(String userPwd) { this.userPwd = userPwd; } }
Dao
public interface UserDao{
int insertTest(List<UserInfo> userInfo);
}
mapper
<insert id="insertTest" parameterType="java.util.List" useGeneratedKeys="true" keyProperty="userId"> insert into t_sys_course (user_name,user_pwd) values <foreach collection="list" item="item" index="index" separator=","> (#{item.userName,jdbcType=VARCHAR},#{item.userPwd,jdbcType=VARCHAR}) </foreach> </insert>
serviceImpl
public List<UserInfo> saveCheckin(List<UserInfo> userInfo) { userDao.insertCheckin(userInfo); return userInfo; }
//返回的对象List里面已经包含主键ID