,我的mapper xml是
<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>
我认为这里写的语句’SELECT LAST_INSERT_ID()as id’应该返回最后插入记录的id但是我在插入记录后总是1.
我的mapper.java类我有方法
int insertSelective(FileAttachment record);
在我正在使用的dao课程中
int id = fileAttachmentMapper.insertSelective(fileAttachment);
插入新记录时,我的ID值始终为1.我的Id字段自动递增,记录正确插入.
id被注入对象:
int num_of_record_inserted = fileAttachmentMapper.insertSelective(fileAttachment); int id = fileAttachment.getId();
selectKey做的是在你要插入的对象中设置id,在这种情况下,在fileAttachment中输入其属性id并插入AFTER记录.
翻译自:https://stackoverflow.com/questions/12103606/get-the-id-of-last-inserted-record-in-mybatis