selectKey 标签

原文: https://blog.csdn.net/Sun_of_Rainy/article/details/81564433

在insert语句中,在Oracle经常使用序列、在MySQL中使用函数来自动生成插入表的主键,而且需要方法能返回这个生成主键。使用myBatis的selectKey标签可以实现这个效果。

SelectKey在Mybatis中是为了解决Insert数据时不支持主键自动生成的问题,他可以很随意的设置生成主键的方式。

不管SelectKey有多好,尽量不要遇到这种情况吧,毕竟很麻烦。

属性 描述
keyProperty selectKey 语句结果应该被设置的目标属性。
resultType 结果的类型。MyBatis 通常可以算出来,但是写上也没有问题。MyBatis 允许任何简单类型用作主键的类型,包括字符串。
order

这可以被设置为 BEFORE 或 AFTER。如果设置为 BEFORE,那么它会首先选择主键,设置 keyProperty 然后执行插入语句。如果设置为 AFTER,那么先执行插入语句,然后是 selectKey 元素-这和如 Oracle 数据库相似,可以在插入语句中嵌入序列调用。

 statementType  和前面的相 同,MyBatis 支持 STATEMENT ,PREPARED 和CALLABLE 语句的映射类型,分别代表 PreparedStatement 和CallableStatement 类型。

SelectKey需要注意order属性,像Mysql一类支持自动增长类型的数据库中,order需要设置为after才会取到正确的值。

像Oracle这样取序列的情况,需要设置为before,否则会报错。

另外在用Spring管理事务时,SelectKey和插入在同一事务当中,因而Mysql这样的情况由于数据未插入到数据库中,所以是得不到自动增长的Key。取消事务管理就不会有问题。

<insert id="insertSelective" parameterType="com.huatek.compass.frame.entity.Role">
    <selectKey keyProperty="id" resultType="String" order="BEFORE">  
               select  replace(uuid(),'-','')   from dual 
       </selectKey> 
    insert into sys_role
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="active != null">
        active,
      </if>
      <if test="comment != null">
        comment,
      </if>
      <if test="role != null">
        role,
      </if>
      <if test="groupId != null">
        group_id,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=VARCHAR},
      </if>
      <if test="active != null">
        #{active,jdbcType=INTEGER},
      </if>
      <if test="comment != null">
        #{comment,jdbcType=VARCHAR},
      </if>
      <if test="role != null">
        #{role,jdbcType=VARCHAR},
      </if>
      <if test="groupId != null">
        #{groupId,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>

  

原文地址:https://www.cnblogs.com/xinruyi/p/11110203.html