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

Spring Boot 3中如何将类属性作为URL参数实现任务状态筛选?

实现按任务完成状态筛选的接口

步骤1:修改控制器方法,添加请求参数

在原有的listAllTasks方法中,加入@RequestParam接收completed参数。选用Boolean类型(支持空值),确保用户不传该参数时仍能返回全部任务:

@Autowired
private TaskRepository repository;

@GetMapping
public Page<TaskListingData> listAllTasks(
        Pageable pagination,
        @RequestParam(name = "completed", required = false) Boolean completed) {
    
    Page<Task> tasksPage;
    if (completed != null) {
        // 传入状态参数时,按条件筛选
        tasksPage = repository.findByCompleted(completed, pagination);
    } else {
        // 未传参数时,返回所有任务
        tasksPage = repository.findAll(pagination);
    }
    return tasksPage.map(TaskListingData::new);
}

步骤2:在TaskRepository中添加查询方法

借助Spring Data JPA的方法命名规则,直接定义分页筛选方法,无需手写SQL:

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;

public interface TaskRepository extends JpaRepository<Task, Long> {
    // 按completed状态分页查询任务
    Page<Task> findByCompleted(boolean completed, Pageable pageable);
}

接口验证

现在可以通过以下地址调用接口:

  • 查询所有任务:http://localhost:8080/tasks
  • 查询已完成任务:http://localhost:8080/tasks?completed=true
  • 查询未完成任务:http://localhost:8080/tasks?completed=false

补充说明

  • 使用Boolean而非基本类型boolean,是因为required=false时未传参数会返回null,基本类型无法接收空值。
  • Spring Data JPA会自动根据方法名生成对应的SQL查询语句,无需额外配置。

内容的提问来源于stack exchange,提问作者João Pedro Checco

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 05:22:09