Mybatis 中如何使用 useGeneratedKeys 获取自增主键

一、useGeneratedKeys 是什么 ?

关于useGeneratedKeys,官方的说法是,这个参数的作用是:"允许 JDBC 支持自动生成主键,需要驱动兼容",如何理解这句话的含义?

其原意是。对于支持自动生成记录主键的数据库,如 MySQL 和 SQL Server,此时将 useGeneratedKeys 参数的值设置为 true,则进行 INSERT 操作后,数据库自动生成的主键会填充到 Java 实体属性中,我们可以从 Java 实体属性中获得数据库自动生成的主键 ID。


二、如何使用?

配置useGeneratedKeys,可以通过以下方式实现:

  • 配置全局配置文件
  • 在 xml 映射器中配置 useGeneratedKeys 参数
  • 在接口映射器中设置 useGeneratedKeys 参数

2.1 在 mybatis 的全局配置文件中配置

  1. application.yml 配置文件

    • 通过 configLocation 指定 mybatis 的配置文件 mybatis-config.xml

      # MyBatis configuration
      mybatis:
          # Search for the specified package alias
          typeAliasesPackage: com.ruoyi.**.domain
          # Configure mapper scan to find all mapper.xml mapping files
          mapperLocations: classpath*:mapper/**/*Mapper.xml
          # Load the global configuration file
          configLocation: classpath:mybatis/mybatis-config.xml
      
      
  2. mybatis-config.xml

    • 通过<setting name="useGeneratedKeys" value="true" />激活useGeneratedKeys.

      <?xml version="1.0" encoding="UTF-8" ?>
      <! DOCTYPE configuration
      PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
      "http://mybatis.org/dtd/mybatis-3-config.dtd">
      <configuration>
      
              <settings>
                      <setting name="cacheEnabled" value="true" /> <!-- global mapper enables caching -->
                      <setting name="useGeneratedKeys" value="true" /> <!-- Allow JDBC to support automatic generation of primary keys -->
                      <setting name="defaultExecutorType" value="REUSE" /> <!-- configure the default executor -->
                      <setting name="logImpl" value="SLF4J" /> <!-- Specify the specific implementation of the log used by MyBatis -->
      <!-- <setting name="mapUnderscoreToCamelCase" value="true"/> <!– CamelCase naming–>-->
              </settings>
      
      </configuration>
      
      

注意:在settings元素中设置的全局 useGeneratedKeys 参数对 xml 后缀的 mapper 无效。如果你想在 xml 后缀的 mapper 中添加记录后返回主键 ID,你必须在 xml 后缀的 mapper 中明确设置useGeneratedKeys参数的值为 true。

2.2 在 xml mapper 中配置 useGeneratedKeys 参数。

  1. Mapper.xml

    <insert id="addBigdataGroup" parameterType="BigdataGroup" useGeneratedKeys="true" keyProperty="groupId" keyColumn="group_id">
            insert into bigdata_group (
            group_id, group_name, comment, business_line, create_by, remark, create_time)
            values(#{groupId}, #{groupName}, #{comment}, #{businessLine}, #{createBy}, #{remark}, sysdate() );
    </insert>
    
    
  • parameterType 传入参数类型
  • keyProperty JAVA 对象中的属性名称
  • keyColumn 数据库字段名称

keyProperty与keyColumn的关系图示(来自网络).png

再次说明:在 xml mapper 中配置的 useGeneratedKeys 参数只影响 xml mapper,设置元素中设置的全局 useGeneratedKeys 参数值对 xml mapper 没有影响。

2.3 在 interface mapper 中设置 useGeneratedKeys 参数

设置 useGeneratedKeys 为 true,返回由数据库自动生成的记录主键 id。

@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
@Insert("insert into test(name,descr,url,create_time,update_time) values(#{name},#{descr},#{url},now(),now())")
Integer insertOneTest(Test test);

注意:在 interface mapper 中设置的 useGeneratedKeys参数将覆盖 mybatis 配置文件中 setting 元素内所配置的useGeneratedKeys的值。

另外笔者的实践中,keyProperty = "id"并未生效,需要设置为keyProperty = "test.id";即参数的名称 + . + 主键属性名。 读者老师需结合自己的环境试一试。

三、遇到的问题

在配置了获得主键 ID 后,但返回的结果并没有像预期的那样返回新插入数据库行的主键的真实数据。但返回的居然1

代码示例如下:

  1. Mybatis 侧
import java.util.List;

public interface BigdataMapper {

    List<BigdataGroup> getBigdataGroup();

    int addBigdataGroup(BigdataGroup bigdataGroup);
}

  1. service 侧
public int addBigdataGroup(BigdataGroup bigdataGroup) {
    bigdataGroup.setCreateBy(SecurityUtils.getUsername());

    int update = bigdataMapper. addBigdataGroup(bigdataGroup);
    log.info("update: {}", update);
    return update;
}

  1. xml file侧
<insert id="addBigdataGroup" parameterType="BigdataGroup" useGeneratedKeys="true" keyProperty="groupId" keyColumn="group_id">
    insert into bigdata_group (
    group_id, group_name, comment, business_line, create_by, remark, create_time)
    values(#{groupId}, #{groupName}, #{comment}, #{businessLine}, #{createBy}, #{remark}, sysdate() );
</insert>

  1. 打印结果

按理说,返回的结果应该是插入后主键中的真实数据,但返回结果是1

注意:真实的 id 已经被注入到参数传递对象的主键的相应属性中,方法的返回值实际表示的是插入的行数,因为插入了 1 条记录,所以返回值是 1;如果要获得新添加数据的自增ID,那么只需要读取对象中对应的自增ID属性的值。

修改获取主键值的方式:

public int addBigdataGroup(BigdataGroup bigdataGroup) {
    bigdataGroup.setCreateBy(SecurityUtils.getUsername());

    int update = bigdataMapper. addBigdataGroup(bigdataGroup);
    log.info("update: {}", update);
    // Add the following code
    int group_id = bigdataGroup. getGroupId();
    log.info("group_id: {}", group_id);
    // stop here
    return update;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值