mybatis插入一条数据后返回主键id

在bean的mapper配置文件的insert节点添加:

useGeneratedKeys="true" keyProperty="id"

如:

<insert id="insert" useGeneratedKeys="true" keyProperty="id" parameterType="com.ajie.dao.pojo.TbBlog" >
    insert into tb_blog (id, userId, userHeader, 
      userName, userNickName, createTime, 
      lastModifyDate, title, content, 
      commentNum, praiseNum, collectNum, 
      readNum, labelStrs, mark
      )
    values (#{id,jdbcType=INTEGER}, #{userid,jdbcType=INTEGER}, #{userheader,jdbcType=VARCHAR}, 
      #{username,jdbcType=VARCHAR}, #{usernickname,jdbcType=VARCHAR}, #{createtime,jdbcType=TIMESTAMP}, 
      #{lastmodifydate,jdbcType=TIMESTAMP}, #{title,jdbcType=VARCHAR}, #{content,jdbcType=VARCHAR}, 
      #{commentnum,jdbcType=INTEGER}, #{praisenum,jdbcType=INTEGER}, #{collectnum,jdbcType=INTEGER}, 
      #{readnum,jdbcType=INTEGER}, #{labelstrs,jdbcType=VARCHAR}, #{mark,jdbcType=INTEGER}
      )
  </insert>

这样就可以了,当调用mapper的insert方法后,如果成功,那么mybaits会自动把主键的id返回并赋值给你传进来的bean

猜你喜欢

转载自blog.csdn.net/Mitnick5194/article/details/87884598