Mybatis的insert语句中,在返回参数中返回insert数据的自增id

郎家岭伯爵 2023年05月24日 270次浏览

背景

业务场景是这样的:在设计数据表时涉及到跨表保存数据,其中 A 表数据对应多条 B 表数据,且 A 表的自增 ID 在 B 表中为一个字段,从而实现两表的业务关系。

但由于两表的数据需要同时(业务上的同时,在代码实现上仍然是先插入 A 表数据然后再插入 B 表数据) insert 到数据库中,因此在插入 A 表数据时需要获取它的自增 ID。

实现

理论部分

在 MyBatis 的 insert 语句中,可以通过设置 useGeneratedKeyskeyProperty 属性来实现返回自增 ID。

useGeneratedKeys 属性设置为 true 表示使用数据库自动生成的键值,keyProperty 属性指定了将自动生成的键值设置到哪个属性中。

具体实现

在 SpringBoot 项目中,例如我们创建一个如下 Demo:

User 实体:

package com.langjialing.helloworld.model.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

/**
 * @author 郎家岭伯爵
 * @time 2023/3/13 16:07
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class UserEntity {
    
    private Integer id;
    
    private String userName;

    private String password;

    private Long age;
}

测试 Controller:

@GetMapping("/addUser")
public Integer addUser(){
    UserEntity userEntity = new UserEntity().setUserName("郎家岭伯爵").setPassword("123456").setAge(18L);
    userMapper.insertUser(userEntity);
    return userEntity.getId();
}

Mapper.xml:(useGeneratedKeys=“true” keyProperty="id"两个属性设置实现功能)

<insert id="insertUser" parameterType="com.langjialing.helloworld.model.entity.UserEntity" useGeneratedKeys="true" keyProperty="id">
    insert into `user` (user_name, password, age)
    values (#{userName}, #password}, #{age})
</insert>

Postman 调用测试:

Postman调用接口

数据库中插入的数据

总结

在 MyBatis 的 insert 语句中,可以通过设置 useGeneratedKeyskeyProperty 属性来实现返回自增 ID,从而实现一些特定的业务需求。

赞助页面示例