Get the id of last inserted record in mybatis

I am newbie to mybatis. I am trying to get the id of last inserted record. My database is mysql and my mapper xml is

  <insert id="insertSelective"  parameterType="com.mycom.myproject.db.mybatis.model.FileAttachment" >
  <selectKey resultType="java.lang.Long" keyProperty="id" order="AFTER" >
  SELECT LAST_INSERT_ID() as id
</selectKey>
 insert into fileAttachment
<trim prefix="(" suffix=")" suffixOverrides="," >
  <if test="name != null" >
    name,
  </if>
  <if test="attachmentFileSize != null" >
    size,
  </if>      
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
  <if test="name != null" >
    #{name,jdbcType=VARCHAR},
  </if>
 <if test="attachmentFileSize != null" >
    #{attachmentFileSize,jdbcType=INTEGER},
  </if>
 </trim>
 </insert>

I thought statement written here ‘SELECT LAST_INSERT_ID() as id’ should return id of last inserted record but I am getting always 1 after inserting the record.

My mapper.java class I have method

   int insertSelective(FileAttachment record);

In my dao class I am using

int id = fileAttachmentMapper.insertSelective(fileAttachment);

I am getting value of Id always 1 when new record is inserted. my Id field is auto incremented and records are inserting properly.

Answer

The id is injected in the object:

int num_of_record_inserted = fileAttachmentMapper.insertSelective(fileAttachment);

int id = fileAttachment.getId();

What selectKey does is to set the id in the object you are inserting, in this case in fileAttachment in its property id and AFTER record is inserted.

Leave a Reply

Your email address will not be published. Required fields are marked *