1 processing in XML mapping files

Configure fetch record primary key values in the mapper

Define in the INSERT tag in XML:

  • UseGeneratedKeys is true, which is used to return the primary key ID,
  • KeyProperty represents a database record primary key field
  • KeyColumn represents the Java object member attribute name
 <! Select * from primary key where id = 1;
<insert id="insert" useGeneratedKeys="true" keyProperty="id"  keyColumn="id">
		insert  into t_user (name,age) values (#{name},#{age})
</insert>
Copy the code

2 Interface annotation processing

Set the parameters useGeneratedKeys, keyProperty, and keyColumn as follows in the interface mapper annotation @options

// Returns the primary key field id value
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
@Insert("insert into t_user (name,age) values (#{name},#{age})")
void insert(Student stu);
Copy the code

Mybatis 3 Plus

When BaseMapper’s Insert method is called, the auto-increment primary key is wrapped in an insert object by default

Talk about useGeneratedKeys

In MyBatis, it is allowed to set the parameter named “useGeneratedKeys” in 3 places as follows:

  • Set the useGeneratedKeys parameter in the Settings element
  • Set the useGeneratedKeys parameter in the XML mapper
  • Set the useGeneratedKeys parameter in the interface mapper
4.1 Set the useGeneratedKeys parameter in the Settings element

For databases that support automatic primary key generation, such as MySQL and SQL Server, set useGeneratedKeys to true. After adding records, you can obtain the ID of the primary key automatically generated by the database.

5 Precautions

When using useGeneratedKeys to generate a primary key, you cannot use @param annotations to pass parameters in the DAO layer, otherwise you cannot obtain the primary key.

///Dao layer code cannot pass arguments using @param annotations
/// Long savNewUser(@Param("user") User user);
 Long savNewUser( User user);
///Mapper corresponds to the mapping layer
 <insert id="add" useGeneratedKeys="true" keyProperty="id">
     insert into t_user(u_name,u_age) VALUES (#{user.userName},#{user.userAget})
 </insert>

Copy the code