java mybatis中insert 操作 返回主鍵的小技巧。。。。

來源:互聯網
上載者:User

標籤:mode   方式   get   dict   des   選擇   test   before   小技巧   

第一種方式:

在實體類的對應檔 "*Mapper.xml" 這樣寫:

<insert id="insertvmatedic" keyColumn="mdid" useGeneratedKeys="true" keyProperty="mdid" parameterType="Vmaterialdictionary">      insert into vmaterialdictionary values(testsq.nextval,#{mdname},#{mdtype},#{mdunit},#{mdcost}) </insert>
keyColumn="mdid"  表示資料庫中哪一列
useGeneratedKeys="true" 表示給主鍵設定自增長
keyProperty="mdid"  表示將自增長後的Id賦值給實體類中的mdid欄位。
這裡提醒下,<insert></insert> 中沒有resultType屬性,不要亂加。
實體類中mdid要有getter() and setter(); 方法

第二種方式:

同樣在實體類的對應檔 "*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>
<insert></insert> 中沒有resultType屬性,但是<selectKey></selectKey> 標籤是有的。

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

可被設定為 BEFORE 或 AFTER。

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

如果設定為 AFTER,那麼先執行插入語句,然後是 selectKey 元素-這和如 Oracle 資料庫相似,可以在插入語句中嵌入序列調用
keyProperty="userId"  表示將自增長後的Id賦值給實體類中的userId欄位。

 

java mybatis中insert 操作 返回主鍵的小技巧。。。。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.