天天看点

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

作者:java小悠

一、useGeneratedKeys 是什么 ?

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

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

二、如何使用?

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

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

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

  1. application.yml 配置文件
  2. 通过 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 复制代码
  3. mybatis-config.xml
  4. 通过<setting name="useGeneratedKeys" value="true" />激活useGeneratedKeys.
  5. <?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
  2. <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 数据库字段名称
Mybatis 中如何使用 useGeneratedKeys 获取自增主键

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;
}
复制代码           
原文链接:https://juejin.cn/post/7187567574522167355

继续阅读