mybatis 新增返回id


第一種方式:

在實體類的映射文件 "*Mapper.xml" 這樣寫:

<insert id="insertAndGetId" useGeneratedKeys="true" keyProperty="userId" parameterType="com.chenzhou.mybatis.User">
    insert into user(userName,password,comment)
    values(#{userName},#{password},#{comment})
</insert>

Tips:

useGeneratedKeys="true" 表示給主鍵設置自增長
keyProperty="userId"  表示將自增長后的Id賦值給實體類中的userId字段。
parameterType="com.chenzhou.mybatis.User" 這個屬性指向傳遞的參數實體類

這里提醒下,<insert></insert> 中沒有resultType屬性,不要亂加。

實體類中uerId 要有getter() and setter(); 方法

由於我在MySQL數據庫中建表時候已經設置了字段自增長,

第二種方式:

同樣在實體類的映射文件 "*Mapper.xml" 但是要這樣寫:

<!-- 插入一個商品 -->
    <insert id="insertProduct" parameterType="domain.model.ProductBean" >
       <selectKey resultType="java.lang.Long" order="AFTER" keyProperty="productId">
          SELECT LAST_INSERT_ID()
      </selectKey>
        INSERT INTO t_product(productName,productDesrcible,merchantId)values(#{productName},#{productDesrcible},#{merchantId});
    </insert>

Tips: 

<insert></insert> 中沒有resultType屬性,但是<selectKey></selectKey> 標簽是有的。

order="AFTER" 表示先執行插入語句,之后再執行查詢語句。

可被設置為 BEFORE 或 AFTER。

如果設置為 BEFORE,那么它會首先選擇主鍵,設置 keyProperty 然后執行插入語句。

如果設置為 AFTER,那么先執行插入語句,然后是 selectKey 元素-這和如 Oracle 數據庫相似,可以在插入語句中嵌入序列調用
keyProperty="userId"  表示將自增長后的Id賦值給實體類中的userId字段。

SELECT LAST_INSERT_ID() 表示MySQL語法中查詢出剛剛插入的記錄自增長Id.

實體類中uerId 要有getter() and setter(); 方法

 

調用:

    UserAccount userAccount1  = new UserAccount();
        userAccount1.setAccountname("test2");
        userAccount1.setPassword("test2");
        userAccount1.setRegistos("IOS");
        userAccount1.setStutas(0);
        userAccount1.setCreatetime(System.currentTimeMillis());
        userAccount1.setImei("test");
        userAccount1.setChannel("test");
        userAccount1.setRegistip("0.0.0.0");
        int i = userAccountMapper.insertSelective(userAccount1);
        System.out.println(userAccount1.getAccountid());

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 
         
         
       


免責聲明!

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



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