mybatis中update语句使用selectKey返回更新的主键

2 篇文章 0 订阅
2 篇文章 0 订阅

想法:更新某条符合条件的记录的状态status为1,并且返回这条记录的id。如果没有符合条件的记录,就返回0。
update语句默认返回的是影响到的记录数,用selectKey可以返回指定属性值到 传入的对象。

比如updateStatus(exampleObject),执行sql update 后

使用 exampleObject.getId()可以得到 被修改的记录的id

本篇涉及到 selectKey、 mysql的ifnull()、max()

假设ExampleObject 属性有主键id, is_delete,status,relation_id…等其他属性

第一部分:ExampleObjectImpl.java

 	@Resource
    ExampleObjectMapper exampleObjectMapper;

	@Override
    public Long updateStatus(ExampleObject exampleObject ) {
        int affectRow=exampleObjectMapper.updateStatus(exampleObject );
        System.out.println("修改成功?:"+affectRow);
        System.out.println("返回的id:"+exampleObject .getId());
        return exampleObject.getId();
    }

第二部分:ExampleObjectMapper .java

注意 这里int值 不是返回的主键id,是修改的行数

int updateStatus(ExampleObject exampleObject);

第三部分:ExampleObjectMapper .xml

order=“AFTER”:在update语句执行后 再执行selectKey
keyProperty="id:select语句返回的 id 要赋给哪个属性

<update id="updateStatus"  parameterType="com.*******.model.ExampleObject" >
        <selectKey resultType="java.lang.Long" keyColumn="id" keyProperty="id" order="AFTER">
            select id from example_table
            where relation_id=#{relationId}
        </selectKey>
        update example_table
        set status=0,relation_id=#{relationId}
        where  is_delete=0 and status=1
        and unix_timestamp( start_date )  =unix_timestamp( #{startDate} )
        and unix_timestamp( end_date )  =unix_timestamp( #{endDate} )
        limit 1
</update>

在这里插入图片描述到这里出现了问题:控制台报错ExecutorException: SelectKey returned no data.
如果update语句修改的行数为0,或者
如果没有符合条件的记录 select语句的结果就是 N/A
在这里插入图片描述
ifnull()处理不了 N/A,再加个max(),当查询结果为 N/A时,max(id)的值为null,这样报错就处理好了。

<update id="updateStatus"  parameterType="com.*******.model.ExampleObject">
        <selectKey resultType="java.lang.Long" keyColumn="id" keyProperty="id" order="AFTER">
            select ifnull(max(id),0) id from example_table
            where relation_id=#{relationId}
        </selectKey>
        update example_table
        set status=0,relation_id=#{relationId}
        where  is_delete=0 and status=1
        and unix_timestamp( start_date )  =unix_timestamp( #{startDate} )
        and unix_timestamp( end_date )  =unix_timestamp( #{endDate} )
        limit 1
</update>

结果
在这里插入图片描述
在这里插入图片描述

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值