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

Spring Data MongoDB更新auth_otp状态查询失效及正确实现方案

解决Spring Data MongoDB更新auth_otp集合无返回结果的问题

问题根源分析

你当前的写法存在两个核心问题:

  1. void返回类型:这种定义只会执行更新操作,但不会返回任何数据,自然拿不到更新后的文档或更新数量。
  2. 缺少更新语句与注解:仅用@Query指定查询条件,没有声明更新逻辑,也未添加@Modifying注解,Spring Data不会执行更新操作,甚至可能只是执行了一次空查询。

解决方案

1. 返回更新的文档数量(最常用)

如果只需要知道有多少文档被更新,用long类型作为返回值,同时补充@Modifying和更新语句:

import org.springframework.data.mongodb.repository.Modifying;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface AuthOtpRepository extends MongoRepository<AuthOtp, String> {

    @Modifying
    @Query(value = "{'status': ?0, 'otp_type': ?1}", update = "{$set: {'status': 'INACTIVE'}}")
    long updateOtpStatus(String otpStatus, String otpType);
}

2. 返回更新后的单个文档

如果需要获取更新后的文档,开启returnNew = true,返回实体类对象(默认只更新第一个匹配的文档):

import org.springframework.data.mongodb.repository.Modifying;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface AuthOtpRepository extends MongoRepository<AuthOtp, String> {

    @Modifying
    @Query(value = "{'status': ?0, 'otp_type': ?1}", update = "{$set: {'status': 'INACTIVE'}}", returnNew = true)
    AuthOtp updateOtpStatusAndReturn(String otpStatus, String otpType);
}

3. 返回批量更新后的所有文档

如果需要更新所有匹配的文档并返回结果,添加multi = true(注意:部分Spring Data MongoDB版本对批量更新返回文档的支持有限,若失效可改用MongoTemplate实现):

import org.springframework.data.mongodb.repository.Modifying;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface AuthOtpRepository extends MongoRepository<AuthOtp, String> {

    @Modifying
    @Query(value = "{'status': ?0, 'otp_type': ?1}", update = "{$set: {'status': 'INACTIVE'}}", returnNew = true, multi = true)
    List<AuthOtp> updateAllOtpStatusAndReturn(String otpStatus, String otpType);
}

额外检查项

  • 集合名称映射:确保实体类上的@Document注解正确指向auth_otp集合:
    import org.springframework.data.mongodb.core.mapping.Document;
    
    @Document(collection = "auth_otp")
    public class AuthOtp {
        // 字段定义
    }
    
  • 字段名匹配:如果实体类字段用驼峰命名(如otpType),需用@Field注解映射到集合中的下划线字段:
    @Field("otp_type")
    private String otpType;
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 19:58:29