获取MyBatis插入数据的自增长id

本文介绍在SpringBoot中使用MyBatis进行数据库操作时,如何通过@Options注解配置来获取自增ID,实现将自动生成的主键值注入到实体类的指定属性中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

spring boot中集成MyBatis来向数据库中插入一个id自增长的数据时,默认返回的是受影响数据的行数。而现在的需求是要获取自增长的id。
要解决该问题,需要使用注解:

@Options(useGeneratedKeys = true, keyProperty = "属性名")

useGeneratedKeys = true的作用是令MyBatis获取自动生成的主键,keyProperty = "属性名"则定义了将获取到的主键值注入到实体类的指定属性中。
例如:

public class Company {
    protected Integer id;
    protected String name;

    public Integer getId() { return id; }
    public void setId(Integer id) { this.id = id; }
    public Integer getName() { return name; }
    public void setName(String name) { this.name = name; }
}

其中id为自增长字段。
进行插入时:

@Insert({
  "insert into company",
  "(name)",
  "values (#{name, jdbcType=VARCHAR}"
})
int addCompany(Company company);

传入的company对象其id为null。
插入成功,返回的int是1,表示有1行受影响的数据。
现在要获取自增长的id,则:

@Insert({
  "insert into company",
  "(name)",
  "values (#{name, jdbcType=VARCHAR}"
})
@Options(useGeneratedKeys = true, keyProperty = "id")
int addCompany(Company company);

添加成功后,会将自动生成的id填充到传入的company对象中。直接调用company.getId()即可获取自动生成的id。
也可以使用规定参数的形式:

@Insert({
  "insert into company",
  "(name)",
  "values (#{c.name, jdbcType=VARCHAR}"
})
@Options(useGeneratedKeys = true, keyProperty = "c.id")
int addCompany(@Param("c") Company company);
Spring Boot项目中,结合MyBatis进行数据插入并期望获取自动生成的ID通常涉及到一些步骤。首先,你需要配置好MyBatis的动态SQL以及数据库的ID生成策略。 1. **设置Mapper XML文件**:创建一个Mapper接口和对应的XML映射文件。例如: ```xml <mapper namespace="com.example.demo.mapper.UserMapper"> <insert id="insertUser" parameterType="com.example.demo.entity.User"> INSERT INTO user (username, password) VALUES (#{username}, #{password}) SELECT LAST_INSERT_ID() AS id; </insert> </mapper> ``` 这里的`LAST_INSERT_ID()`是一个SQL函数,用于获取上一条插入操作的自动ID。 2. **编写Repository接口**:在Spring Data JPA风格的Repository接口中声明保存方法,并注入相应的Mapper接口: ```java public interface UserRepository extends JpaRepository<User, Long> { @Insert("CALL ${insertUser}") @Select("SELECT last_insert_id() as id") Long insert(User user); } ``` 这里使用了`@Insert`注解来进行插入操作,并通过占位符`${insertUser}`引用Mapper接口中的`insertUser`方法,同时使用`@Select`注解选择返回值。 3. **调用服务层方法**:在服务层,你可以像这样调用Repository的`insert`方法并获取新生成的ID: ```java @Service public class UserService { private final UserRepository userRepository; public UserService(UserRepository userRepository) { this.userRepository = userRepository; } public User createUser(User user) { User savedUser = userRepository.insert(user); return savedUser; } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值