MyBatis 如何获取插入数据的主键
要在 MyBatis 中添加返回主键的功能,可以按照以下步骤进行操作:
- 在 Mapper 接口中定义一个方法,用于插入数据并返回主键。例如:
public interface UserMapper {
int insertUser(User user);
}
- 在 Mapper XML 文件中,使用'useGeneratedKeys' 和 'keyProperty' 属性来指定要返回的主键列。例如:
<insert id="insertUser" parameterType="User" useGeneratedKeys="true" keyProperty="id">
INSERT INTO user (name, age) VALUES (#{name}, #{age})
</insert>
- 在 Mapper 接口的方法中,使用 '@Options' 注解来开启返回主键的功能。例如:
public interface UserMapper {
@Options(useGeneratedKeys = true, keyProperty = "id")
int insertUser(User user);
}
- 在插入数据时,调用 Mapper 接口的方法即可获取返回的主键。例如:
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = new User('John', 25);
userMapper.insertUser(user);
System.out.println('插入的用户ID:' + user.getId());
这样,就可以通过 MyBatis 插入数据并返回主键了。
原文地址: https://www.cveoy.top/t/topic/pea4 著作权归作者所有。请勿转载和采集!