获取mybatis中最后插入记录的ID

use*_*884 9 java mysql ibatis 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>
Run Code Online (Sandbox Code Playgroud)

我认为这里写的语句'SELECT LAST_INSERT_ID()as id'应该返回最后插入记录的id但是我在插入记录后总是1.

我的mapper.java类我有方法

   int insertSelective(FileAttachment record);
Run Code Online (Sandbox Code Playgroud)

在我正在使用的dao课程中

int id = fileAttachmentMapper.insertSelective(fileAttachment);

插入新记录时,我的ID值始终为1.我的Id字段自动递增,记录正确插入.

jdd*_*lla 17

id被注入对象:

int num_of_record_inserted = fileAttachmentMapper.insertSelective(fileAttachment);

int id = fileAttachment.getId();
Run Code Online (Sandbox Code Playgroud)

selectKey在您插入的对象中设置id是什么,在这种情况下,fileAttachment在其属性id中插入AFTER记录.


Ruj*_*uju 10

你只需要使用

  <insert id="insert" parameterType="com.mycom.myproject.db.mybatis.model.FileAttachment" useGeneratedKeys="true" keyProperty="id" keyColumn="id"> 
Run Code Online (Sandbox Code Playgroud)

不需要在MyBatis中的insert标记内执行select查询.它为插入操作提供了新参数.在此定义useGeneratedKeys ="true",keyProperty ="id",keyColumn ="id".您可以通过以下方式检索id的值

  FileAttachment fileAttachment=fileAttachmentMapper.insertSelective(fileAttachment);
  Integer id=fileAttachment.getId();
Run Code Online (Sandbox Code Playgroud)

使用fileAttachment.getId()是因为在插入标记中定义了keyColumn ="id",您将获得FileAttachment的fileAttachment引用中的所有返回值.


sof*_*fia 6

实际上,MyBatis已经提供了此功能。您可以使用选项:“ useGeneratedKeys”来获取最后的插入ID。

这是MyBatis的解释(如果您想了解更多详细信息,可以转到MyBatis官方页面)。

useGeneratedKeys(仅插入和更新)这告诉MyBatis使用JDBC getGeneratedKeys方法检索数据库内部生成的密钥(例如,RDBMS中的自动增量字段,例如MySQL或SQL Server)。默认值:false

如果您使用的是xml:

<insert id="" parameterType="" useGeneratedKeys="true">
Run Code Online (Sandbox Code Playgroud)

如果您使用注释:

@Insert("your sql goes here")
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
int insert(FileAttachment fileAttachment) throws Exception;
Run Code Online (Sandbox Code Playgroud)

完成插入操作后,将调用 fileAttachment的setId()方法,并将其设置为最后插入的记录的ID。您可以使用fileAttachment的getId()来获取最后的插入ID。

我希望这会对您有所帮助。