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 完成插入数据库,并将主键返回的注意事项的更多相关文章

  1. MyBatis 插入记录同时获取主键

    MyBatis 插入记录同时获取主键 MyBatis 插入记录同时获取主键的系统界面 useGeneratedKeys 属性 keyProperty 属性 keyColumn 属性 selectKey ...

  2. Mybatis里Mapper映射sql文件里insert的主键返回selectKey使用

    有时候新增一条数据,知道新增成功即可,但是有时候,需要这条新增数据的主键,以便逻辑使用,再将其查询出来明显不符合要求,效率也变低了. 这时候,通过一些设置,mybatis可以将insert的数据的主键 ...

  3. insert主键返回 selectKey使用

    有时候新增一条数据,知道新增成功即可,但是有时候,需要这条新增数据的主键,以便逻辑使用,再将其查询出来明显不符合要求,效率也变低了. 这时候,通过一些设置,mybatis可以将insert的数据的主键 ...

  4. Mybatis获取数据库自增主键

    一般我们都为将表中主键列设置为自增,当我们执行插入语句时,比如这样 //测试添加 Employee employee = new Employee(null, "jerry4",n ...

  5. mybatis保存时将数据库自动生成的主键返回

    场景 保存订单数据和订单详情数据时需要将订单的主键作为关联子段添加到明细表中,需要将保存订单时的主键返回给供保存明细表时使用 添加xml中新增数据时的配置 <insert id="in ...

  6. mybatis的插入数据后的主键获取

    为什么要在插入数据后获取主键:当有一个订单表和订单详情表,当插入订单表的数据后,需要在订单详情表插入该订单的具体购物情况,订单详情表需要的一个列是订单表的主键或者订单ID.(通俗讲:A表的主键是B表的 ...

  7. MyBatis主键返回

    在使用MyBatis做持久层时,insert语句默认是不返回记录的主键值,而是返回插入的记录条数:如果业务层需要得到记录的主键时,可以通过配置的方式来完成这个功能. 比如在表的关联关系中,将数据插入主 ...

  8. mybatis主键返回的实现

    向数据库中插入数据时,大多数情况都会使用自增列或者UUID做为主键.主键的值都是插入之前无法知道的,但很多情况下我们在插入数据后需要使用刚刚插入数据的主键,比如向两张关联表A.B中插入数据(A的主键是 ...

  9. ibatis annotations 注解方式返回刚插入的自增长主键ID的值

    mybatis提供了注解方式编写sql,省去了配置并编写xml mapper文件的麻烦,今天遇到了获取自增长主键返回值的问题,发现相关问答比较少,还好最后还是圆满解决了,现把重点记录一下,解决问题的关 ...

随机推荐

  1. 【Codeforces 582A】 GCD Table

    [题目链接] 点击打开链接 [算法] G中最大的数一定也是a中最大的数.          G中次大的数一定也是a中次大的数. 第三.第四可能是由最大和次大的gcd产生的 那么就不难想到下面的算法: ...

  2. JavaScript-Tool:jquery.jsprint.js

    ylbtech-JavaScript-Tool:jquery.jsprint.js 一个通过单击页面按钮,便实现页面打印的jQuery插件jqprint. 1.返回顶部 1. 插件描述:一个通过单击页 ...

  3. java利用Aspose.words.jar将本地word文档转化成pdf(完美破解版 无水印 无中文乱码)

    package doc; import java.io.*; import junit.framework.Test; import com.aspose.words.*; public class ...

  4. Lua变量

    Lua 变量 变量在使用前,必须在代码中进行声明,即创建该变量. 编译程序执行代码之前编译器需要知道如何给语句变量开辟存储区,用于存储变量的值. Lua 变量有三种类型:全局变量.局部变量.表中的域. ...

  5. 为什么linux有足够的内存还进行swap?

    1.Linux在内存被用完之前开始交换.这是为了提高性能和响应能力: 性能提高是因为一些内存放磁盘缓存比方内存更合适.因此,最好将一个已经停用了一段时间的程序交换出去,而将经常使用的文件保存在缓存中. ...

  6. SDUT2161:Simple Game(NIM博弈+巴什博弈)

    传送门 题意 n堆石子,每次可以取一堆至三堆任意非零石子数,取完者赢,问最后谁能赢 分析 以前我们做过NIM博弈是对一堆进行操作,现在换成了三堆,其实对于n堆都一样一堆的情况 如果最后二进制每位数的1 ...

  7. POJ2063【完全背包】

    题意: 给一个初始的钱,年数, 然后给出每个物品的购买价格 与 每年获得的利益, 求在给出的年份后手上有多少钱. 思路: 背包重量还是资金. dp[0]=初始资金: 重物的重量是他的价格,获利是价值. ...

  8. Cg(C for Graphic)语言语义词与语义绑定详述 (转)

    摘抄“GPU Programming And Cg Language Primer 1rd Edition” 中文名“GPU编程与CG语言之阳春白雪下里巴人” 语义词( Semantic )与语义绑定 ...

  9. BERT的几个可能的应用

      BERT是谷歌公司于2018年11月发布的一款新模型,它一种预训练语言表示的方法,在大量文本语料(维基百科)上训练了一个通用的"语言理解"模型,然后用这个模型去执行想做的NLP ...

  10. 一起学Android之Activity

    概述 本文以一个简单的小例子,简述Android开发中Activity的相关知识,仅供学习分享使用. 什么是Activity? Activity是一个应用程序组件,通常显示为一个页面,用户可以通过Ac ...