MyBatis gets the self growing field value of the inserted record of ID

  • 2020-11-18 06:16:16
  • OfStack

Step 1:

Add attributes to Mybatis Mapper file" useGeneratedKeys "And" keyProperty ", keyProperty Is the property name of the Java object!


<insert id="insert" parameterType="Spares" 
 useGeneratedKeys="true" keyProperty="id">
 insert into spares(spares_id,spares_name,
  spares_type_id,spares_spec)
 values(#{id},#{name},#{typeId},#{spec})
 </insert>

Step 2:

After Mybatis executes the insert statement, it automatically assigns the auto-growth value to the property id of object Spares. Therefore, it can be obtained by Spares's corresponding getter method!


 /**
 *  The new spare parts 
 * @author hellostory
 * @param spares
 * @return
 */
 @RequestMapping(value = "/insert")
 @ResponseBody
 public JsonResponse insert(Spares spares) {
 int count = sparesService.insert(spares);
 System.out.println(" A total of insert " + count + " Record! "
  + "\n The auto-growth value of the primary key just inserted into the record is: " + spares.getId());

ps: mybatis returns the self-growing id for inserted data

The test feedback of one bug today is that the newly registered users can see the report of all the users, but the old users have no problem. When checking the log, it was found that the original query was id of the newly registered users as null, so the full table valid data query was conducted. But the table's primary key is not allowed to be empty, so how can a new registered user id be null? The reason is that the code in the service layer returns the parameter object directly, while xml does not do any configuration.

The specific solution is the insert method configuration in xml


useGeneratedKeys= " true "  keyProperty= " registerId " 

The keyProperty value corresponds to the primary key attribute in the entity VO object

The details are as follows:


<code class="hljs java">@Override
  public Registers create(Registers r) {
    registersMapper.insert(r);
    return r;
  }</code>

The insert method of registermapper is as follows:


<code class="hljs xml"><insert id="insert" keyproperty="registerId" parametertype="com.ciji.zzaservice.pojo.base.Registers" usegeneratedkeys="true">

Execute the normal insert statement


</insert></code>

In this way, the self-growing primary key of the newly inserted data can be obtained in the controller layer.

The web site explains what it means to add two attributes to xml:

useGeneratedKeys

(useful for insert only) this tells MyBatis to use JDBC's getGeneratedKeys method to extract primary keys generated internally by data (e.g., auto-increments fields of database management systems such as MySQL and SQL Server). Default: false.

keyProperty

(useful for insert only) tag 1 attribute, and MyBatis sets its value either through getGeneratedKeys or through the selectKey child element of the insert statement. Default: Not set.

conclusion


Related articles: