情景需求:
当客户端向后台插入一条数据时将插入成功的数据的id返回给客户端。
上代码:
controller的代码:
@RequestMapping(value = "marriage/testinsert", produces = "application/json;charset=UTF-8")
@ResponseBody
public String testinsert() {
PageData pd = new PageData();
pd = this.getPageData();
pd.put("amount",66666);
pd.put("type","type");
pd.put("time","66666");
pd.put("main_key","test");
try {
marriageService.testinsert(pd);
return JSONUtil.JsonString(new JsonResult(1, "成功!", pd));
} catch (Exception e) {
// TODO: handle exception
logger.error("错误:" + e.toString(), e);
return JSONUtil.toJsonString(new JsonResult(-1, "失败:服务器内部错误!", null));
}
}
sql:
<insert id="testinsert" parameterType="pd" useGeneratedKeys="true" keyProperty="primary_id">
insert into
testinsert
(amount,type,time,main_key)
values
(
#{amount},
#{type},
#{time},
#{main_key}
)
</insert>
插入成功后返回客户端的json:
{"code":1,"message":"成功!","rows":{"amount":66666,"primary_id":1,"time":"66666","type":"type","main_key":"test"}}
需要注意的
useGeneratedKeys="true" MySQL支持但是Oracle不支持,据说是因为MySQL支持自增Oracle不支持,所以Oracle的时候就要使用selectKey获取了,keyProperty是将获取到的自增的值装入map中,key为primary_id。