需求:使用MyBatis往MySQL數據庫中插入一條記錄后,需要返回該條記錄的自增主鍵值。
方法:在mapper中指定keyProperty屬性,示例如下:
<insert id="insertAndGetId" useGeneratedKeys="true" keyProperty="userId" parameterType="com.chenzhou.mybatis.User"> insert into user(userName,password,comment) values(#{userName},#{password},#{comment}) </insert>
useGeneratedKeys:
取值范圍true|false
默認值是:false。
含義:設置是否使用JDBC的getGenereatedKeys方法獲取主鍵並賦值到keyProperty設置的領域模型屬性中。MySQL和SQLServer執行auto-generated key field,因此當數據庫設置好自增長主鍵后,可通過JDBC的getGeneratedKeys方法獲取。但像Oralce等不支持auto-generated key field的數據庫就不能用這種方法獲取主鍵了。
keyProperty:
(僅對 insert 有用) 標記一個屬性, MyBatis 會通過 getGeneratedKeys 或者通過 insert 語句的 selectKey 子元素設置它的值。默認: 不設置。
所示,我們在insert中指定了keyProperty="userId",其中userId代表插入的User對象的主鍵屬性。
public class User { private int userId; private String userName; private String password; private String comment; //setter and getter }
輸出:
插入前主鍵為:0
插入后主鍵為:15
查詢數據庫:
如上所示,剛剛插入的記錄主鍵id為15