ibatis中使用insert后,返回值为null的解决方案:博主本人写的代码,测试后发现问题如下:
映射文件:
<insert id="addAdRecord" parameterClass="java.util.Map">
<![CDATA[
insert into hk_click(clickIp,clickDate,adId) values (#clickIp#,#clickDate#,#adId#)
]]>
</insert>
实现类:
@Override
public boolean isAddClickRecord(Map map) {
try {
System.out.println((client.insert("clickSpace.addAdRecord",map)));
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
测试方法:
System.out.println(dao.isAddClickRecord(map));
返回结果:
2016-01-08 14:39:16,940 DEBUG [java.sql.PreparedStatement] - {pstm-100001} Executing Statement: insert into hk_click(clickIp,clickDate,adId) values (?,?,?)
2016-01-08 14:39:16,940 DEBUG [java.sql.PreparedStatement] - {pstm-100001} Parameters: [10.130.160.69, 2016-01-08 14:39:16.699, 1]
2016-01-08 14:39:16,940 DEBUG [java.sql.PreparedStatement] - {pstm-100001} Types: [java.lang.String, java.sql.Timestamp, java.lang.Integer]
null
true
经查阅ibatis文档得知:
Executes 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.
所说的是:返回值是新插入记录的主键,类型为Object主要是因为主键类型可以是int也可以是String类型。 故,我们配置文件应该加上一个返回主键的代码。
<insert id="addAdRecord" parameterClass="java.util.Map">
<![CDATA[
insert into hk_click(clickIp,clickDate,adId) values (#clickIp#,#clickDate#,#adId#)
]]>
<selectKey resultClass="int" keyProperty="id">
select max(id) from hk_click
</selectKey>
</insert>
加入之后,测试内返回的结果:
2016-01-08 14:45:02,719 DEBUG [java.sql.PreparedStatement] - {pstm-100001} Executing Statement: insert into hk_click(clickIp,clickDate,adId) values (?,?,?)
2016-01-08 14:45:02,719 DEBUG [java.sql.PreparedStatement] - {pstm-100001} Parameters: [10.130.160.69, 2016-01-08 14:45:02.484, 1]
2016-01-08 14:45:02,719 DEBUG [java.sql.PreparedStatement] - {pstm-100001} Types: [java.lang.String, java.sql.Timestamp, java.lang.Integer]
2016-01-08 14:45:02,744 DEBUG [java.sql.PreparedStatement] - {pstm-100002} Executing Statement: select max(id) from hk_click
2016-01-08 14:45:02,745 DEBUG [java.sql.PreparedStatement] - {pstm-100002} Parameters: []
2016-01-08 14:45:02,745 DEBUG [java.sql.PreparedStatement] - {pstm-100002} Types: []
14
true
返回的主键是14,故,问题解决。