关于mybatis插入数据库返回主键id

时间:2022-03-10 17:05:11
  • 关于Sequence主键的数据库来说,如:
    • <insert id="add" parameterType="vo.Category">

      <selectKey resultType="java.lang.Short" order="BEFORE" keyProperty="id">

      SELECT SEQ_TEST.NEXTVAL FROM DUAL

      </selectKey>

      insert into category (name_zh, parent_id,

      show_order, delete_status, description

      )

      values (#{nameZh,jdbcType=VARCHAR},

      #{parentId,jdbcType=SMALLINT},

      #{showOrder,jdbcType=SMALLINT},

      #{deleteStatus,jdbcType=BIT},

      #{description,jdbcType=VARCHAR}

      )

      </insert>

  • 自增主键的表,插入时不需要主键,而是在插入过程中获取一个自增的主键,如:
    • <insert id="add" parameterType="vo.Category" useGeneratedKeys="true" keyProperty="id">

      insert into category (name_zh, parent_id,

      show_order, delete_status, description

      )

      values (#{nameZh,jdbcType=VARCHAR},

      #{parentId,jdbcType=SMALLINT},

      #{showOrder,jdbcType=SMALLINT},

      #{deleteStatus,jdbcType=BIT},

      #{description,jdbcType=VARCHAR}

      )

      </insert>

      或者

      <insert id="add" parameterType="vo.Category">

      <selectKey resultType="java.lang.Short" order="AFTER" keyProperty="id">

      SELECT LAST_INSERT_ID() AS id

      </selectKey>

      insert into category (name_zh, parent_id,

      show_order, delete_status, description

      )

      values (#{nameZh,jdbcType=VARCHAR},

      #{parentId,jdbcType=SMALLINT},

      #{showOrder,jdbcType=SMALLINT},

      #{deleteStatus,jdbcType=BIT},

      #{description,jdbcType=VARCHAR}

      )

      </insert>    注意:keyProperty="id" 这个id必须是实体的id,而不是数据表的主键id,否则,得不到正确的返回结果;接收返回值的时候必须用实体的get属性,而不能定义变量,否则,接收不到正确的返回结果:即必须用user.getId()来接收。例如int insertAndGetId = pgyMemUserService.insertAndGetId(user);

      System.out.println(user.getId());

  • 数据库表的主键不是自增的类型,一般需要应用层通过代码生成主键。也可以在数据库中生成如下:
    •   下面是针对Oracle的写法,Oracle没有autoincrement,而是用触发器实现的 CURRVAL是在触发器中定义的.
      <insert id="insert" parameterClass="ProFeeKindObject">
            <![CDATA[
               INSERT INTO t_pro_feeKind (KINDID,kindName,kindType,enable)
               VALUES (seq_t_pro_feekind_id.nextval,#kindName#,#kindType#,#enable#)
              ]]>
              <selectKey resultClass="java.lang.Integer" keyProperty="kindId" >
              SELECT seq_t_pro_feekind_id.CURRVAL AS kindId FROM DUAL
              </selectKey>    
      </insert>

      <!-- 下面是针对MySQL的写法 -->
      <!--
         <selectKey resultClass="int" keyProperty="id" >
         SELECT @@IDENTITY AS id
         </selectKey>
      -->