mybatis+mysql insert新增資料後返回資料主鍵id
1.根據useGeneratedKeys獲取返回值,部分資料庫不支援
修改mybatis xml
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id" parameterType="com.entity.user">
insert into test (name) values (#{name})
</insert>
useGeneratedKeys="true" :設定是否使用JDBC的getGenereatedKeys方法獲取主鍵並賦值到keyProperty設定的領域模型屬性中。(適用於mysql、sqlserver資料庫,oracle不能使用,使用selectkey子節點做)
keyProperty:賦值的物件的屬性名稱。
新增完成後,直接根據物件屬性取值。
user u=new user();
u.setName("測試");
System.out.println(u.getId()+"取值前");
int num = this.dao.getSqlSession().insert("insertUser",u);
System.out.println(u.getId()+"取值後");
2.根據selectkey獲取
<insert id="insertUser" parameterType="com.entity.user">
insert into test (name) values (#{name})
<selectKey keyProperty="id" resultType="java.lang.Integer">
select LAST_INSERT_ID() as id
</selectKey>
</insert>
後臺程式碼不變。
各個資料庫獲取方式不一樣,本例根據mysql為例。其他請各自根據需要查詢。