mybatis新增insert返回主键id,与解决新增主键id一直为1的问题。

  • 新增返回主键

mapper(dao)

public Integer insertCmsContent(CmsContent cmsContent);     //返回类型为 Integer  xml文件不用写 resultType = "Integer" 标签属性

mapper.xml文件

<insert id="insertCmsContent" parameterType="cmsContent" useGeneratedKeys="true" keyProperty="cmsContent.id" keyColumn="id" >
.. (新增语句忽略 主要是加标签 useGeneratedKeys="true" keyProperty="id" keyColumn="id" "id" 为你表的要返回主键 )
</insert>
  • 处理返回新增主键一直为1问题
//service 业务层 contentId 为你返回的主键id
Integer contentId = baseMapper.insertCmsContent(cmsContent);

解决方案:

不能用  Integer contentId  去接收返回的自增主键id  ,要使用该主键的话,需要把整个  baseMapper.insertCmsContent(cmsContent)  set 进去。例:

cmsContent.setContentId(baseMapper.insertCmsContent(cmsContent));

然后,问题解决!至于为啥出现这种问题,这边文章不做叙述。只用做解决bug。

原文地址:https://www.cnblogs.com/ITzhangda/p/13271875.html