在使用mybatis中我们经常需要插入数据。给主表插入一条数据,给从表插入若干条数据,但是从表需要插入主表里自增的Id来维持关系。
我知道的,mybatis做法有两种:
1.例如:注意这两个属性useGeneratedKeys="true" keyProperty="report.reportId"
useGeneratedKeys="true"把新增加的主键赋值到自己定义的keyProperty(id)中
useGeneratedKeys 取值范围true|false 默认值是:false。 含义:设置是否使用JDBC的getGenereatedKeys方法获取主键并赋值到keyPropert设置的领域模型属性中
<insert id="insertAvailableRateReport" useGeneratedKeys="true"
keyProperty="report.reportId" parameterType="com.webank.ims.config.bean.availableRate.AvailableRateReport">
REPLACE INTO webank_available_rate_report (report_id,report_name,event_id,start_time,end_time,status,creator,remark)
VALUES (
#{report.reportId},#{report.reportName},#{report.eventId},#{report.startTime},#{report.endTime},#{report.status},#{report.creator},#{report.remark}
)
</insert>
2.例如:注意
<selectKey resultType="java.lang.Long" keyProperty="groupId" order="AFTER">SELECT LAST_INSERT_ID() AS groupId</selectKey>
参考文章selectKey的使用
<insert id="addBatchScheduleGroup" parameterType="com.webank.ims.config.bean.batch.ComBatchScheduleGroup">
<selectKey resultType="java.lang.Long" keyProperty="groupId" order="AFTER">
SELECT LAST_INSERT_ID() AS groupId
</selectKey>
INSERT INTO
com_batch_schedule_group
(
group_id,
group_name,
domain_id
)
VALUES
(
#{groupId},
#{groupName},
#{domainId}
)
</insert>
本文介绍在MyBatis中实现主从表插入的方法,包括如何将自动生成的主键值传递给从表,确保数据之间的关联性。通过使用useGeneratedKeys属性和selectKey元素,可以有效地解决这一问题。
1761

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



