You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JPA CrudRepository自定义更新/删除查询不修改MySQL数据库问题求助

问题根因与修复方案

你遇到的自定义操作不生效问题主要是两个常见的Spring Data JPA使用疏漏,按以下步骤修复即可:

  • 补全@Param参数绑定注解:默认情况下Java编译不会保留方法参数名,Spring Data JPA无法自动匹配方法参数和JPQL中定义的参数名,会导致查询条件实际匹配不到对应数据,执行后自然无数据变更。
  • 修正JPQL中的布尔值赋值:你的实体类中approved字段是Boolean类型,JPQL中直接写数字1会存在类型映射问题,应该直接使用布尔值true。
  • 可选优化:将更新、删除方法的返回值改为int,可以直接接收执行后受影响的行数,方便后续排查时确认是否真的匹配到了待修改的数据。

修正后的BusinessRepository代码

import com.rmit.sept.bk_loginservices.model.Business;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public interface BusinessRepository extends CrudRepository<Business, Long> {

    // Don't use `SELECT * FROM Business WHERE businessId = :businessId` it doesn't work!
    @Query("FROM Business b WHERE b.userKey = :userKey")
    Business getBusinessByUserPrimaryKey(@Param("userKey") Long userKey);

    @Modifying
    @Transactional
    @Query("UPDATE Business b SET b.approved = true WHERE b.businessId = :businessId")
    int approveBusiness(@Param("businessId") String businessId);

    @Modifying
    @Transactional
    @Query("DELETE FROM Business b WHERE b.businessId = :businessId")
    int rejectBusiness(@Param("businessId") String businessId);
}

额外排查点

如果修复后还是不生效,可以再检查以下两点:

  1. 确认项目中导入的@Transactional注解是org.springframework.transaction.annotation.Transactional,不要使用javax.transaction.Transactional,后者和Spring Data JPA的适配存在很多坑。
  2. 检查Service层调用这两个方法时,有没有捕获异常后没有抛出的情况,默认Spring事务只会在发生RuntimeException或Error时回滚,如果业务代码吞了异常会导致事务逻辑异常。

内容的提问来源于stack exchange,提问作者perrywinkle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 05:45:04