mybatis mysql 批量insert 返回主鍵


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM