Welcome to Yumao′s Blog.
Ibatis和Mybatis的insert返回值差異
, 2016年08月17日 , Java Language , 评论 在〈Ibatis和Mybatis的insert返回值差異〉中留言功能已關閉 ,

最近將項目從ibatis移到了Mybatis上

基本上的感覺是平滑升級

但是區別還是有的

我們就來扒一扒這倆返回值得區別好了

 

我們先來看一下Ibatis的文檔

insert
public java.lang.Object insert(java.lang.String id,
java.lang.Object parameterObject)
throws java.sql.SQLExceptionExecutes a mapped SQL INSERT statement. Insert is a bit different from other update methods, as it provides facilities for returning the primary key of the newly inserted row (rather than the effected rows). This functionality is of course optional.
The parameter object is generally used to supply the input data for the INSERT values.

Parameters:
id - The name of the statement to execute.
parameterObject - The parameter object (e.g. JavaBean, Map, XML etc.).
Returns:
The primary key of the newly inserted row. This might be automatically generated by the RDBMS, or selected from a sequence table or other source.
Throws:
java.sql.SQLException - If an error occurs.

再看一下Mybatis的

public abstract int insert (String statement, Object parameter)

Execute an insert statement with the given parameter object. Any generated autoincrement values or selectKey entries will modify the given parameter object properties. Only the number of rows affected will be returned.
Parameters
statement Unique identifier matching the statement to execute.
parameter A parameter object to pass to the statement.
Returns
int The number of rows affected by the insert.

結果會發現

在Ibatis時期 Insert返回的是主鍵内容

而在Mybatis時期 Insert返回的是影響行數

 

因爲這點我被坑了好久啊~

因爲在Mybatis裏面設置selectKey之後

返回的依然都是1……

原因就在這裡了 因爲你insert變動的内容只有1條而已

 

而selectKey的返回值到底在哪呢

將selectKey的keyProperty設置成Object-parameter的property之後

去找找你傳入的Object-parameter吧

值已經在裏面等著你的調用了喔  XD

 

关键字:, ,

评论已关闭