自己踩過的坑,查了好久,終於發現解決方法。
步驟有三:
1. 寫SQL,但不要自己插入主鍵值
2. 配置@Options(useGeneratedKeys=true, keyProperty="對象.屬性")
這個的作用是設置是否使用JDBC的getGenereatedKeys()
方法獲取主鍵並賦值到keyProperty設置的對象的屬性中,說白了就是把自增長的主鍵值賦值給對象相應的屬性
3. 在插入後,使用對象.主鍵屬性的getXXId()
方法 獲取主鍵值
示例:
@Insert("INSERT INTO api(component, clientApi, scribeDescribe, clientApiVersion, invokeTimeout, authType, sessionRequire, openType) VALUES(#{api.component}, #{api.clientApi}, #{api.scribeDescribe}, #{api.clientApiVersion}, #{api.invokeTimeout}, #{api.authType}, #{api.sessionRequire}, #{api.openType})")
@Options(useGeneratedKeys = true, keyProperty = "api.apiId")
void add(@Param("api") Api api);
然後調用api.getApiId()即可