mybatis+oracle 完成插入数据库,并将主键返回的注意事项
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;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
我写的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>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
截取上面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(http://www.my516.com))) {
result = (rowCount > 0);
} else {
throw new BindingException("Mapper method '" + command.getName() + "' has an unsupported return type: " + method.getReturnType());
}
return result;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
所以通过源码我们可以知道insert ,update,delete操作只能返回int,lang,boolean类型,若返回string类型,就会报错。
4.keyProperty 是 selectKey 语句结果应该被设置的目标属性。
SelectKey需要注意order属性,像Mysql一类支持自动增长类型的数据库中,order需要设置为after才会取到正确的值。
像Oracle这样取序列的情况,需要设置为before
,否则会报错。
---------------------
mybatis+oracle 完成插入数据库,并将主键返回的注意事项的更多相关文章
- MyBatis 插入记录同时获取主键
MyBatis 插入记录同时获取主键 MyBatis 插入记录同时获取主键的系统界面 useGeneratedKeys 属性 keyProperty 属性 keyColumn 属性 selectKey ...
- Mybatis里Mapper映射sql文件里insert的主键返回selectKey使用
有时候新增一条数据,知道新增成功即可,但是有时候,需要这条新增数据的主键,以便逻辑使用,再将其查询出来明显不符合要求,效率也变低了. 这时候,通过一些设置,mybatis可以将insert的数据的主键 ...
- insert主键返回 selectKey使用
有时候新增一条数据,知道新增成功即可,但是有时候,需要这条新增数据的主键,以便逻辑使用,再将其查询出来明显不符合要求,效率也变低了. 这时候,通过一些设置,mybatis可以将insert的数据的主键 ...
- Mybatis获取数据库自增主键
一般我们都为将表中主键列设置为自增,当我们执行插入语句时,比如这样 //测试添加 Employee employee = new Employee(null, "jerry4",n ...
- mybatis保存时将数据库自动生成的主键返回
场景 保存订单数据和订单详情数据时需要将订单的主键作为关联子段添加到明细表中,需要将保存订单时的主键返回给供保存明细表时使用 添加xml中新增数据时的配置 <insert id="in ...
- mybatis的插入数据后的主键获取
为什么要在插入数据后获取主键:当有一个订单表和订单详情表,当插入订单表的数据后,需要在订单详情表插入该订单的具体购物情况,订单详情表需要的一个列是订单表的主键或者订单ID.(通俗讲:A表的主键是B表的 ...
- MyBatis主键返回
在使用MyBatis做持久层时,insert语句默认是不返回记录的主键值,而是返回插入的记录条数:如果业务层需要得到记录的主键时,可以通过配置的方式来完成这个功能. 比如在表的关联关系中,将数据插入主 ...
- mybatis主键返回的实现
向数据库中插入数据时,大多数情况都会使用自增列或者UUID做为主键.主键的值都是插入之前无法知道的,但很多情况下我们在插入数据后需要使用刚刚插入数据的主键,比如向两张关联表A.B中插入数据(A的主键是 ...
- ibatis annotations 注解方式返回刚插入的自增长主键ID的值
mybatis提供了注解方式编写sql,省去了配置并编写xml mapper文件的麻烦,今天遇到了获取自增长主键返回值的问题,发现相关问答比较少,还好最后还是圆满解决了,现把重点记录一下,解决问题的关 ...
随机推荐
- Luogu网校听课笔记(自用
TG助学课——noilinux 8.2 深夜 Noi Linux的使用——darkflames的博客 #include<bits/stdc++.h> using namespace std ...
- backface-visibility
浏览器支持 只有 Internet Explorer 10+ 和 Firefox 支持 backface-visibility 属性. Opera 15+.Safari 和 Chrome 支持替代的 ...
- scp.sh
#!/bin/sh #Auto change server files #liudong 2016-3-21 if [ ! -f ip.txt ];then echo -e "\033[31 ...
- lua ffi简介
本文转自网络 由来 FFI库,是LuaJIT中最重要的一个扩展库.它允许从纯Lua代码调用外部C函数,使用C数据结构.有了它,就不用再像Lua标准math库一样,编写Lua扩展库.把开发者从开发Lua ...
- 【旧文章搬运】更正一个枚举PspCidTable时的错误
原文发表于百度空间及看雪论坛,2009-02-27 看雪论坛地址:https://bbs.pediy.com/thread-82919.htm============================= ...
- iOS 中的 Block
参考:链接 (1)block作为本地变量(local variable) returnType (^blockName)(parameterTypes) = ^returnType(parameter ...
- windows下patch
经常在网上看到有人发布patch文件来更新他们的开源代码,例如cegui.ogre等都使用这种形式来修bug或者增加一些小功能.但是,我们下载到的patch文件,貌似是linux/unix的diff工 ...
- eclipse导入工程报Invalid project description(转载)
转自:http://blog.sina.com.cn/s/blog_a2eab3000101k3r7.html 昨天新搭建的环境,今天把以前的项目导入eclipse时报错: 说的是我导入的项目与wor ...
- Codeforces Round #408 (Div. 2) C.Bank Hacking(二分)
传送门 题意 给出n个银行,银行之间总共有n-1条边,定义i与j有边相连为neighboring,i到j,j到k有边,则定义i到k的关系为semi- neighboring, 每家银行hack的难度为 ...
- python 迭代器 Iterator
一.可迭代对象定义 可以直接作用于for循环的数据类型有以下几种: 一类是集合数据类型,如list.tuple.dict.set.str.bytes.bytearray等: 一类是generator, ...