本文介紹了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]的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!