MyBatis, how to get the auto generated key of an insert? [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!
推荐答案
如果要获取生成的主键,应通过Map
或POJO 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]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:MyBatis,如何获取插入的自动生成密钥?[MySql]
基础教程推荐
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 降序排序:Java Map 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01