Search code examples
javamysqlinsertmybatis

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!


Solution

  • If you want to get the generated primary key, you should pass the arguments by Map or POJO Object

    public void insertRecord(Map<String, Object> map);
    

    When call the mapping method, put values to map.

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("returnedId", 0);
    map.put("message", message);
    // other paramters
    mapper.insertRecord(map);
    return map.get("returnedId");