引言
真完蛋,时间久不用就忘了,简单记录一下耻辱史吧。
场景
添加一条记录,返回这条记录的id,当然,这个id是自增字段。
代码
mapper接口
int ***(***Entity ***Entity);
mapper文件
<insert id="***" parameterType="***" useGeneratedKeys="true" keyProperty="id">
insert into ***(***)
values(***)
</insert>
其中的useGeneratedKeys="true" keyProperty="id"这个也写了,id也是实体中的id(实体和数据库字段是对应的)
useGeneratedKeys [true/false], 默认值为false
true使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty属性中
keyProperty 最终获取到的结果放到哪儿
别这么做
在service层
return ***Mapper.append***(***Entity);
// 因为mapper接口时int,就误以为它返回的就是id,实际上0是失败,>=1是成功
应该这么做
Mapper.append(***Entity);
return ***Entity.getId() //没错,这个就是传入的实体对象
在调用Mapper前,实体对象的id是Null,但是Mybatis执行成功后,它的id就变成了插入后的ID了

评论 0
还没有评论,来说点什么吧。