背景:目前有个插入语句须要获取插入记录的id 由于id是自增加的,因此要在插入后返回这个idapp
错误1:spa
mapper.xml:code
<!-- 新增 返回自增加id--> <insert id="save" parameterType="pd" resultType="int"> insert into sys_push( username,title,content,publisher,pushtime ) values ( #{username},#{title},#{content},#{publisher},#{pushtime} ) </insert>
我天真的觉得 须要用resultType返回一个int类型的,结果项目启动直接报错了,由于insert方法根本就没有resultType! 哎 基础不扎实啊。。。xml
以后百度了下 哦 原来返回id是这么用的对象
正确: keyProperty="id" useGeneratedKeys="true"get
<!-- 新增 返回自增加id--> <insert id="save" keyProperty="id" useGeneratedKeys="true" parameterType="pd"> insert into sys_push( username,title,content,publisher,pushtime ) values ( #{username},#{title},#{content},#{publisher},#{pushtime} ) </insert>
从新启动后 调用查询语句发现:it
int id = pushService.save(pd);
怎么id都是1。。。。class
错误2:基础
又百度了一下,原来insert这个返回值返回的是插入成功的条数,不是id啊。。。哎 基础不扎实啊。。。百度
正确:
在查询后,要获取的id其实已经在传入对象的参数里了,用xx.getId()方法就能够直接获取到了。
int insertNum = pushService.save(pd);//插入的条数 Long id = (Long) pd.get("id");//获取id
我这里传入的是封装的pd对象,获取方法是get("id")
若是是传入user类,获取方式是 Long id = user.getId();//该对象的自增ID
注意: 返回的id是long类型
over!