首页 技术 正文
技术 2022年11月19日
0 收藏 904 点赞 2,800 浏览 1530 个字

在MyBatis中,希望在Oracle中插入数据的同时返回主键值,而非插入的条数。

① oracle使用 selectKey。

U_USER_INFO_SEQ 是在数据库中定义好的这张表关联的序列sequence,
Nextval是获取自增的id
<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.

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,075
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,551
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,399
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,176
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,811
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,892