mybatis使用,插入数据主从表的主表自增建如何赋值

本文介绍在MyBatis中实现主从表插入的方法,包括如何将自动生成的主键值传递给从表,确保数据之间的关联性。通过使用useGeneratedKeys属性和selectKey元素,可以有效地解决这一问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在使用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>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值