mybatis註解獲取插入的自增主鍵id

2021-10-09 08:03:46 字數 1053 閱讀 9886

@insert

(,address)"

+,#)"

)@selectkey

(statement=

"select last_insert_id()"

, keyproperty=

"userauthenticationrequestv3.cerid"

, before=

false

, resulttype=

int.

class

)

下面介紹乙個重要註解@selctkey(statement=「sql語句」,keyproperty=「將sql語句查詢結果存放到keyproperty中去」,before=「true表示先查詢再插入,false反之」,resulttype=int.class)

其中:statement是要執行的sql語句,它的返回值通過resulttype來指定

before表示查詢語句statement執行的時機

keyproperty表示查詢結果賦值給**中的哪個物件,keycolumn表示將查詢結果賦值給資料庫表中哪一列

keyproperty和keycolumn都不是必需的,有沒有都可以

before=true,插入之前進行查詢,可以將查詢結果賦給keyproperty和keycolumn,賦給keycolumn相當於更改資料庫

befaore=false,先插入,再查詢,這時只能將結果賦給keyproperty

賦值給keyproperty用來「讀」資料庫,賦值給keycolumn用來寫資料庫

selectkey的兩大作用:1、生成主鍵;2、獲取剛剛插入資料的主鍵。

使用selectkey,並且使用mysql的last_insert_id()函式時,before必為false,也就是說必須先插入然後執行last_insert_id()才能獲得剛剛插入資料的id。

@selectkey查詢的結果也就是keyproperty 的值將會存放在userauthenticationrequestv3 的cerid 這個屬性中,所以傳參中必須要乙個實體類,不然主鍵值不知道放在**

MyBatis獲取插入記錄的自增長字段值

開發中經常遇到插入一條資料之後,需要獲得新插入記錄自增長生成的id。方法如下 insert into spares spares id,spares name,spares type id,spares spec values mybatis執行完插入語句後,自動將自增長值賦值給物件spares的屬...

MyBatis獲取插入記錄的自增長字段值

1 insert id addmessage parametertype message usegeneratedkeys true keyproperty msgid 23 insert into message detail msgsubject,msgcontent,msgtime,msgty...

mybatis用註解批量插入資料

author xiaopengcheng create 2019 06 22 15 50 商品類別 public class productcategory implements serializable public void setproductcategoryid long productca...