假设数据库表中有一个bigint+autoincremnt类型的字段id,在采用MyBatis技术往表中添加数据时,可以通过以下几种方式获取新增记录的主键值。
方式一- 单个插入
INSERT INTO tb_user (username,password)
VALUES (#{username},#{password})
- 批量插入
insert into tb_user(username, password)
values
(#{item.username}, #{item.password}
方式二
select LAST_INSERT_ID()
insert into tb_user(username, password)
values
(#{username},#{password})
其实对于这种方式来说,也可以返回非自增方式新增记录主键的值
select uuid() as id
insert into tb_user(username, password) values (#{username},#{password})
方式三
@Insert("insert into tb_user(username, password) values (#{username},#{password})")
@SelectKey(statement = "select last_insert_id()",keyProperty = "id",before = false,resultType = Long.class)
int insert(Province province);
方式四
@InsertProvider(type =MapperProvider.class, method = "insert")
@Options(useGeneratedKeys = true,keyProperty = "id",keyColumn = "id")
//@Options和@SelectKey都能够实现功能:返回新增记录的自增长主键id字段值
//@SelectKey(statement = "select last_insert_id()",keyProperty = "id",before = false,resultType = Long.class)
int insert(User user);
其中 public class MapperProvider{ public String insert(User user) { return “insert into tb_user(username, password) values (”+user.getName+“,”+user.getPassword+“)” } }