在 MyBatis 中获取自动生成的主键值通常有以下几种方式:
useGeneratedKeys
和 keyProperty
:
INSERT INTO users (name, age) VALUES (#{name}, #{age})
useGeneratedKeys="true"
:告诉 MyBatis 使用数据库的自增主键生成策略。keyProperty="userId"
:指定将自动生成的主键值赋给 User
对象的 userId
属性。
INSERT INTO users (name, age) VALUES (#{name}, #{age})
SELECT LAST_INSERT_ID()
<selectKey>
标签用于执行查询以获取主键值,LAST_INSERT_ID()
是获取 MySQL 自增主键的函数,order="AFTER"
表示在插入后执行。@Options
注解:@Options(useGeneratedKeys = true, keyProperty = "userId")
@Insert("INSERT INTO users (name, age) VALUES (#{name}, #{age})")
int insertUser(User user);
@Options
注解,在注解中设置 useGeneratedKeys = true
和 keyProperty = "userId"
。这些方式能够让 MyBatis 在执行插入操作后获取自动生成的主键值,并将其设置到对应的属性中。
Proudly powered by WordPress