What is the method to retrieve a primary key in MyBatis?
In MyBatis, there are two common ways to retrieve the primary key.
- 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>
- 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.