MyBatis獲取數(shù)據(jù)庫自生成的主鍵Id詳解及實(shí)例代碼
在使用MySQL數(shù)據(jù)庫時(shí)我們一般使用數(shù)據(jù)庫的自增主鍵自動(dòng)產(chǎn)生主鍵。如果在插入主表時(shí),我們需要同時(shí)插入從表的數(shù)據(jù),這時(shí)我們通常需要知道主表插入時(shí)自動(dòng)產(chǎn)生的主鍵Id值。
下面介紹使用MyBatis進(jìn)行插入時(shí),如何同時(shí)獲取數(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)用這個(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ì)變成自生成的idint id = person.getId();感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選