问题描述
我是mybatis的新手。我想获取最后插入记录的ID。我的数据库是mysql,我的mapper xml是
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>
我认为这里写的语句'SELECT LAST_INSERT_ID()as id'应该返回最后插入记录的id但是插入记录后我总是1。
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.
我的mapper.java类我有方法
My mapper.java class I have method
int insertSelective(FileAttachment record);
在我的dao课程中我使用
In my dao class I am using
int id = fileAttachmentMapper.insertSelective(fileAttachment);
int id = fileAttachmentMapper.insertSelective(fileAttachment);
插入新记录时,我的ID值始终为1。我的Id字段自动递增,记录正确插入。
I am getting value of Id always 1 when new record is inserted. my Id field is auto incremented and records are inserting properly.
推荐答案
id被注入对象:
int num_of_record_inserted = fileAttachmentMapper.insertSelective(fileAttachment);
int id = fileAttachment.getId();
selectKey
做的是设置id在你要插入的对象中,在这种情况下在 fileAttachment
中的属性 id
并插入AFTER记录。
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.
这篇关于获取mybatis中最后插入记录的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!