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