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才会取到正确的值。

例子:

查询未使用的账号并进行使用修改其使用状态

<!-- 获取即时通讯账号 order=’BEFORE’ update前执行select-->
  <update id="getByMessengerAccount" parameterType="com.qike.chat.entity.InstantMessengerAccount">
    <selectKey keyProperty='id' resultType='java.lang.String' order='BEFORE'>
        select IFNULL((SELECT
            CONCAT(id,'||',account_number) as id
        from instant_messenger_account where 
        status = '1' and delete_flag = '0' limit 1), 'error') as id from DUAL
    </selectKey>
    update instant_messenger_account
    set status = '2'
    where status = '1' and delete_flag = '0' and id = substring_index(#{id},"|",1);
  </update>

注:<selectKey 不可返回null

查询的id存在与model中,并作为update条件,必须设置parameterType。

如查询为null则返回error,代表error为null

Mybatis SelectKey实例

相关文章: