mybatis mysql 批量insert 返回主鍵

From: https://www.cnblogs.com/xiao-lei/p/6809884.htmlhtml

Mybatis在插入單條數據的時候有兩種方式返回自增主鍵:    mybatis3.3.1支持批量插入後返回主鍵ID,java

首先對於支持自增主鍵的數據庫:useGenerateKeys和keyProperty。數據庫

不支持生成自增主鍵的數據庫:<selectKey>。mybatis

這裏主要說下批量插入數據時如何返回主鍵ID(注意要將mybatis升到3.3.1)app

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 post

1
public interface UserDao{
1
int insertTest(List<UserInfo> userInfo);
1
}<br>

  

mapperthis

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 >

serviceImplspa

1
2
3
4
public  List<UserInfo> saveCheckin(List<UserInfo> userInfo) {
         userDao.insertCheckin(userInfo);
         return userInfo;
     } //返回的對象List裏面已經包含主鍵ID
相關文章
相關標籤/搜索