简体   繁体   中英

Spring-data incorrectly forms the request

I have table tasks:

create table tasks
(
    id          bigserial,
    title       varchar(25) not null,
    leader_id   bigint      not null,
    project_id  bigint      not null,
    deadline    date        not null,
    primary key (id),
    foreign key (leader_id) references users (id),
    foreign key (project_id) references projects (id),
    is_archived BOOLEAN default FALSE
);

Task rest controller:

@GetMapping
public List<Task> getAllTasksByProjectId(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                         @RequestParam(required = false) MultiValueMap<String, String> params) {
    TaskFilter taskFilter = new TaskFilter(params);
    return taskService.findAllTasksByProject(taskFilter.getSpec(), page - 1, 5).getContent();
}

Service:

public Page<Task> findAllTasksByProject(Specification<Task> spec, int page, int size) {
    return taskRepository.findAll(spec, PageRequest.of(page, size));
}

Repository:

@Repository
public interface TaskRepository extends JpaRepository<Task, Long>, JpaSpecificationExecutor<Task> {
}

Filter:

 public TaskFilter(MultiValueMap<String, String> params) {
        spec = Specification.where(null);
        if (params.containsKey("is_archived")) {
            spec.and(TaskSpecifications.isArchived(Boolean.parseBoolean(params.getFirst("is_archived"))));
            System.out.println(params.getFirst("is_archived"));
        }
        if (params.containsKey("project")) {
            spec = spec.and(TaskSpecifications.projectEqual(Long.parseLong(params.getFirst("project"))));
        }
    }

And Specification:

public static Specification<Task> projectEqual(Long projectId) {
    return (Specification<Task>) (root, criteriaQuery, criteriaBuilder) -> criteriaBuilder.equal(root.get("project"), projectId);
}
public static Specification<Task> isArchived(Boolean isArchived) {
    return (Specification<Task>) (root, criteriaQuery, criteriaBuilder) -> criteriaBuilder.equal(root.get("isArchived"), isArchived);
}

So I want to get all tasks that is_archived = true or false. But I get all tasks. For exmaple get request to

localhost:8189/tm/api/v1/tasks?page=1&is_archived=false

returns tasks with is_archived = true and false. What problem it can be?

I have mistake in this line:

spec.and(TaskSpecifications.isArchived(Boolean.parseBoolean(params.getFirst("is_archived"))));

Every time I create new specification, instead of add in old specification.

spec = spec.and(TaskSpecifications.isArchived(Boolean.parseBoolean(params.getFirst("is_archived"))));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM