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為例。其他請各自根據需要查詢。