How to get the ID value of the auto-incremented primary key after the Insert operation

Background information

In MyBatis, in most cases, after we insert a piece of data into the database, we do not need to pay attention to the primary key ID of the newly inserted data. We also know that although the normal insert statement in DAO can return an int type value, this value represents the number of rows affected by the insertion, not the primary key ID of the newly inserted data.

There is a demand recently. The core is to save some error information of inspection results. However, since the error details may be quite large, the plan is to first record the error details in an extended table, and then save the primary key ID recorded in the extended table in the error in the record table. So there is a question here, how can we directly obtain the primary key ID after inserting into the extended table? This article will briefly document two common processing methods.

Solutions

No matter which method is used, the core points are:

  • Set it in the insert statement in the mapper.xml file so that the insertion result can obtain the primary key id.
  • After calling the DAO insertion method, obtain the primary key id of the insertion result from the input parameter DO of the insertion method.

Configure mapper.xml

method one

Configure the "useGeneratedKeys" and "keyProperty" attributes in insert:

  • useGeneratedKeys: Value range true|false (default value), set whether to use JDBC's getGenereatedKeys method to obtain the primary key and assign it to the domain model attribute set by keyProperty
  • keyProperty: The default value is unset, used to set the property of DO to which the return value of the getGeneratedKeys method or selectKey sub-element will be assigned.
    <insert id="insertDataErrorExtension" parameterType="com.xx.campaign.dataobject.DataErrorExtensionDO" useGeneratedKeys="true" keyProperty="id">
        insert into data_error_extension
        (group_id, page_id, module_id, tag_id, schedule_id, error_type, error_code, error_level, error_message, error_details, status, version, attr)
        values (#{groupId}, #{pageId}, #{moduleId}, #{tagId}, #{scheduleId}, #{errorType},#{errorCode}, #{errorLevel}, #{errorMessage}, #{errorDetails}, #{status}, #{version}, #{attr})
    </insert>

Method 2

Add a selectKey node in Insert:

  • Node properties:
    1. resultType: represents the attribute that returns the node value;
    2. order: can be set to BEFORE or AFTER. If set to BEFORE, then it will first select the primary key, set the keyProperty and then execute the insert statement. If set to AFTER, the insert statement is executed first, followed by the selectKey element
    3. keyProperty: The target property that should be set as a result of the selectKey statement.
  • The node executes the statement, that is, how to obtain the primary key id. You can try one of the following two methods:
    1. SELECT LAST_INSERT_ID()
    2. select @@IDENTITY
    <insert id="insertDataErrorExtension" parameterType="com.xx.campaign.dataobject.DataErrorExtensionDO">
        <selectKey resultType="long" order="AFTER" keyProperty="id">
            SELECT LAST_INSERT_ID()
        </selectKey>
        insert into data_error_extension
        (group_id, page_id, module_id, tag_id, schedule_id, error_type, error_code, error_level, error_message, error_details, status, version, attr)
        values (#{groupId}, #{pageId}, #{moduleId}, #{tagId}, #{scheduleId}, #{errorType},#{errorCode}, #{errorLevel}, #{errorMessage}, #{errorDetails}, #{status}, #{version}, #{attr})
    </insert>

Get primary key id in code

The key point here is that the insert method of DAO must pass the corresponding DO object. The sample method signature is as follows:

    /**
     * 插入Data error extension
     *
     * @param dataErrorExtensionDO dataErrorExtensionDO
     *
     * @return 影响行数
     *
     * @throws Exception 插入异常
     */
    Integer insertDataErrorExtension(DataErrorExtensionDO dataErrorExtensionDO) throws Exception;

Then after calling the insert method of DAO, you can get the auto-incremented primary key id from the DO correspondence:
file

Guess you like

Origin blog.csdn.net/weixin_42534940/article/details/129777955