对Mybatis传参使用了@Param之后执行插入操作返回主键的问题解决办法

今天做项目时,遇到了需要返回刚插入数据的自增主键ID的问题,发现从object中getId返回对的一直是空的,上网查了资料的都是

类似于这样,
 <insert id="insertAndgetkey" parameterType="com.soft.mybatis.model.User">
        <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
            SELECT LAST_INSERT_ID()
        </selectKey>
        insert into t_user (username,password,create_date) values(#{username},#            
       {password},#{createDate})
</insert>

对应的dao都是这样类型

int insertAndGeyKey(User user);

但是我项目里面使用了@Param注解,而且是传入了两个参数如下:

public Long insertExpression(@Param("orgId") Long orgId,@Param("expression") EventEmotionExpression expression);

最开始我的sql文件里是这么写的:

<insert id="insertExpression" >
		<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
			select last_insert_id()
		</selectKey>
		insert into event_emotion_expression_#{orgId}
		  <include refid="columns"/>
		values(
			#{expression.eventId},#{expression.name},
			#{expression.weight},#{expression.categoryId},
			#{expression.sourceStartTime},#{expression.sourceEndTime},
			#{expression.insertDate}
		)
	</insert>

搞了好久发现返回的ID一直都是null,马上都要开始怀疑人生了,后来终于有了突破,因为selectkey标签是负责查询本次插入数据使用的主键ID然后复制到对应的keyProperty对一个的属性上,而我的id属性是在expression对象上的,只写了一个id肯定是赋值不上去的,所以keyProperty的属性需要写为“expression.id”,完美解决。

最后的sql文件为:

<insert id="insertExpression" >
		<selectKey keyProperty="expression.id" order="AFTER" resultType="java.lang.Long">
			select last_insert_id()
		</selectKey>
		insert into event_emotion_expression_#{orgId}
		  <include refid="columns"/>
		values(
			#{expression.eventId},#{expression.name},
			#{expression.weight},#{expression.categoryId},
			#{expression.sourceStartTime},#{expression.sourceEndTime},
			#{expression.insertDate}
		)
	</insert>

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值