SpringBoot Mybatis keyProperty和useGeneratedKeys的作用

在使用mybatis时,常常会出现这种需求:
当主键是自增的情况下,添加一条记录的同时,其主键是不能被使用的(为空),但是有时我们需要该主键,这时我们该如何处理呢?这时我们只需要在其对应xml中加入以下属性即可:

<insert id="insertSelective" parameterType="com.vmware.miaosha.dataobject.UserPasswordDO" keyProperty="id" useGeneratedKeys="true">

示例代码:

// 实现model -> dataObject方法
UserDO userDO = convertFromModel(userModel);

// insertSelective与insert的区别:
// insertSelective 如果数据库中表字段设置了默认值,那么插入的值为空,就使用数据库默认的值。
// insert 如果插入的值为空,就会使用null覆盖数据库中表字段设置的默认值
userDOMapper.insertSelective(userDO);

userModel.setId(userDO.getId());   // userDO中就包含了“自增的ID”

UserPasswordDO userPasswordDO = convertPasswordFromModel(userModel);
userPasswordDOMapper.insertSelective(userPasswordDO);
原文地址:https://www.cnblogs.com/vincenshen/p/10399824.html