MyBatis插入时返回主键

插入时主键返回

咱们向数据库插入一条记录时,使用Mybatis的<insert>是没法返回插入的主键的,但咱们须要这个刚插入的主键,可使用以下方式返回:java

自增主键:使用last_insert_id()查询刚插入的key的id,该方法须要和insert配合使用,是插入以后获取。

result返回的是插入成功条数,而主键id返回到CourseInfo的id属性中mysql

<insert id="insert" parameterType="org.andy.shop.model.CourseInfo" >  
    insert into course_info (id, cname, caddress)  
    values (#{id,jdbcType=INTEGER}, #{cname,jdbcType=VARCHAR}, #{caddress,jdbcType=VARCHAR})  
    
     <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">  
       select last_insert_id()  
     </selectKey>  
  </insert>

或者:sql

<insert id="insert" parameterType="org.andy.shop.model.CourseInfo" useGeneratedKeys="true" keyProperty="id">  
    insert into course_info (id, cname, caddress  
      )  
    values (#{id,jdbcType=INTEGER}, #{cname,jdbcType=VARCHAR}, #{caddress,jdbcType=VARCHAR}  
      )  
  </insert>

非自增主键:但咱们的ID为uuid字符类型的32为长度时,咱们使用mysql的uuid()查询主键,是在查询以后再插入。

<insert id="insert" parameterType="org.andy.shop.model.CourseInfo" >  
    <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String">  
      select uuid()  
    </selectKey>  
    insert into course_info (id, cname, caddress)  
    values (#{id,jdbcType=VARCHAR}, #{cname,jdbcType=VARCHAR}, #{caddress,jdbcType=VARCHAR})  
  </insert>
相关文章
相关标签/搜索