What is the method to retrieve a primary key in MyBatis?

In MyBatis, there are two common ways to retrieve the primary key.

  1. By utilizing the selectKey element, it is possible to retrieve the automatically generated primary key value when inserting data. For example:
<insert id="insertUser" parameterType="User">
    <selectKey keyProperty="id" order="AFTER" resultType="int">
        SELECT LAST_INSERT_ID()
    </selectKey>
    INSERT INTO user (name, age) VALUES (#{name}, #{age})
</insert>
  1. Tag: When inserting data, you can use tags to retrieve automatically generated primary key values. For example:
<insert id="insertUser" parameterType="User">
    <selectKey keyProperty="id" order="AFTER" resultType="int">
        SELECT LAST_INSERT_ID()
    </selectKey>
    INSERT INTO user (name, age) VALUES (#{name}, #{age})
</insert>

Both methods involve executing an SQL statement immediately after inserting data to retrieve the primary key value, which is then set to the primary key property of the entity object.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds