我是mybatis新手。我正在尝试获取最后插入记录的 ID。我的数据库是 mysql,我的 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 字段自动递增并且记录正确插入。
最佳答案
对象中注入(inject)id:
int num_of_record_inserted = fileAttachmentMapper.insertSelective(fileAttachment);
int id = fileAttachment.getId();
selectKey
所做的是在您要插入的对象中设置 id,在本例中是在 fileAttachment
的属性 id
和 AFTER 中插入记录。
关于java - 获取mybatis最后插入记录的id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12103606/