Mybatis+Mysql 返回主鍵的值


需求:使用MyBatis往MySQL數據庫中插入一條記錄后,需要返回該條記錄的自增主鍵值。

 

方法:在mapper中指定keyProperty屬性,示例如下:

Xml代碼 復制代碼  收藏代碼
  1. <insert id="insertAndGetId" useGeneratedKeys="true" keyProperty="userId" parameterType="com.chenzhou.mybatis.User">  
  2.     insert into user(userName,password,comment)  
  3.     values(#{userName},#{password},#{comment})  
  4. </insert>  
<insert id="insertAndGetId" useGeneratedKeys="true" keyProperty="userId" parameterType="com.chenzhou.mybatis.User">
	insert into user(userName,password,comment)
	values(#{userName},#{password},#{comment})
</insert>

 如上所示,我們在insert中指定了keyProperty="userId",其中userId代表插入的User對象的主鍵屬性。

 

User.java

Java代碼 復制代碼  收藏代碼
  1. public class User {  
  2.     private int userId;  
  3.     private String userName;  
  4.     private String password;  
  5.     private String comment;  
  6.       
  7.     //setter and getter  
  8. }  
public class User {
	private int userId;
	private String userName;
	private String password;
	private String comment;
	
	//setter and getter
}

 UserDao.java

Java代碼 復制代碼  收藏代碼
  1. public interface UserDao {  
  2.   
  3.     public int insertAndGetId(User user);  
  4.   
  5. }  
public interface UserDao {

	public int insertAndGetId(User user);

}

 測試:

Java代碼 復制代碼  收藏代碼
  1. User user = new User();  
  2. user.setUserName("chenzhou");  
  3. user.setPassword("xxxx");  
  4. user.setComment("測試插入數據返回主鍵功能");  
  5.   
  6. System.out.println("插入前主鍵為:"+user.getUserId());  
  7. userDao.insertAndGetId(user);//插入操作  
  8. System.out.println("插入后主鍵為:"+user.getUserId());  
User user = new User();
user.setUserName("chenzhou");
user.setPassword("xxxx");
user.setComment("測試插入數據返回主鍵功能");

System.out.println("插入前主鍵為:"+user.getUserId());
userDao.insertAndGetId(user);//插入操作
System.out.println("插入后主鍵為:"+user.getUserId());

 輸出:

Shell代碼 復制代碼  收藏代碼
  1. 插入前主鍵為:0  
  2. 插入后主鍵為:15  
插入前主鍵為:0
插入后主鍵為:15

 查詢數據庫:

 

如上所示,剛剛插入的記錄主鍵id為15


免責聲明!

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



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