1. 程式人生 > 實用技巧 >mybatis新增insert返回主鍵id,與解決新增主鍵id一直為1的問題。

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。