[英]How to obtain last insert id in Oracle using MyBatis?
I'm inserting some data into an Oracle
table and need to retrieve the id
of the inserted row. 我将一些数据插入到Oracle
表中,需要检索插入行的id
。 Said id
is being generated by a sequence and then inserted to the table by a trigger. 所述id
由序列生成,然后通过触发器插入到表中。
Now, I know there are several ways to get the id of the inserted row when using JDBC
, but since I'm using MyBatis
to execute the INSERT
command, I can't seem to figure out how to obtain the id after inserting my data. 现在,我知道有几种方法可以在使用JDBC
时获取插入行的id,但由于我使用MyBatis
来执行INSERT
命令,我似乎无法弄清楚如何在插入数据后获取id 。 Any advice would be greatly appreciated. 任何建议将不胜感激。
Something like this should work 这样的事情应该有效
class User {
int userId
...
}
<insert id="addUser" useGeneratedKeys="true" keyColumn="user_id" keyProperty="userId">
INSERT INTO user(login, name,...) VALUES(#{login}, #{name},...
</insert>
For me it works like this (mybatis 3) 对我来说它的工作原理如下(mybatis 3)
<insert id="create" parameterType="Project" useGeneratedKeys="true" keyProperty="project.projectId" keyColumn="PROJECT_ID">
INSERT INTO PROJECT (TITLE,DESCRIPTION)
VALUES
(#{title},#{description})
</insert>
No need for selectKey. 不需要selectKey。 Just sure to put the correct value in keyProperty.. I have a trigger before insert in oracle to get next id from sequence. 只需确保在keyProperty中输入正确的值。我在插入oracle之前有一个触发器,以便从序列中获取下一个id。
Alternatively this works also: 或者,这也有效:
<insert id="createEmpty" statementType="CALLABLE" parameterType="Panelist">
BEGIN INSERT INTO PANELIST(PANEL_ID) VALUES (#{panelId})
RETURNING PANELIST_ID INTO
#{panelist.panelistId,mode=OUT,jdbcType=INTEGER}; END;
</insert>
Let's say the trigger uses id_seq Oracle sequence to get the id. 假设触发器使用id_seq Oracle序列来获取id。 If you execute from MyBatis using the same database session, the SQL 如果使用相同的数据库会话从MyBatis执行SQL
select id_seq.currval from dual;
You will get the ID used. 您将获得使用的ID。
With oracle, better is doing it in two phases. 有了oracle,更好的是分两个阶段完成。 Works well and the price is only one more mapper: 效果很好,价格只有一个映射器:
First phase: 第一阶段:
<?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 namespace="com.sample.work.dao.SequencerMapper" >
<select id="selectNextId" resultType="long" >
select seq_sample.nextval from dual
</select>
</mapper>
You obtain the seq, put into your object place holder and 你获得seq,放入你的对象占位符和
Second Phase: 第二阶段:
insert your object 插入你的对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.