Mybatis——selectKey

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

 使用mybatis的selectKey就能够获得sequence的值,同时也会将值返回。不过对于不一样的数据库有不一样的操做方式。mysql

 

属性 描述
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才会取到正确的值。sql

Oracle这样取序列的状况,须要设置为before,不然会报错。数据库

下面是一个xml和注解的例子,SelectKey很简单,两个例子就够了:mybatis

<insert id="insert" parameterType="map">  
    insert into table1 (name) values (#{name})  
    <selectKey resultType="java.lang.Integer" keyProperty="id">  
      CALL IDENTITY()  
    </selectKey>  
  </insert>

 

上面xml的传入参数是map,selectKey会将结果放到入参数map中。用POJO的状况同样,可是有一点须要注意的是,keyProperty对应的字段在POJO中必须有相应的setter方法,setter的参数类型还要一致,不然会报错。oracle

 

  对于oracle: 
      <insert id="insertUser" parameterClass="XXX.User"> 
          <selectKey resultClass="long" keyProperty="id"order="BEFORE"> 
              select SEQ_USER_ID.nextval as id from dual 
          </selectKey> 
           insert into user  (id,name,password) 
          values (#{id},#{name},#{password}) 
      </insert> 
       这句话会在插入user以前执行(order="BEFORE"),该句话执行完以后,会生成一个ID,传进来的参数User对象里的id字段就会被赋值成sequence的值。 

     对于mysql 
     <insert id="insertUser" parameterClass="XXX.User"> 
          insert into user (name,password) 
         values (#{id},#{name},#{password}) 
          <selectKey resultClass="long" keyProperty="id" order="after">  
             SELECT LAST_INSERT_ID() AS ID  
        </selectKey>  
      </insert> 
       将selectKey放在insert以后,经过LAST_INSERT_ID() 得到刚插入的自动增加的id的值。插入以后得到ID赋值到传进来的对象中(对象中必须有相应的属性)。.net

相关文章
相关标签/搜索