【问题标题】:Get SUM of matched records and then UPDATE those records using JPA获取匹配记录的总和,然后使用 JPA 更新这些记录
【发布时间】:2020-06-07 06:52:20
【问题描述】:

首先,我想根据一些参数获取匹配记录的总和,为此我编写了以下查询 -

@Query(value = "select sum(charges) from usage_logs where X=:x and Y=:y and Z=:z  and status=1", nativeQuery = true)
Double getCharges(@Param("x")String x,@Param("y") String y,@Param("z") String z);

同时,我想将匹配记录的状态更新为“0”(紧随其后计算费用)。

那么,在获得 SUM 后是否有任何优化的方法来更新记录,或者我需要获取匹配记录的 ids 并使用批处理函数单独更新。

【问题讨论】:

    标签: mysql spring-boot jpa spring-data-jpa


    【解决方案1】:

    您可以为此使用事务。 SQL 就是这四个语句。

    START TRANSACTION;
    select sum(charges) from usage_logs where X=:x and Y=:y and Z=:z  and status=1 FOR UPDATE;
    
    UPDATE usage_logs SET status=0 where X=:x and Y=:y and Z=:z  and status=1;
    COMMIT;
    

    transaction 保护您的操作免受数据库上同时发生的其他事情的干扰。它确保WHERE 子句的两种用法都选择完全相同的行。而且,如果您的程序逻辑决定您不想继续更新,您可以说 ROLLBACK; 代替 COMMIT;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-13
      • 1970-01-01
      • 2013-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多