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

时间:2012-08-24 05:30:32

标签: 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>

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

我的mapper.java类我有方法

   int insertSelective(FileAttachment record);

在我的dao课程中,我正在使用

int id = fileAttachmentMapper.insertSelective(fileAttachment);

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

8 个答案:

答案 0 :(得分:16)

id被注入对象:

int num_of_record_inserted = fileAttachmentMapper.insertSelective(fileAttachment);

int id = fileAttachment.getId();

selectKey的作用是在您要插入的对象中设置ID,在本例中,在fileAttachment的属性id中插入AFTER记录。

答案 1 :(得分:8)

您只需要使用

  <insert id="insert" parameterType="com.mycom.myproject.db.mybatis.model.FileAttachment" useGeneratedKeys="true" keyProperty="id" keyColumn="id"> 

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

  FileAttachment fileAttachment=fileAttachmentMapper.insertSelective(fileAttachment);
  Integer id=fileAttachment.getId();

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

答案 2 :(得分:4)

事实上,MyBatis已经提供了这个功能。你可以使用选项:&#34; useGeneratedKeys&#34;获取最后一个插入ID。

以下是MyBatis的解释。(如果您想了解更详细的信息,可以访问MyBatis官方页面。)

  

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

如果您使用的是xml:

<insert id="" parameterType="" useGeneratedKeys="true">

如果您使用的是注释:

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

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

我希望这会对你有帮助。

答案 3 :(得分:1)

我认为返回的1指的是更新/插入的记录数。我认为id是在传递给insertSelective调用的fileAttachment参数上设置的。

答案 4 :(得分:0)

我希望在作者中,您可以拥有一个自定义复合编写器,并且您可以在那里获得插入的ID。

答案 5 :(得分:0)

(1)添加到Ruju的答案,在insert语句中你需要定义属性useGeneratedKeys = true,parameterType =&#34; object&#34;,keyProperty =&#34; objectId&#34;和keyColumn =&#34; objectId&#34;应该从存​​储对象记录的表中设置相同的主键列名(objectId)。主键列(objectId)应在数据库表中设置为AUTO_INCREMENT。

(2)当触发insert语句时,新生成的主键(objectId)将存储在object中,你可以通过使用这个方法(object.getObjectId()或object.objectId)访问objectId属性来检索它。 。现在,这应该给出确切的和新生成的主要。它对我有用....

答案 6 :(得分:0)

使用codeGenerator进行配置的需求:

 <table schema="catalogue" tableName="my_table" >
        <generatedKey column="my_table_id" sqlStatement="JDBC" identity="true" />
        <columnOverride column="my_table_id" isGeneratedAlways="true"/>
    </table>

http://www.mybatis.org/generator/configreference/generatedKey.html

代码生成后,插入内容会自动包含id字段

答案 7 :(得分:0)

     Traceback (most recent call last):
  File "c:\python27\lib\runpy.py", line 174, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "c:\python27\lib\runpy.py", line 72, in _run_code
    exec code in run_globals
  File "C:\Users\esinitsyn\AppData\Roaming\Python\Scripts\git-review.exe\__main__.py", line 9, in <module>
  File "C:\Users\esinitsyn\AppData\Roaming\Python\Python27\site-packages\git_review\cmd.py", line 1714, in main
    _main()
  File "C:\Users\esinitsyn\AppData\Roaming\Python\Python27\site-packages\git_review\cmd.py", line 1690, in _main
    (status, output) = run_command_status(cmd)
  File "C:\Users\esinitsyn\AppData\Roaming\Python\Python27\site-packages\git_review\cmd.py", line 129, in run_command_status
    argv = shlex.split(str(argv[0]))
  File "c:\python27\lib\shlex.py", line 279, in split
    return list(lex)
  File "c:\python27\lib\shlex.py", line 269, in next
    token = self.get_token()
  File "c:\python27\lib\shlex.py", line 96, in get_token
    raw = self.read_token()
  File "c:\python27\lib\shlex.py", line 172, in read_token
    raise ValueError, "No closing quotation"
ValueError: No closing quotation