MyBatis+MySQL 返回插入的主键ID

一.需求:

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

二.使用:

1.实体类:

public class User {
    private int userId;
    private String userName;
    private String password;
    private String comment;
}

2.mapperXml代码:

<insert id="insertAndGetId" useGeneratedKeys="true" keyProperty="userId" parameterType="com.chenzhou.mybatis.User">
    insert into user(userName,password,comment)
    values(#{userName},#{password},#{comment})
</insert>

useGeneratedKeys:

  取值范围true|false

  默认值是:false。

  含义:设置是否使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。

keyProperty:

  在insert中指定了keyProperty="userId",其中userId代表插入的User对象的主键属性。

3.测试代码:

User user = new User();
user.setUserName("chenzhou");
user.setPassword("xxxx");
user.setComment("测试插入数据返回主键功能");

System.out.println("插入前主键为:"+user.getUserId());    //输出:0
userDao.insertAndGetId(user);//插入操作
System.out.println("插入后主键为:"+user.getUserId());    //输出:4

转自:https://blog.csdn.net/weixin_38553453/article/details/80506935

原文地址:https://www.cnblogs.com/XueTing/p/14052915.html