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

如何使用Spring Data MongoDB添加可选查询参数?附控制器代码

如何用Spring Data MongoDB实现带可选查询参数的接口

看起来你已经搭好了控制器的基本结构,接下来我们用Spring Data MongoDB的MongoTemplate和Criteria来实现动态的可选参数查询,这是最灵活的方式,能轻松处理任意数量的可选条件。

首先,先把你的控制器代码补全并优化一下(比如用构造函数注入,调整参数接收方式更友好):

@RestController
public class ActionController {
    private final ActionService actionService;

    // 构造函数注入(推荐的依赖注入方式)
    public ActionController(ActionService actionService) {
        this.actionService = actionService;
    }

    @GetMapping("/action/{id}") // 用@GetMapping替代@RequestMapping更简洁
    public ResponseEntity<List<Action>> getActionList(
            @PathVariable("id") long id,
            @RequestParam(value = "actionType", required = false) ActionType actionType,
            // 推荐用Map接收任意可选参数,比数组更灵活,用户可以传?status=active&priority=high这样的参数
            @RequestParam(required = false) Map<String, String> optionalParams) {
        
        List<Action> actionList = actionService.getActionList(id, actionType, optionalParams);
        return ResponseEntity.ok(actionList);
    }
}

接下来是Service层的实现,核心是用Criteria动态构建查询条件:

1. 定义Service接口

public interface ActionService {
    List<Action> getActionList(long relatedId, ActionType actionType, Map<String, String> optionalParams);
}

2. 实现Service逻辑

@Service
public class ActionServiceImpl implements ActionService {

    private final MongoTemplate mongoTemplate;

    public ActionServiceImpl(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    @Override
    public List<Action> getActionList(long relatedId, ActionType actionType, Map<String, String> optionalParams) {
        // 先添加必填的关联ID条件(假设你的Action实体里对应这个ID的字段是relatedId,根据实际调整)
        Criteria criteria = Criteria.where("relatedId").is(relatedId);

        // 处理可选的actionType参数:如果参数存在,追加查询条件
        if (actionType != null) {
            criteria.and("actionType").is(actionType);
        }

        // 处理任意可选参数:遍历Map,把每个键值对作为查询条件
        if (optionalParams != null && !optionalParams.isEmpty()) {
            optionalParams.forEach((fieldName, fieldValue) -> 
                criteria.and(fieldName).is(fieldValue)
            );
        }

        // 构建Query并执行查询
        Query query = new Query(criteria);
        return mongoTemplate.find(query, Action.class);
    }
}

3. 配套的实体类示例

确保你的Action实体和枚举类配置正确:

@Document(collection = "actions") // 指定MongoDB集合名
public class Action {
    @Id
    private String id;
    private long relatedId; // 对应控制器里的path变量id
    private ActionType actionType;
    // 其他业务字段,比如status、priority等
    private String status;
    private String priority;

    // getter、setter方法
}

public enum ActionType {
    CREATE, UPDATE, DELETE // 枚举值根据你的业务定义
}

测试请求示例

现在你可以用不同的参数组合来测试接口:

  • 只查询指定ID的所有动作:GET /action/123
  • 按ID+动作类型查询:GET /action/123?actionType=CREATE
  • 按ID+动作类型+额外条件查询:GET /action/123?actionType=UPDATE&status=active&priority=high

备选方案:用Example查询

如果你喜欢更简洁的方式,也可以用Spring Data的Example API,适合简单的匹配场景:

// Service层示例
@Override
public List<Action> getActionList(long relatedId, ActionType actionType, Map<String, String> optionalParams) {
    Action probe = new Action();
    probe.setRelatedId(relatedId);
    if (actionType != null) {
        probe.setActionType(actionType);
    }
    // 如果需要处理optionalParams,可以用BeanUtils把Map转成实体属性
    Example<Action> example = Example.of(probe);
    return actionRepository.findAll(example);
}

这种方式适合字段匹配逻辑简单的场景,但灵活性不如Criteria。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:19:52