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