How to use the keyproperty attribute in Mybatis?

The keyProperty attribute in MyBatis is used to specify a property whose value will be populated with the generated primary key value after an insert or update. This is typically used in cases where the primary key is automatically generated.

When defining insert or update statements, the keyProperty attribute should be used in the corresponding insert or update tag to specify the primary key property to be populated. An example is shown below:

<insert id="insertUser" parameterType="User" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO user (name, age) VALUES (#{name}, #{age})
</insert>

In the example above, the keyProperty attribute specifies the id attribute as the primary key attribute. When performing an insert operation, the generated primary key value will be populated in the id attribute.

It’s important to note that when using the keyProperty attribute, make sure the database supports auto-generated primary keys and that the corresponding database table has a rule for auto-generating primary keys.

Leave a Reply 0

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