How to get last insert id in Oracle using MyBatis?

I am inserting some data into an Oracle table and you need to get the id inserted row. The specified id generated by the sequence and then inserted into the table using a trigger.

Now I know that there are several ways to get the ID of the inserted row when using JDBC , but since I use MyBatis to execute the INSERT , I cannot figure out how to get the identifier after entering my data. Any advice would be greatly appreciated.

+4
source share
4 answers

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> 
+5
source

For me it works like this (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. Just believe the correct value in keyProperty .. I have a trigger before inserting into oracle to get the next identifier from the sequence.

Alternatively, this also works:

 <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> 
+1
source

Suppose a trigger uses the Oracle id_seq sequence to obtain an identifier. If you run from MyBatis using the same database session, SQL

 select id_seq.currval from dual; 

You will receive an identifier.

0
source

With the help of the oracle, it is better to do this in two stages. It works well, and the price is just one cartographer:

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 get seq, put the object’s place in your holder and

Second phase:

insert your object

0
source

All Articles