Mybatis使用useGeneratedKeys获取自增主键

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Mybatis使用useGeneratedKeys获取自增主键

Applehope   2023-02-03 我要评论

一、useGeneratedKeys 是什么 ?

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

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

二、如何使用?

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

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

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

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

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 参数。

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

代码示例如下:

  • Mybatis 侧
import java.util.List;
public interface BigdataMapper {
    List&lt;BigdataGroup&gt; getBigdataGroup();
    int addBigdataGroup(BigdataGroup bigdataGroup);
}
  • service 侧
public int addBigdataGroup(BigdataGroup bigdataGroup) {
    bigdataGroup.setCreateBy(SecurityUtils.getUsername());
    int update = bigdataMapper. addBigdataGroup(bigdataGroup);
    log.info("update: {}", update);
    return update;
}
  • 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

注意:真实的 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;
}

结语

英文原文:zditect.com/code/mybati…

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们