[英]How to populate object property with value generated by Mysql Trigger in MyBatis Insert
[英]MyBatis, how to get the auto generated key of an insert? [MySql]
如何使用MyBatis獲取插入的生成密鑰? 我讀了很多關於這個問題的網頁,但我仍然被封鎖,有人可以幫幫我嗎? 這是我的代碼:
桌子:
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:
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>
怎么了? 如何獲取此插入的生成密鑰? 謝謝!
對我來說它是這樣工作的(mybatis 3.x)..必須在mysql表中設置id自動增量
<insert id="createEmpty" parameterType="Project" useGeneratedKeys="true" keyProperty="project.projectId" keyColumn="PROJECT_ID">
INSERT INTO PROJECT (TITLE,DESCRIPTION)
VALUES
(#{title},#{description})
</insert>
注意 keyProperty="project.projectId"
和useGeneratedKeys="true"
我的界面是:
public int createEmpty(@Param("project") Project project, @Param("title") String title,
@Param("description") String description);
最后獲取值(將自動分配給pojo的id屬性)我使用:
projectRepository.createEmpty(p, "one", "two");
System.err.print(p.getProjectId() + "\n");
你可以通過兩種方式實現這一目標,
通過使用useGeneratedKeys="true", keyProperty="id", keyColumn="id"
keyProperty
是指POJO變量名, keyColumn
是指數據庫中生成的列名
通過在insert標簽內使用<selectKey/>
簡易方案:
使用KeyProperty
屬性作為objectName.AutoincrementId
下面像...
useGeneratedKeys="true", KeyProperty="person.id", KeyColumn="id"
如果您查看MyBatis文檔 ,請使用GenenedKeys和keyProperty ,至少需要獲取自動增量數據(對於某些數據庫,您需要添加keyColumn )。
如您所見,useGeneratedKeys取決於是否/如何實現dataBase的JDBC的getGeneretadKeys方法。
例如,使用mysql或H2,getGeneretadKeys僅支持一列。 最后生成的密鑰將是getGeneretadKeys返回的密鑰。
總之,在您的情況下,您只需要添加useGeneratedKeys和keyProperty(使用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);
如果您仍然遇到一些問題來檢索生成的密鑰,請查看mysql的JDBC文檔(舊版本可能不會實現getGeneretadKeys)。
在xml文件中放置以下5行:
<insert id="createPet" parameterType="java.util.Map"
useGeneratedKeys="true" keyProperty="id">
INSERT INTO Pet (NAME, OWNER, SPECIES, SEX, BIRTH)
VALUES (#{name}, #{owner}, #{species}, #{sex}, #{birth})
</insert>
在Java主類中創建此方法並在main方法中調用它:
public int createPet(PetDVO petDVO) throws Exception {
HashMap<String, Object> inputMap = new HashMap<String, Object>();
inputMap.put("name", petDVO.getName());
inputMap.put("owner", petDVO.getOwner());
inputMap.put("species", petDVO.getSpecies());
inputMap.put("sex", petDVO.getSex());
inputMap.put("birth", petDVO.getBirth());
/**
* Get the sql session and commit the data
*/
SqlSession sqlSession = getSqlSession();
sqlSession.insert("createPet", inputMap);
sqlSession.commit();
BigInteger newID = (BigInteger)inputMap.get("id");
return newID.intValue();
}
但是你應該自己創建PetDVO課程。 這就對了。
在Mapper Xml下,使用查詢:
<insert id="saveDemo" parameterType="com.abc.demo"
useGeneratedKeys="true" keyProperty="demoId" keyColumn="DEMOID">
INSERT INTO TBL_DEMO (DEMONAME,DEMODESCRIPTION)
VALUE (#{demoName},#{demoDescription})
<selectKey keyProperty="demoId" resultType="int" order="AFTER">
SELECT LAST_INSERT_ID();
</selectKey>
</insert>
Java方面
@Override
public boolean saveDemo(Demo demo) {
boolean status = false;
SqlSession session = this.sqlSessionFactory.openSession();
try {
DemoMapper mapper = session.getMapper(DemoMapper.class);
mapper.saveDemo(demo);
session.commit();
status = true;
} catch(PersistenceException e) {
System.out.println(e);
} finally {
session.close();
}
return status;
}
請按照以下步驟操作:
使用id作為屬性創建錯誤POJO
將returnId替換為錯誤,如下所示,
public void insertRecord(@Param(“error”)錯誤錯誤,@ Param(“timestamp”)時間戳時間戳,@ Param(“type”)字符串類型,@ Param(“message”)字符串消息,@ Param(“source”) )String source);
將keyProperty =“ID_ERROR”更改為keyProperty =“error.id”
去掉
<selectKey resultType="long" order="AFTER" keyProperty="returnedId"> SELECT LAST_INSERT_ID() as returnedId </selectKey>
您將在error.id
插入id
如果要獲取生成的主鍵,則應通過Map
或POJO Object
傳遞參數
public void insertRecord(Map<String, Object> 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");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.