MyBatis獲取數據庫自生成的主鍵Id詳解及實例代碼

這篇文章主要介紹了MyBatis獲取數據庫自生成的主鍵Id詳解及實例代碼的相關資料,需要的朋友可以參考下

MyBatis獲取數據庫自生成的主鍵Id詳解及實例代碼

在使用MySQL數據庫時我們一般使用數據庫的自增主鍵自動產生主鍵。如果在插入主表時,我們需要同時插入從表的數據,這時我們通常需要知道主表插入時自動產生的主鍵Id值。

下面介紹使用MyBatis進行插入時,如何同時獲取數據庫自生成的主鍵:

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);

注意在調用這個方法時,返回的int值並不是主鍵,而是插入的記錄數。主鍵id會被賦值到輸入的person對象裏,自動賦值給person對象的id屬性。比如:

Person person = new Person("name","psw");
//num是插入的記錄數
int num = PersonMapper.insert(person);
//person對象的id屬性會變成自生成的id
int id = person.getId();

 感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章