Mybatis之执行插入语句后返回主键id的三种方式

本文介绍了在MyBatis中处理多表更新时,如何在XML映射文件中使用useGeneratedKeys和keyProperty,selectKey以及注解@SelectKey来确保插入后获取新生成的主键ID。

在工程应用中,通常会遇到多表更新操作,在集成mybatis中需要在执行插入语句后返回主键id进行后续的表更新操作,下面对其实现的方式记录分享出来,以应对不同的应用场景。

1、在xml文件中应用useGeneratedKeys和keyProperty

在xml文件中,insert标签属性中,添加useGeneratedKeys和keyProperty,类似如下:

	<insert id="insert" parameterType="com.***.Attachment" useGeneratedKeys="true" keyProperty="attachment.id"  keyColumn="id">
        insert into b_attachment
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="attachment.id != -1">
                id,
            </if>
            <if test="attachment.fileName != null and attachment.fileName !=''">
                file_name,
            </if>
            <if test="attachment.remarks != null and attachment.remarks !=''">
                remarks,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if t
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值