How to obtain last insert id in Oracle using MyBatis?

后端 未结 4 1665
暗喜
暗喜 2020-12-16 07:01

I\'m inserting some data into an Oracle table and need to retrieve the id of the inserted row. Said id is being generated by a sequenc

相关标签:
4条回答
  • 2020-12-16 07:13

    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 sure to put the correct value in keyProperty.. I have a trigger before insert in oracle to get next id from sequence.

    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>
    
    0 讨论(0)
  • 2020-12-16 07:22

    Let's say the trigger uses id_seq Oracle sequence to get the id. If you execute from MyBatis using the same database session, the SQL

    select id_seq.currval from dual;
    

    You will get the ID used.

    0 讨论(0)
  • 2020-12-16 07:26

    With oracle, better is doing it in two phases. 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

    Second Phase:

    insert your object

    0 讨论(0)
  • 2020-12-16 07:33

    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>
    
    0 讨论(0)
提交回复
热议问题