1. 程式人生 > >關於Mybatis插入資料返回主鍵的小問題

關於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,而不能是某個引數。