MyBatis如何获取插入记录的自增长字段值:
第一步:
在Mybatis Mapper文件中添加属性“useGeneratedKeys”和“keyProperty”,其中keyProperty是Java对象的属性名!
<insert id="insert" parameterType="Spares" useGeneratedKeys="true" keyProperty="id"> insert into spares(spares_id,spares_name,spares_type_id,spares_spec) values(#{id},#{name},#{typeId},#{spec}) </insert>
第二步:
Mybatis执行完插入语句后,自动将自增长值赋值给对象Spares的属性id。因此,可通过Spares对应的getter方法获取!
/** * 新增备件 * @author hellostory * @param spares * @return */ @RequestMapping(value = "/insert") @ResponseBody public JsonResponse insert(Spares spares) { int count = sparesService.insert(spares); //count>0 表示成功 System.out.println( "刚刚插入记录的主键自增长值为:" + spares.getId());
如果没有useGeneratedKeys="true"和keyProperty="id",下面 insert 之后的 user.getId() 是无法获取 id 值的public void insert(User user) { int count = userMapper.insert(user); System.out.println("共插入" + count + "条记录!" + "\n刚刚插入记录的主键自增长值为:" + user.getId()); }
原文地址:https://blog.csdn.net/thlzjfefe" target="_blank" rel="noopener" title="thlzjfefe">thlzjfefe</a> <img class="article-time-img article-heard-img" src="https://csdnimg.cn/release/blo
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。