關於Mybatis插入數據返回主鍵的小問題

1.在Mybatis Mapper文件中添加屬性“useGeneratedKeys”和“keyProperty”,其中keyProperty是Java對象的屬性名,而不是表格的字段名

<insert id="insert" parameterType="Spares"     
        useGeneratedKeys="true" keyProperty="id">    
        insert into system(name) values(#{name})    
</insert>

2.Mybatis執行完插入語句後,自動將自增長值賦值給對象systemBean的屬性id。因此,可通過systemBean對應的getter方法獲取!

int count = systemService.insert(systemBean);    
        
int id = systemBean.getId(); //獲取到的即爲新插入記錄的ID 

【注意事項】

1.Mybatis Mapper 文件中,“useGeneratedKeys”和“keyProperty”必須添加,而且keyProperty一定得和java對象的屬性名稱一直,而不是表格的字段名

2.java Dao中的Insert方法,傳遞的參數必須爲java對象,也就是Bean,而不能是某個參數。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章