很多人有需求:新增一个实体后返回自增的id
但直接返回了 sql的返回值这是不对的。
<insert id="addFile" parameterType="com.wx.fastdfs.model.File" useGeneratedKeys="true" keyProperty="id">
insert into file(file_name,group_name,file_path)
values (#{fileName},#{groupName},#{filePath})
</insert>
上面的sql 返回值 只能是1 或者0 ,这是返回的是数据影响的行数。
正确的理解是:
当执行完sql 后 持久层的参数会自动填充id 属性(由 keyProperty=“id” 指定)
如dao层:
Integer addFile(File file);
service层可见id: 重点是return,绝不是返回dao层的执行结果
public Integer addFile(File build) throws IOException {
fileDao.addFile(build);
return build.getId();
}