Mybatis在插入单条数据的时候有两种方式返回自增主键: mybatis3.3.1支持批量插入后返回主键ID,
首先对于支持自增主键的数据库:useGenerateKeys和keyProperty。
不支持生成自增主键的数据库:<selectKey>。
这里主要说下批量插入数据时如何返回主键ID(注意要将mybatis升到3.3.1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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
1 | public interface UserDao{ |
1 | int insertTest(List<UserInfo> userInfo); } |
|
mapper
1 2 3 4 5 6 7 8 | < 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
1 2 3 4 | public List<UserInfo> saveCheckin(List<UserInfo> userInfo) { userDao.insertCheckin(userInfo); return userInfo; }<br> //返回的对象List里面已经包含主键ID |