Mybatis uses, how to assign data to the main table of the master-slave table and add it

In using mybatis we often need to insert data. Insert a piece of data into the master table and insert several pieces of data into the slave table, but the slave table needs to insert the self-incrementing Id in the master table to maintain the relationship.

As far as I know, mybatis has two approaches:

1. For example: note these two properties useGeneratedKeys="true" keyProperty="report.reportId"

 

useGeneratedKeys="true" assigns the newly added primary key to its own defined keyProperty(id)
useGeneratedKeys value range true|false The default value is: false. Meaning: Set whether to use the getGenereatedKeys method of JDBC to obtain the primary key and assign it to the domain model property set by 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. For example: Note

<selectKey resultType="java.lang.Long" keyProperty="groupId" order="AFTER">SELECT LAST_INSERT_ID() AS groupId</selectKey>

Refer to the use of selectKey in the article

<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>

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326230283&siteId=291194637