Hibernate及MyBatis獲取資料庫新插入記錄主鍵id
阿新 • • 發佈:2018-12-14
記錄一下Hibernate以及MyBatis往資料庫插入一條新紀錄,獲取這條新紀錄的id的方法。
1.Hibernate
HIbernate插入資料時執行save()方法,執行完該方法之後,實體類物件就已經有了在資料庫中的id值,呼叫getId方法就可以獲取id,簡單示例如下:
Person person = new Person();
//給person賦值
//...
personDao.save(person);//執行save()方法
int id = person.getId();
2.MyBatis
說明:這裡在資料庫中的主鍵id必須是自增主鍵
在personMapper.xml檔案insert語句中新增 useGeneratedKeys="true"
keyProperty=" id"
屬性
<insert id="addPerson" parameterType="Person" useGeneratedKeys="true" keyProperty="id">
insert into person(name, age) values (#{name}, #{age})
</insert>
簡單呼叫示例:
Person person = new Person(); //給person賦值 //... personMapper.addPerson(person);//執行insert方法 int id = person.getId();
參考連結:
1.https://blog.csdn.net/codejas/article/details/79513834