码迷,mamicode.com
首页 > 其他好文 > 详细

Mybatis 插入数据后返回主键值

时间:2014-08-18 22:13:03      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   java   使用   os   

Oracle中获取刚刚插入记录的主键值:

<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与SQL Server获取刚刚插入数据的主键值:

    <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.


转自:MyBatis返回主键值

Mybatis 插入数据后返回主键值,布布扣,bubuko.com

Mybatis 插入数据后返回主键值

标签:des   style   blog   http   color   java   使用   os   

原文地址:http://my.oschina.net/KingPan/blog/304063

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!