mysql 存储过程,以及mybatis如何调用

说道存储过程,很多人都知道,但是真正用的人其实很少,但是在某些必要的场景,是必须使用的,虽然可以使用java代码解决,但是效率性能远不及存储过程

曾经在sqlserver 以及pgadmin上用过,mysql还真没使用过,今天遇到这样的场景那就使用一次吧

场景:订单自动失效,定时任务跑批的时候会查询出失效的订单,根据失效的订单中的相关item的id,再做相应的处理

begin
     declare cargoSourceId varchar(20);
    
     declare done int;
     declare cur_test CURSOR for select cargo_source_id from orders where order_status = '10' and datediff(NOW(),update_time)>=3;
     declare continue handler FOR SQLSTATE '02000' SET done = 1;
     
         open cur_test;
         repeat
             fetch cur_test into cargoSourceId;
                         # 将要取消的失效对于的货源全部更新为“未下单”状态
             update cargo_source set is_ordered=0,update_time=now() where id=cargoSourceId;
         until done end repeat;
         close cur_test;
            # 失效订单
            update orders set order_status='50', update_time=now() where order_status = '10' and datediff(NOW(),update_time)>=3;

 end

mybatis调用:

<!-- 调用存储过程 -->
    <update id="updateOrderInvalidAfter3Days" statementType="CALLABLE">
         CALL updateOrderInvalidAfter3Days
     </update>

service调用:

@Autowired
    private OrdersMapper ordersMapper;
    
    @Override
    public void updateOrderInvalidAfter3Days() {
        int result = ordersMapper.updateOrderInvalidAfter3Days();
        System.out.println(result);
    }

tips:同样的结果不同的手段,使用更优的手段来解决问题,几年前我会选择方便自己的做法,而现在要更多的考虑项目。

原文地址:https://www.cnblogs.com/leechenxiang/p/5822172.html