首页 课程 师资 教程 报名

让我们深入的了解下mybatis返回主键id

  • 2023-02-17 17:06:26
  • 1822次 星辉

添加单一记录时返回主键ID

添加一条记录时返回主键值,在xml映射器和接口映射器中都可以实现。

在映射器中配置获取记录主键值

xml映射器

在定义xml映射器时设置属性useGeneratedKeys值为true,并分别指定属性keyProperty和keyColumn为对应的数据库记录主键字段与Java对象的主键属性。

<mapper namespace="org.chench.test.mybatis.mapper">
	<!-- 插入数据:返回记录主键id值 -->
	<insert id="insertOneTest" parameterType="org.chench.test.mybatis.model.Test" useGeneratedKeys="true" keyProperty="id" keyColumn="id" >
		insert into test(name,descr,url,create_time,update_time) 
		values(#{name},#{descr},#{url},now(),now())
	</insert>
</mapper>

接口映射器

在接口映射器中通过注解@Options分别设置参数useGeneratedKeys,keyProperty,keyColumn值

// 返回主键字段id值
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
@Insert("insert into test(name,descr,url,create_time,update_time) values(#{name},#{descr},#{url},now(),now())")
Integer insertOneTest(Test test);

获取新添加记录主键字段值

需要注意的是,在MyBatis中添加操作返回的是记录数并非记录主键id。因此,如果需要获取新添加记录的主键值,需要在执行添加操作之后,直接读取Java对象的主键属性。

Integer rows = sqlSession.getMapper(TestMapper.class).insertOneTest(test);
System.out.println("rows = " + rows); // 添加操作返回记录数
System.out.println("id = " + test.getId()); // 执行添加操作之后通过Java对象获取主键属性值

添加批量记录时返回主键ID

如果希望执行批量添加并返回各记录主键字段值,只能在xml映射器中实现,在接口映射器中无法做到。

<!-- 批量添加数据,并返回主键字段 -->
<insert id="insertBatchTest" useGeneratedKeys="true" keyProperty="id">
	INSERT INTO test(name,descr,url,create_time,update_time) VALUES
		<foreach collection="list" separator="," item="t">
		(#{t.name},#{t.descr},#{t.url},now(),now())
		</foreach>
</insert>

可以看到,执行批量添加并返回记录主键值的xml映射器配置,跟添加单条记录时是一致的。不同的地方仅仅是使用了foreach元素构建批量添加语句。

获取主键ID实现原理

需要注意的是,不论在xml映射器还是在接口映射器中,添加记录的主键值并非添加操作的返回值。实际上,在MyBatis中执行添加操作时只会返回当前添加的记录数。

package org.apache.ibatis.executor.statement;
public class PreparedStatementHandler extends BaseStatementHandler {
	@Override
    public int update(Statement statement) throws SQLException {
        PreparedStatement ps = (PreparedStatement) statement;
        // 真正执行添加操作的SQL语句
        ps.execute();
        int rows = ps.getUpdateCount();
        Object parameterObject = boundSql.getParameterObject();
        KeyGenerator keyGenerator = mappedStatement.getKeyGenerator();
        // 在执行添加操作完毕之后,再处理记录主键字段值
        keyGenerator.processAfter(executor, mappedStatement, ps, parameterObject);
        // 添加记录时返回的是记录数,而并非记录的主键字段值
        return rows;
    }
}

顺便看一下MyBatis添加操作的时序图:

跟踪时序图执行步骤可以看到,MyBatis最终是通过MySQL驱动程序获取到了新添加的记录主键值。

以上就是星辉小编介绍的"让我们深入的了解下mybatis返回主键id",希望对大家有帮助,如有疑问,请在线咨询,有专业老师随时为您务。

选你想看

你适合学Java吗?4大专业测评方法

代码逻辑 吸收能力 技术学习能力 综合素质

先测评确定适合在学习

在线申请免费测试名额
价值1998元实验班免费学
姓名
手机
提交