MyBatis獲取數(shù)據(jù)庫自生成的主鍵Id詳解及實例代碼
在使用MySQL數(shù)據(jù)庫時我們一般使用數(shù)據(jù)庫的自增主鍵自動產(chǎn)生主鍵。如果在插入主表時,我們需要同時插入從表的數(shù)據(jù),這時我們通常需要知道主表插入時自動產(chǎn)生的主鍵Id值。
下面介紹使用MyBatis進行插入時,如何同時獲取數(shù)據(jù)庫自生成的主鍵:
1、XML配置文件
insert id="insert" parameterType="Person" useGeneratedKeys="true" keyProperty="id"> insert into person(name,pswd) values(#{name},#{pswd}) /insert>
2、Mapper中的方法
int insert(Person person);
注意在調(diào)用這個方法時,返回的int值并不是主鍵,而是插入的記錄數(shù)。主鍵id會被賦值到輸入的person對象里,自動賦值給person對象的id屬性。比如:
Person person = new Person("name","psw"); //num是插入的記錄數(shù) int num = PersonMapper.insert(person); //person對象的id屬性會變成自生成的id int id = person.getId();
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
標簽:淮安 柳州 瀘州 江蘇 荊門 景德鎮(zhèn) 那曲 威海
巨人網(wǎng)絡通訊聲明:本文標題《MyBatis獲取數(shù)據(jù)庫自生成的主鍵Id詳解及實例代碼》,本文關(guān)鍵詞 MyBatis,獲取,數(shù)據(jù)庫,自,生成,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權(quán)與本站無關(guān)。