MyBatis selectKey: Guide to Primary Keys
In MyBatis, selectKey is an element used to generate primary key values and set them in the entity object. It is typically used to generate primary key values when inserting data, and then set the primary key value in the entity object so that it can be used for subsequent operations.
The selectKey element is commonly nested within an insert statement, where the keyProperty attribute is used to specify which entity object property the generated primary key value should be set to. The order attribute is used to specify the order in which the primary key value is generated (BEFORE or AFTER), and the resultType attribute is used to specify the data type of the generated primary key value.
The sample code is shown below:
<insert id="insertUser" parameterType="User" useGeneratedKeys="true" keyProperty="id">
<selectKey keyProperty="id" order="AFTER" resultType="int">
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO user (name, age) VALUES (#{name}, #{age})
</insert>
In this example, insertUser is an SQL statement for inserting user information. The selectKey element is used to generate a primary key value and set it to the id attribute of the User object. After inserting the data, you can retrieve the generated primary key value using the id attribute of the User object.