mybatis+mysql insert添加數據后返回數據主鍵id---(轉)


1.根據useGeneratedKeys獲取返回值,部分數據庫不支持

修改mybatis xml

 

1
2
3
<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獲取

 

1
2
3
4
5
6
<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為例。其他請各自根據需要查詢。

分類: mybatis相關


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM