selectkey

 

ibatis的selectkey

  在使用ibatis插入数据进数据库的时候,会用到一些sequence的数据,有些情况下,在插入完成之后还需要将sequence的值返回,然后才能进行下一步的操作。 
      使用ibatis的selectKey就可以得到sequence的值,同时也会将值返回。不过对于不同的数据库有不同的操作方式。 
      对于oracle: 
      <insert id="insertUser" parameterClass="ibatis.User"> 
          <selectKey resultClass="long" keyProperty="id"> 
              select SEQ_USER_ID.nextval as id from dual 
          </selectKey> 
           insert into user 
          (id,name,password) 
          values 
          (#id#,#name#,#password#) 
      </insert> 
       该句话执行完之后,传进来的参数User对象DO里的id字段就会被赋值成sequence的值。 

     对于mysql 
     <insert id="insertUser" parameterClass="ibatis.User"> 
          insert into user 
          (name,password) 
          values 
          (#name#,#password#) 
          <selectKey resultClass="long" keyProperty="id">  
             SELECT LAST_INSERT_ID() AS ID  
        </selectKey>  
      </insert> 
       将selectKey放在insert之后,通过LAST_INSERT_ID() 获得刚插入的自动增长的id的值。

<insert id="addMetaReport" parameterClass="metaRpo">
		<![CDATA[
			insert IGNORE into rpo_trackingMeta(trackingMeta_id, trackingMeta_title, company_id, subCompany_id, meta_type,
			delegation_at, report_cycle, start_at, end_at, matched_num_new, matched_num_takeoff, matched_num_total,
			created_at, created_by, updated_at, updated_by)
			select	  #trackingMetaId#
					, #metaTitle#
					, #companyId#
					, #subCompanyId#
					, #metaType#
					, #delegationAt#
					, #reportCycle#
					, #startAt#
					, #endAt#
					, sum(case when created_at >= #startAt# and created_at < #endAt# then 1 else 0 end)
					, 0
					, count(*)
					, now()
					, #createdBy#
					, now()
					, #updatedBy#
		  from matchedPage where task_id = #orderId#
		  and verification = 'mediadna';
		   ]]>
		  <selectKey keyProperty="id" resultClass="int">
			SELECT IF(row_count() > 0, last_insert_id(), 0) AS id FROM dual
		</selectKey>
	</insert>
 

 

你可能感兴趣的:(select)