MyBatis,如何获取插入的自动生成密钥?[MySql]

MyBatis, how to get the auto generated key of an insert? [MySql](MyBatis,如何获取插入的自动生成密钥?[MySql])
本文介绍了MyBatis,如何获取插入的自动生成密钥?[MySql]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

如何使用 MyBatis 获取插入的生成密钥?我读了很多关于这个问题的页面,但我仍然被阻止,有人可以帮助我吗?这是我的代码:

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:

桌子:

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

道:

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

mapper.java:

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);

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!

推荐答案

如果要获取生成的主键,应通过MapPOJO Object

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");

这篇关于MyBatis,如何获取插入的自动生成密钥?[MySql]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Android sdk 18 TextView gravity doesn#39;t work vertically(Android sdk 18 TextView 重力不能垂直工作)
Java android: appending a newline using TextView(Java android:使用 TextView 添加换行符)
How to create simple Android TextView and display text on it using java code?(如何使用 java 代码创建简单的 Android TextView 并在其上显示文本?)
Add opaque quot;shadowquot; (outline) to Android TextView(添加不透明的“阴影(大纲)到 Android TextView)
Android: Creating a Circular TextView?(Android:创建一个圆形 TextView?)
Android - set TextView TextStyle programmatically?(Android - 以编程方式设置 TextView TextStyle?)