SpringBoot+MyBatis+MySQL 返回插入的主键ID
使用MyBatis往MySQL数据库中插入一条记录后,需要返回该条记录的自增主键值。
在mapper中指定keyProperty属性,示例如下:
insert into user(userName,password,comment)
values(#{userName},#{password},#{comment})
useGeneratedKeys:
取值范围true|false
默认值是:false。
含义:设置是否使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。MySQL和SQLServer执行auto-generated key field,因此当数据库设置好自增长主键后,可通过JDBC的getGeneratedKeys方法获取。但像Oralce等不支持auto-generated key field的数据库就不能用这种方法获取主键了。
keyProperty:
(仅对 insert 有用) 标记一个属性, MyBatis 会通过 getGeneratedKeys 或者通过 insert 语句的 selectKey 子元素设置它的值。默认: 不设置。
所示,我们在insert中指定了keyProperty="userId",其中userId代表插入的User对象的主键属性。
public class User {
private int userId;
private String userName;
private String password;
private String comment;
//setter and getter
}
public interface UserDao {
public int insertAndGetId(User user);
}
user.setPassword("xxxx");
user.setComment("测试插入数据返回主键功能");
System.out.println("插入前主键为:"+user.getUserId());
userDao.insertAndGetId(user);//插入操作
System.out.println("插入后主键为:"+user.getUserId());
输出:
插入前主键为:0
插入后主键为:15
- 本文标签: springboot mysql mybatis
- 版权声明: 本站原创文章,于2020年06月27日由wzbjsz发布,转载请注明出处