Mybatis获取插入记录的自增长ID

 

需求:使用MyBatis往MySQL数据库中插入一条记录后,需要返回该条记录的自增主键值。

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

 <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

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

UserDao.java

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

输出:

  1. 插入前主键为:0  

  2. 插入后主键为:15

 查询数据库:

如上所示,刚刚插入的记录主键id为15

p.s. 注意:

1.Mybatis Mapper 文件中,“useGeneratedKeys”和“keyProperty”必须添加,而且keyProperty一定得和java对象的属性名称一直,而不是表格的字段名

2.java Dao中的Insert方法,传递的参数必须为java对象,也就是Bean,而不能是某个参数。

原文地址:https://www.cnblogs.com/pejsidney/p/9237114.html