在工程应用中,通常会遇到多表更新操作,在集成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

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

被折叠的 条评论
为什么被折叠?



