MyBatis插入数据后回填id
  在 MyBatis 中插入数据后回填自增主键(如 MySQL 的 AUTO_INCREMENT)可以通过以下两种方式实现,以下是详细说明和示例:
方法 1:useGeneratedKeys + keyProperty(推荐)
适用于支持自增主键的数据库(如 MySQL),直接在 insert 标签中配置:
Mapper XML 配置
<insert id="insertUserAccount" 
        parameterType="com.example.entity.UserAccount"
        useGeneratedKeys="true" 
        keyProperty="id">  <!-- 将生成的 key 回填到实体类的 id 属性 -->
    INSERT INTO sys_user_account (
        create_time, update_time, create_by, update_by, remark,
        supplier_id, user_id, total_charge_amount, total_give_back_amount,
        available_balance_amount, balance_amount, effect
    ) VALUES (
        #{createTime}, #{updateTime}, #{createBy}, #{updateBy}, #{remark},
        #{supplierId}, #{userId}, #{totalChargeAmount}, #{totalGiveBackAmount},
        #{availableBalanceAmount}, #{balanceAmount}, #{effect}
    )
</insert>
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
Java 实体类
确保实体类中有 id 字段及其对应的 setter 方法:
public class UserAccount {
    private Integer id;
    private LocalDateTime createTime;
    private LocalDateTime updateTime;
    // 其他字段及 getter/setter...
    
    // 必须有 setter 方法
    public void setId(Integer id) {
        this.id = id;
    }
}
 1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
调用示例
UserAccount account = new UserAccount();
// 设置其他字段值...
userAccountMapper.insertUserAccount(account);  // 执行插入
// 插入后,自动回填的 id 会直接赋给 account 对象
System.out.println("生成的ID:" + account.getId()); 
 1
2
3
4
5
6
2
3
4
5
6
方法 2:selectKey 标签(通用方案)
适用于不支持自增主键的数据库(如 Oracle),或需要显式控制主键生成逻辑的场景。
Mapper XML 配置
<insert id="insertUserAccount" parameterType="com.example.entity.UserAccount">
    <selectKey 
        keyProperty="id"          <!-- 回填到实体类的 id 属性 -->
        resultType="java.lang.Integer" 
        order="AFTER">           <!-- 在 INSERT 语句执行后执行 -->
        SELECT LAST_INSERT_ID()  <!-- MySQL 获取自增主键的函数 -->
    </selectKey>
    
    INSERT INTO sys_user_account (
        create_time, update_time, create_by, update_by, remark,
        supplier_id, user_id, total_charge_amount, total_give_back_amount,
        available_balance_amount, balance_amount, effect
    ) VALUES (
        #{createTime}, #{updateTime}, #{createBy}, #{updateBy}, #{remark},
        #{supplierId}, #{userId}, #{totalChargeAmount}, #{totalGiveBackAmount},
        #{availableBalanceAmount}, #{balanceAmount}, #{effect}
    )
</insert>
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
关键注意事项
确保数据库支持自增主键
• 检查表结构中的id字段是否定义为AUTO_INCREMENT(MySQL)。避免手动设置
id
• 插入时不要在 SQL 中传递id值,否则会覆盖数据库生成的值。Oracle 或其他数据库适配
• 如果使用 Oracle,需改用序列(Sequence)并调整selectKey逻辑:<selectKey keyProperty="id" resultType="java.lang.Long" order="BEFORE"> SELECT your_sequence.NEXTVAL FROM DUAL </selectKey>1
2
3实体类必须有
setter方法
• MyBatis 依赖setter方法回填主键值。
完整示例代码 Service 层调用
public void createAccount(UserAccount account) {
    userAccountMapper.insertUserAccount(account);
    // 插入后直接使用 account.getId() 获取主键
    log.info("新账户ID:{}", account.getId());
}
 1
2
3
4
5
2
3
4
5
通过上述配置,MyBatis 会在插入数据后自动将数据库生成的主键值回填到实体对象的 id 字段中。
编辑  (opens new window)
  上次更新: 2025/06/10, 09:18:05