Mybatis获取插入数据后的自增主键的值

mapper.xml中的useGeneratedKeys和keyProperty属性

利用mybatis提供的useGeneratedKeys和keyProperty属性可以在插入一条数据后,获取插入数据自增主键的值返回给前台。

keyProperty属性绑定java实体类中的属性,useGeneratedKeys设置为true即可。

LAST_INSERT_ID()函数

该函数可以获取当前所插入表中,最后一条插入记录的id

常见业务场景(一对多)

1、插入记录主表,获取主表id,把主表id插入从表记录的主表外键中。
例如:
一条考试记录对应多条考试题目记录、一个新增班级id绑定多个学生等等

使用案例

插入example实例记录,得到记录的自增id

//实体类
public class Example {
	private int id;
	private String name;
	private String sex;
	private String age;
//...set、get
}
<insert id="insertexample" parameterType="com.example.domain.Example" useGeneratedKeys="true" keyProperty="id">
	insert into example
	<trim prefix="(" suffix=")" suffixOverrides=",">
		<if test="name != null">name,</if>
		<if test="sex != null">sex,</if>
		<if test="age != null">age,</if>
	</trim>
	<trim prefix="values (" suffix=")" suffixOverrides=",">
		<if test="name != null">#{name}</if>
		<if test="sex != null">#{sex}</if>
		<if test="age != null">#{age}</if>
	</trim>
</insert>

<!-- 方式二 -->
<insert id="insertexample2" parameterType="com.example.domain.Example">
    <selectKey keyProperty="id" order="AFTER" resultType="int">
        select LAST_INSERT_ID()
    </selectKey>
	insert into example
	<trim prefix="(" suffix=")" suffixOverrides=",">
		<if test="name != null">name,</if>
		<if test="sex != null">sex,</if>
		<if test="age != null">age,</if>
	</trim>
	<trim prefix="values (" suffix=")" suffixOverrides=",">
		<if test="name != null">#{name}</if>
		<if test="sex != null">#{sex}</if>
		<if test="age != null">#{age}</if>
	</trim>
</insert>

执行insert语句,通过对象get到id。

public interface ExampletMapper{
    public void insertdemo(Example example);
}
public void insertExample(){
	Example example = new Example();
	example.setName("名字");
	example.setSex("性别");
	example.setAge("年龄");
    exampletMapper.insertdemo(test);
    System.out.println("example的id:"+ example.getId());
}

### 使用 MyBatis 进行批量插入获取主键 为了实现通过 MyBatis 插入多条记录的同时获取每一条记录对应的自主键 ID,需遵循特定配置与编码实践。 #### 环境准备 确保所使用的 MyBatis 版本不低于 3.3.1[^2]。较低版本可能不具备此功能的支持。 #### Mapper XML 文件配置 在 `mapper.xml` 中定义 SQL 映射语句时,应加入如下属性来启用自动生成的键返回: ```xml <insert id="batchInsert" useGeneratedKeys="true" keyProperty="id"> INSERT INTO table_name (column_list) VALUES <foreach collectioncolumn2}) </foreach> </insert> ``` 上述代码片段展示了如何利用 `<foreach>` 标签遍历传入的对象集合,并为每一项构建相应的插入子句;同时设置了 `useGeneratedKeys=true` 及指定了用于接收新生成 ID 的对象属性名 `keyProperty="id"`。 #### Java 接口设计 对应于上面的映射文件,在接口层面上声明相应的方法签名,注意这里只接受单一参数即待插入数据集数组或列表形式传递给 DAO 层处理: ```java public interface UserMapper { int batchInsert(@Param("list") List<User> userList); } ``` 得注意的是,尽管执行批处理操作,但该方法仍然保持简单整数类型的返回表示受影响行的数量而非直接返回包含所有新 ID 的列表。 #### 实体类调整 如果表中的自动长列名称与实体类成员变量命名存在差异,则应在 mapper xml 设置额外两个属性:`keyColumn` 和 `keyProperty` 来建立两者之间的关联关系。 例如对于 MySQL 表内名为 `user_id` 而实体类里叫作 `userId` 的情况可以这样指定: ```xml <insert id="batchInsertUserWithDifferentIdName" useGeneratedKeys="true" keyColumn="user_id" keyProperty="userId"> <!-- ... --> </insert> ``` #### 测试验证 最后编写单元测试案例调用上述服务完成实际业务逻辑检验整个流程是否正常工作以及确认确实能够取得预期的结果集——也就是各个被插入记录各自的唯一标识符。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值