mybatis+oracle 完成插入数据库,并将主键返回的注意事项

本文详细介绍了在mybatis+oracle环境下进行数据插入时如何正确获取主键返回值,重点讲解了mapper.xml中useGeneratedKeys、keyColumn、resultType和keyProperty的设置,以及在不同数据库中selectKey order属性的使用注意事项,包括避免出现的错误和解决策略。

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

mybatis+oracle 完成插入数据库,并将主键返回的注意事项

一条插入语句就踩了不少的坑,
首先我的建表语句是:

create table t_openapi_batch_info(
	BATCH_NO                      VARCHAR2(200),
	UM_CODE                       VARCHAR2(50),
	BATCH_STATUS                  CHAR(1)   DEFAULT '0',
	BATCH_TYPE                    CHAR(1),
	CREATED_DATE                  DATE,
	CREATED_BY                    VARCHAR(100),
	UPDATED_DATE                  DATE
	UPDATED_BY                    VARCHAR(100)
	
)

CREATE SEQUENCE  SEQ_OPENAPI_BATCHNO
minvalue  0
maxvalue   999999999
start wuth  7342937
increate by  1
cache  40;

我写的mapper.xml的sql语句为:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper>
    <insert id="insertBatchInfo" parameterType="java.util.Map" useGeneratedKeys="true" keyColumn ="batchNo">
        <selectKey resultType="int" keyProperty="batchNo" order="BEFORE">
            select seq_openapi_batchno.nextval as batchNo from dual
        </selectKey>
        insert into t_openapi_batch_info
        <include refid="batchInfoKey"/>
        VALUES
        <include refid="batchInfoVal"/>
    </insert>

    <sql id="batchInfoKey">
        <trim prefix="(" suffix=")">
            batch_no,
            <if test="umCode!=null and umCode!=''">
                um_code,
            </if>
            <if test="batchStatus!=null and batchStatus!=''">
                batch_status,
            </if>
            <if test="batchType!=null and batchType!=''">
                batch_type,
            </if>
            created_by,created_date,updated_by,updated_date
        </trim>
    </sql>
    
    <sql id="batchInfoVal">
        <trim prefix="(" suffix=")">
            #{batchNo},
            <if test="umCode!=null and umCode!=''">
                #{umCode},
            </if>
            <if test="batchStatus!=null and batchStatus!=''">
                #{batchStatus},
            </if>
            <if test="batchType!=null and batchType!=''">
                #{batchType},
            </if>
            user,sysdate,user,sysdate
        </trim>
    </sql>
    
</mapper>

在这里插入图片描述

截取上面mapper文件中的重要的部分,
1.使用useGeneratedkey,默认为false,设置为true可以将需要的值返回
2.keyColumn这个值可以指定你需要返回的值,比如我需要返回批次号,那么就可以指定keyColumn的值为batchNo,此时我可以将batchNo绑定到map,当然,如果你的参数类型是dto的话,就会绑定到对应实体类的属性上面
,使用map.get(“batchNo”)就可以得到相应的值。

3.resultType=“int”,这里我踩得坑是将resultType写成了String类型**

 /**
   * 这个方法是对SqlSession的包装,对应insert、delete、update、select四种操作
   */
public Object execute(SqlSession sqlSession, Object[] args) {
    Object result;//返回结果
   //INSERT操作
    if (SqlCommandType.INSERT == command.getType()) {
      //处理参数
      Object param = method.convertArgsToSqlCommandParam(args);
      //调用sqlSession的insert方法 
      result = rowCountResult(sqlSession.insert(command.getName(), param));
    } else if (SqlCommandType.UPDATE == command.getType()) {
      //UPDATE操作 同上
      Object param = method.convertArgsToSqlCommandParam(args);
      result = rowCountResult(sqlSession.update(command.getName(), param));
    } else if (SqlCommandType.DELETE == command.getType()) {
      //DELETE操作 同上
      Object param = method.convertArgsToSqlCommandParam(args);
      result = rowCountResult(sqlSession.delete(command.getName(), param));
    } else if (SqlCommandType.SELECT == command.getType()) {
      //如果返回void 并且参数有resultHandler  ,则调用 void select(String statement, Object parameter, ResultHandler handler);方法  
      if (method.returnsVoid() && method.hasResultHandler()) {
        executeWithResultHandler(sqlSession, args);
        result = null;
      } else if (method.returnsMany()) {
        //如果返回多行结果,executeForMany这个方法调用 <E> List<E> selectList(String statement, Object parameter);   
        result = executeForMany(sqlSession, args);
      } else if (method.returnsMap()) {
        //如果返回类型是MAP 则调用executeForMap方法 
        result = executeForMap(sqlSession, args);
      } else {
        //否则就是查询单个对象
        Object param = method.convertArgsToSqlCommandParam(args);
        result = sqlSession.selectOne(command.getName(), param);
      }
    } else {
        //接口方法没有和sql命令绑定
        throw new BindingException("Unknown execution method for: " + command.getName());
    }
    //如果返回值为空 并且方法返回值类型是基础类型 并且不是VOID 则抛出异常  
    if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
      throw new BindingException("Mapper method '" + command.getName() 
          + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
    }
    return result;
  }


 private Object rowCountResult(int rowCount) {
    final Object result;
    if (method.returnsVoid()) {
      result = null;
    } else if (Integer.class.equals(method.getReturnType()) || Integer.TYPE.equals(method.getReturnType())) {
      result = rowCount;
    } else if (Long.class.equals(method.getReturnType()) || Long.TYPE.equals(method.getReturnType())) {
      result = (long) rowCount;
    } else if (Boolean.class.equals(method.getReturnType()) || Boolean.TYPE.equals(method.getReturnType())) {
      result = (rowCount > 0);
    } else {
      throw new BindingException("Mapper method '" + command.getName() + "' has an unsupported return type: " + method.getReturnType());
    }
    return result;
  }

所以通过源码我们可以知道insert ,update,delete操作只能返回int,lang,boolean类型,若返回string类型,就会报错。

4.keyProperty 是 selectKey 语句结果应该被设置的目标属性。

在这里插入图片描述
SelectKey需要注意order属性,像Mysql一类支持自动增长类型的数据库中,order需要设置为after才会取到正确的值。

像Oracle这样取序列的情况,需要设置为before

,否则会报错。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值