java – 获取mybatis中最后插入记录的id

栏目: Java · 发布时间: 7年前

内容简介:翻译自:https://stackoverflow.com/questions/12103606/get-the-id-of-last-inserted-record-in-mybatis
我是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字段自动递增,记录正确插入.

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


以上所述就是小编给大家介绍的《java – 获取mybatis中最后插入记录的id》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Shallows

The Shallows

Nicholas Carr / W. W. Norton & Company / 2011-6-6 / USD 15.95

"Is Google making us stupid?" When Nicholas Carr posed that question, in a celebrated Atlantic Monthly cover story, he tapped into a well of anxiety about how the Internet is changing us. He also crys......一起来看看 《The Shallows》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具