Skip to content
Advertisement

MyBatis oracle insert new row always return wrong primary id value

Try to get the primary id after inserting a new row to oracle DB

<insert id="createActivityLog" parameterType="ActivityLog" >
  <selectKey keyProperty="id" resultType="java.lang.Integer" order="BEFORE">
      select ACTIVITY_LOG_SEQ.nextval as id from dual
  </selectKey>  
  insert into ACTIVITY_LOG (
         activity_log_id,
         notes,
         details            )
  values (
     #{id,jdbcType=NUMERIC},
     #{notes,jdbcType=VARCHAR},
     #{details,jdbcType=VARCHAR}
  )

Here is the java call

Integer myId=(Integer) activityLogDao.createActivityLog(alog);

New data/row can be inserted into DB with no issue with correct primary key/id. But myID is always returned as 1(supposed to be 8971). How can I get the correct value. Thanks in advcance.

version:

    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.6</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.2</version>
    </dependency>

Answer

Your insert returns 1 on success and 0 on failure. If you want to use the primary key, use getId() of the object you used to insert.

*example)

activityLogDao.createActivityLog(alog);
Integer myId = alog.getId();
Advertisement