selectKey在Mybatis中是为了解决Insert数据时不支持主键自动生成的问题,他可以很随意的设置生成主键的方式。但是最近项目中修改了同事的一个bug,通过selectKey解决的。内容如下
@TableField(exist = false)
private int count;
<!--新增-->
<update id="insertBatchFor" parameterType="com.ct.business.domain.DeductionRecordEntity">
<!--查看是否已经修改成功,修改成功了则修改,否则不修改-->
<selectKey keyProperty="count" order="BEFORE" resultType="int" >
select count(1) as count from tb_deduction_record where user_id = #{userId} AND trade_type = #{tradeType}
and type = #{type} and DATE_FORMAT(create_time,'%Y-%m-%d') = DATE_FORMAT(#{createTime},'%Y-%m-%d')
</selectKey>
<!--如果等于null新增-->
<if test="count==0 ">
INSERT INTO tb_deduction_record (id, user_id, user_name, user_phone, business_id, amount, reason, create_by, create_time, trade_type, type, site_id)
values (#{id},#{userId},#{userName},#{userPhone},#{businessId},#{amount},#{reason},#{createBy},#{createTime},#{tradeType},#{type},#{siteId})
</if>
<if test="count !=0 ">
select 1 as count from dual
</if>
</update>