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

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

内容简介:翻译自: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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

Designing Programmes

Designing Programmes

Karl Gerstner / Springer Verlag / 2007 / $499.00

Karl Gerstnera (TM)s work is a milestone in the history of design. One of his most important works is Designing Programmes, which is presented here in a new edition of the original 1964 publication. I......一起来看看 《Designing Programmes》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

SHA 加密
SHA 加密

SHA 加密工具

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

HEX HSV 互换工具