• MyBatis在Oracle中插入数据并返回主键的问题解决


    引言:  在MyBatis中,希望在Oracle中插入数据之时,同一时候返回主键值,而非插入的条数...

    环境:MyBatis 3.2 , Oracle。 Spring 3.2

      SQL Snippet in XML Configuration:

    <insert id="insertSelective" parameterType="com.jxxx.p2pp.model.UUserInfo">
        <selectKey resultType="java.math.BigDecimal" order="BEFORE" keyProperty="id">
    	   SELECT U_USER_INFO_SEQ.Nextval as ID from DUAL
       </selectKey>
    	
        insert into U_USER_INFO
        <trim prefix="(" suffix=")" suffixOverrides="," >
          <if test="id != null" >
            ID,
          </if>
          <if test="userName != null" >
            USER_NAME,
          </if>
          <if test="realName != null" >
            REAL_NAME,
          </if>
        .....
    </insert>
    

    要点是这里使用了selectKey来定义返回新生成的PrimaryKey,这个情况只适用于Oracle。

    须要注意的地方是在Java代码中使用Integer类型。可是在MyBatis的映射文件里。使用java.math.BigDecimal类型,否则会报类型转换或者不匹配的错误。

    其它比方MySQL或者SQLServer的情况适用于下面情况:

        <insert id="insert" parameterType="Spares"   
                useGeneratedKeys="true" keyProperty="id">  
                insert into spares(spares_id,spares_name,  
                    spares_type_id,spares_spec)  
                values(#{id},#{name},#{typeId},#{spec})  
            </insert>  
    使用useGeneratedKeys/KeyProperty来实现插入数据的时候,来完毕新生成主键的返回。


    当中异常信息的解决:

    异常信息:

       org.springframework.jdbc.UncategorizedSQLException: Error getting generated key or setting result to parameter object. Cause: java.sql.SQLException: 无效的列类型: getBigDecimal not implemented for class oracle.jdbc.driver.T4CRowidAccessor
    ; uncategorized SQLException for SQL []; SQL state [99999]; error code [17004]; 无效的列类型: getBigDecimal not implemented for class oracle.jdbc.driver.T4CRowidAccessor; nested exception is java.sql.SQLException:
    无效的列类型: getBigDecimal not implemented for class oracle.jdbc.driver.T4CRowidAccessor


    问题解决:

        问题是在Java代码中设置返回的主键数据类型,当中返回的数据类型为java.lang.Integer,而非BigDecimal和Long. 可是在MyBatis中的映射文件里的类型为java.math.BigDecimal.



  • 相关阅读:
    cnn softmax regression bp求导
    使用kd-tree加速k-means
    KDTree详解及java实现
    加入商品分类信息,考虑用户所处阶段的 图模型 推荐算法 Rws(random walk with stage)
    用户标签
    LDA(latent dirichlet allocation)
    对物品进行反馈 代码
    1.虚拟机中安装ubuntu
    4.动态HTML处理和机器图像识别
    3.非结构化数据与结构化数据提取
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/5382243.html
Copyright © 2020-2023  润新知