MyBatis Auto-Increment Primary Key Setup

MyBatis offers two options for setting auto-increment primary keys.

  1. Utilizing an auto-increment primary key in a database: Define the primary key field as auto-increment in the database, and then set the primary key field to generate automatically in the MyBatis mapping file, as shown below:
<insert id="insertUser" parameterType="User" useGeneratedKeys="true" keyProperty="id">
  INSERT INTO user(username, password) VALUES (#{username}, #{password})
</insert>

In the above example, the useGeneratedKeys property is set to true, and the keyProperty property specifies the name of the primary key field.

  1. Generate primary keys using UUID: Use UUID to generate primary keys in MyBatis mapping files, as shown below:
<insert id="insertUser" parameterType="User">
  <selectKey keyProperty="id" resultType="java.lang.String" order="BEFORE">
    SELECT REPLACE(UUID(), '-', '')
  </selectKey>
  INSERT INTO user(id, username, password) VALUES (#{id}, #{username}, #{password})
</insert>

In the example above, the selectKey element is utilized to generate a primary key and then set the generated key value to the property specified by keyProperty.

It should be noted that using auto-increment primary keys or UUIDs to generate primary keys requires defining the corresponding fields in the database.

bannerAds