Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MyBatis, how to get the auto generated key of an insert? [MySql]

how can I get the generated key of an insert with MyBatis? I read many pages about this question but I'm still blocked, could anyone help me, please? This is my code:

The table:

ID_ERROR long primary key
DATE timestamp
TYPE varchar
MESSAGE varchar
SOURCE varchar

The dao:

Long returnedId = 0L;
MyMapper myMapper = this.sqlSession.getMapper(MyMapper.class);
myMapper.insertRecord(returnedId, Utils.now(), t.getClass().getName(), t.getMessage(), c.getName());
return returnedId;

The mapper.java:

public void insertRecord(@Param("returnedId") Long returnedId, @Param("timestamp")Timestamp timestamp,@Param("type") String type,@Param("message") String message,@Param("source") String source);

The mapper.xml

 <insert id="insertRecord" parameterType="map" useGeneratedKeys="true"  keyProperty="ID_ERROR">
    INSERT INTO errors (
        DATE,
        TYPE,
        MESSAGE,
        SOURCE
    )
    VALUES (
        #{timestamp},
        #{type},
        #{message},
        #{source}
    )
    <selectKey resultType="long" order="AFTER" keyProperty="returnedId">
        SELECT LAST_INSERT_ID() as returnedId
    </selectKey>
</insert>

What is wrong? How can I get the generated key of this insert? Thanks!

like image 391
user2572526 Avatar asked Aug 29 '13 09:08

user2572526


People also ask

How do I get my last inserted ID in MyBatis?

Once you finish insert operation, the fileAttachment's setId() method will be invoked, and is set to id of last inserted record. You can use fileAttachment's getId() to get the last insert id.

What is MyBatis generator?

MyBatis Generator (MBG) is a code generator for MyBatis MyBatis. It will generate code for all versions of MyBatis. It will introspect a database table (or many tables) and will generate artifacts that can be used to access the table(s).


3 Answers

For me it is working like this (mybatis 3.x) .. The id must be set auto increment in mysql table

<insert id="createEmpty" parameterType="Project" useGeneratedKeys="true" keyProperty="project.projectId" keyColumn="PROJECT_ID">     INSERT INTO PROJECT (TITLE,DESCRIPTION)     VALUES     (#{title},#{description}) </insert> 

NOTE keyProperty="project.projectId" and useGeneratedKeys="true"

my interface is:

public int createEmpty(@Param("project") Project project, @Param("title") String title,     @Param("description") String description); 

finally to get the value (that will be automatically assigned to the pojo's id property) i use:

projectRepository.createEmpty(p, "one", "two"); System.err.print(p.getProjectId() + "\n"); 
like image 110
T M Avatar answered Oct 14 '22 03:10

T M


You can achieve this by two ways,

  1. By using useGeneratedKeys="true", keyProperty="id", keyColumn="id"

    keyProperty refers to the POJO variable name and keyColumn refers to generated column name in database

  2. By using <selectKey/> inside insert tag

like image 38
bharanitharan Avatar answered Oct 14 '22 03:10

bharanitharan


If you take a look at MyBatis documentation, useGeneratedKeys and keyProperty is what you need at least to get auto increment data (for some database, you will need to add keyColumn).

As you can see, useGeneratedKeys depends on if/how is implemented the getGeneretadKeys method of the dataBase's JDBC.

For exemple, with mysql or H2, getGeneretadKeys support only one column. The last generated key will be the one return by getGeneretadKeys.

In conclusion, in your case you need to add only useGeneratedKeys and keyProperty (with ID_ERROR auto_increment):

Mapper.xml

<resultMap type='pathToJavaClass/Error' id='error'>
    <id property='id' column='ID_ERROR' />
    <result property='timestamp' column='DATE' />
    <result property='type' column='TYPE'/>
    <result property='message' column='MESSAGE'/>
    <result property='source' column='SOURCE'/>
</resultMap>
<insert id="insertRecord" parameterType="error" useGeneratedKeys="true" keyProperty="id">
INSERT INTO errors (
    DATE,
    TYPE,
    MESSAGE,
    SOURCE
)
VALUES (
    #{timestamp},
    #{type},
    #{message},
    #{source}
)
</insert>

Interface.java

public void insertRecord(@Param("error") Error error);

If you still get some issue to retrieve generated Keys, check also the documentation of mysql's JDBC (older version may not implement getGeneretadKeys).

like image 28
Audrey Carval Avatar answered Oct 14 '22 03:10

Audrey Carval