使用 MyBatis Annotation Spring Boot 检索生成的 ID

Unk*_*200 2 intellij-idea mybatis spring-boot spring-mybatis

我正在努力学习MyBatis。使用注释插入语句后如何获取自动生成的 ID @Insert

我的代码示例:

@Insert("INSERT INTO user(name, mobile, password) VALUES(#{name}, #{mobile}, #{password})")
@SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty = "id", before = false, resultType = Long.class)
Long insertUser(User user);
Run Code Online (Sandbox Code Playgroud)

我想获取生成的 id 作为插入方法的返回。

ave*_*ave 8

@SelectKey适用于旧版驱动程序。
对于最近的驱动程序,您应该使用useGeneratedKeys.
我们有一个常见问题解答条目解释了如何使用 XML 映射器来完成此操作。
如果加上注释,它看起来如下。

@Insert("INSERT INTO user(name, mobile, password) VALUES(#{name}, #{mobile}, #{password})")
@Options(useGeneratedKeys = true, keyProperty = "id")
int insertUser(User user);
Run Code Online (Sandbox Code Playgroud)

请注意,该@Insert方法返回更新的行数,而不是生成的键。在您的情况下,生成的密钥将分配给ie
指定的参数的属性。keyPropertyUser.id

keyColumn对于某些数据库,您可能还需要指定。
如果不起作用,请在问题中添加 DB、驱动程序和 MyBatis 的版​​本。