【SpringBoot】Mybatis执行insert/update后如何获得主键id
warning:
这篇文章距离上次修改已过419天,其中的内容可能已经有所变动。
在MyBatis中,当执行插入操作(INSERT)后获取自动生成的主键ID,可以通过在mapper的XML文件中配置useGeneratedKeys="true"和keyProperty属性来实现。
以下是一个简单的例子:
- 在你的Mapper接口中定义插入方法:
public interface YourEntityMapper {
int insertYourEntity(YourEntity yourEntity);
}- 在对应的Mapper XML文件中配置SQL语句并指定
useGeneratedKeys和keyProperty:
<mapper namespace="com.example.mapper.YourEntityMapper">
<insert id="insertYourEntity" useGeneratedKeys="true" keyProperty="id">
INSERT INTO your_table (column1, column2, ...)
VALUES (#{value1}, #{value2}, ...)
</insert>
</mapper>在上述配置中,useGeneratedKeys="true"告诉MyBatis使用JDBC的getGeneratedKeys方法来取出由数据库自动生成的主键,而keyProperty="id"则指定了这个主键应该被映射到实体类YourEntity的哪个属性上。
在执行insertYourEntity方法后,MyBatis会自动将生成的主键ID赋值到yourEntity对象的id属性上。
确保你的数据库表设置了自增主键或者有其他机制生成主键,并且你的数据库JDBC驱动支持getGeneratedKeys方法。
评论已关闭