MyBatis insert语句selectKey标签和返回主键

本文详细介绍了Mybatis中如何在插入操作后利用<selectKey>元素获取主键,重点讲解了order属性对结果的影响,并通过代码示例展示了在BstSmsTplInstMapper.xml中的应用。适合处理数据库插入后主键获取的需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、简要概述

  1. keyProperty:对应的domain 对象中需要被赋值的属性,一般是主键
  2. resultType:表示的是返回主键的类型
  3. order:如果设置为 BEFORE,那么它会首先选择主键,设置 keyProperty 然后执行插入语句。如果设置为 AFTER,那么先执行插入语句,然后是 selectKey 元素
    注意:SelectKey需要注意order属性,像MySQL一类支持自动增长类型的数据库中,order需要设置为after才会取到正确的值,像Oracle这样取序列的情况,需要设置为before。
  4. mybatis代码片段
<selectKey keyProperty="tpl_inst_id" resultType="long" order="BEFORE">
      SELECT SEQ_BST_SMS_TPL_INST.NEXTVAL FROM DUAL
</selectKey>

二、使用场景

当我们往数据库插入一条记录以后,有时我们接下来的操作需要这条记录的主键。如果在插入后在去查询一下数据库,显然不太遵循Java开发的规范(不够优雅和效率),mybatis正好提供了insert之后返回主键的功能。

三、代码介绍

  1. BstSmsTplInstMapper.xml文件代码如下
<insert id="save" parameterType="com.asiainfo.bst.entity.BstSmsTplInst">
        <selectKey keyProperty="tpl_inst_id" resultType="long" order="BEFORE">
            SELECT SEQ_BST_SMS_TPL_INST.NEXTVAL FROM DUAL
        </selectKey>
        INSERT INTO BST_SMS_TPL_INST
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="tpl_inst_id != null">
                tpl_inst_id,
            </if>
            <if test="busi_intf_seq != null">
                busi_intf_seq,
            </if>
            <if test="msg_code != null">
                msg_code,
            </if>
            <if test="sys_code != null">
                sys_code,
            </if>
            <if test="scene_code != null">
                scene_code,
            </if>
            <if test="rule_code != null">
                rule_code,
            </if>
            <if test="tpl_code != null">
                tpl_code,
            </if>
            <if test="tpl_form != null">
                tpl_form,
            </if>
            <if test="tpl_engine != null">
                tpl_engine,
            </if>
            <if test="tpl_param_inst != null">
                tpl_param_inst,
            </if>
            <if test="src_nbr != null">
                src_nbr,
            </if>
            <if test="dest_nbr_array != null">
                dest_nbr_array,
            </if>
            <if test="staff_code != null">
                staff_code,
            </if>
            <if test="send_priority != null">
                send_priority,
            </if>
                send_time,
                create_time,
        </trim>
        <trim prefix="VALUES (" suffix=")" suffixOverrides=",">
            <if test="tpl_inst_id != null">
                #{tpl_inst_id,jdbcType=NUMERIC},
            </if>
            <if test="busi_intf_seq != null">
                #{busi_intf_seq,jdbcType=VARCHAR},
            </if>
            <if test="msg_code != null">
                #{msg_code,jdbcType=VARCHAR},
            </if>
            <if test="sys_code != null">
                #{sys_code,jdbcType=VARCHAR},
            </if>
            <if test="scene_code != null">
                #{scene_code,jdbcType=VARCHAR},
            </if>
            <if test="rule_code != null">
                #{rule_code,jdbcType=VARCHAR},
            </if>
            <if test="tpl_code != null">
                #{tpl_code,jdbcType=VARCHAR},
            </if>
            <if test="tpl_form != null">
                #{tpl_form,jdbcType=TIMESTAMP},
            </if>
            <if test="tpl_engine != null">
                #{tpl_engine,jdbcType=TIMESTAMP},
            </if>
            <if test="tpl_param_inst != null">
                #{tpl_param_inst,jdbcType=VARCHAR},
            </if>
            <if test="src_nbr != null">
                #{src_nbr,jdbcType=VARCHAR},
            </if>
            <if test="dest_nbr_array != null">
                #{dest_nbr_array,jdbcType=VARCHAR},
            </if>
            <if test="staff_code != null">
                #{staff_code,jdbcType=VARCHAR},
            </if>
            <if test="send_priority != null">
                #{send_priority,jdbcType=VARCHAR},
            </if>
                sysdate,
                sysdate,
        </trim>
    </insert>
  1. 业务逻辑代码如下:
 try {
 			### xxx实例表实例化后保存数据库
            bstSmsTplInstDao.save(bstSmsTplInst);
            ### 获取主键ID
            resMap.put("tplInstId",bstSmsTplInst.getTpl_inst_id().toString());
        } catch (DataAccessException dae) {
            updateMsgStatus(bstBusiMsg, ErrorMsg.HANDLE_FAIL_STATUS, countMap, dae.getMessage());
            log.error("插入模板实例表异常,请检查!", dae);
            errorMap.put("status", ErrorMsg.HANDLE_FAIL_STATUS);
            return errorMap;
        }
//8. 写入实时任务表
long tplInstId = Long.valueOf(resultMap.get("tplInstId"));

四、代码介绍

以上就是我在工作中所遇到的场景,以及如何处理该问题的方法。如果有什么问题欢迎大家在评论区进行探讨!!!

### 使用 MyBatis 执行 `INSERT INTO SELECT` 并返回多个自增主键 当使用 MyBatis 对数据库执行批量插入操作,特别是通过 `INSERT INTO SELECT` 形式的语句时,如果需要获取新插入记录的自增主键值,则需特别注意配置实现细节。 对于 MySQL 数据库而言,由于其支持单次多行插入并能返回所有生成的主键ID列表,因此可以通过特定的方式捕获这些值。然而,在默认情况下,MyBatis 的 `<selectKey>` 或者 `useGeneratedKeys=true` 参数仅适用于简单的单条插入场景[^1]。 为了处理更复杂的 `INSERT INTO SELECT` 场景下的主键回显需求: #### 方法一:利用存储过程或函数 可以考虑编写一个存储过程或者用户定义函数来完成这一任务,并在其中调用相应的 SQL 逻辑以及收集产生的 ID 值。接着可以在 Mapper XML 文件里声明对该存储过程/函数的调用接口。 ```xml <update id="batchInsertWithIds" parameterType="map"> CALL batch_insert_and_get_ids( #{sourceTable, jdbcType=VARCHAR}, #{targetColumns, jdbcType=VARCHAR}, #{resultProperty, mode=OUT, javaType=list, jdbcType=CURSOR, resultMap=idResultMap} ) </update> ``` 这里假设有一个名为 `idResultMap` 的映射用于解析游标中的每一项作为单独的结果集成员。 #### 方法二:借助 JDBC Batch API Last Insert Ids 另一种解决方案是手动控制整个批处理流程,即先准备一批待插入的数据集合,再逐一遍历它们并通过 Java 代码配合 PreparedStatement 来提交事务,最后读取每次插入后的最后一个插入 ID(last inserted id)。需要注意的是这种方法可能效率较低且依赖于具体的驱动程序特性。 ```java public List<Long> performBatchInsertAndGetIds(List<Item> items) { String sql = "INSERT INTO target_table (col1, col2,...) VALUES (?, ?, ...)"; try(Connection conn = dataSource.getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { for(Item item : items){ // 设置参数... pstmt.addBatch(); } int[] updateCounts = pstmt.executeBatch(); ResultSet rs = pstmt.getGeneratedKeys(); List<Long> generatedIdList = new ArrayList<>(); while(rs.next()){ Long id = rs.getLong(1); generatedIdList.add(id); } return generatedIdList; } catch(SQLException e){ throw new RuntimeException(e.getMessage(),e); } } ``` 上述例子展示了如何在一个循环内填充预编译语句并将之加入批次队列中去,之后一次性发送给服务器端执行;紧接着访问由 `getGeneratedKeys()` 提供的结果集以提取每一个被创建出来的唯一标识符[^4]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值