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.




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM