Mybatis獲取插入記錄的自增加ID

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

 

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

 <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.javamybatis

public class User {  
    private int userId;  
    private String userName;  
    private String password;  
    private String comment;  
      
    //setter and getter  
}

UserDao.javaapp

public interface UserDao {  
  
    public int insertAndGetId(User user);  
  
}

測試:測試

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());

輸出:spa

 

  1. 插入前主鍵爲:0  code

  2. 插入後主鍵爲:15orm

 

 查詢數據庫:xml

 

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

 

p.s. 注意:

 

1.Mybatis Mapper 文件中,「useGeneratedKeys」和「keyProperty」必須添加,並且keyProperty必定得和java對象的屬性名稱一直,而不是表格的字段名

2.java Dao中的Insert方法,傳遞的參數必須爲java對象,也就是Bean,而不能是某個參數。

相關文章
相關標籤/搜索