Peter Penzov
Peter Penzov

Reputation: 1588

Implement Sorting for order

I want to implement sorting for a list of filters assigned for a terminal in Spring endpoint when one filter is dragged and the order of all filters if calculated again. I tried this:

DTO:

public class FilterNewDTO {

    private Integer id;

    private Integer terminal_id;

    private Integer position;

    private Integer parent_id;
}

Endpoint:

@PostMapping("filter/updated_position/{id}")
    public ResponseEntity<?> saveFilterPosition(@PathVariable Integer id, @RequestBody FilterNewDTO dto) {

        List<Filters> list = filterService.findFiltersByTerminalId(dto.getTerminal_id());

        for (int i=0; i<list.size(); i++) {
            Filters filter = list.get(i);

            int current_position = 0;
            current_position = filter.getPosition();

            filter.setPosition(current_position + 1);
            filter.update(risk_mapper.toFilter(dto));

            filterService.save(filter);
        }

        return ok().build();
}

But as you can see I just iterate over the list of filters by terminal id. What will happen if I change the filter position from 3 to 5? I suppose that portions 1-3 should not be incremented. Can you give me some guidance how to implement this?

Upvotes: 1

Views: 93

Answers (2)

tevemadar
tevemadar

Reputation: 13195

Assuming you want the filters numbered from 1...n for each terminal, the setPosition() part should rather be

filter.setPosition(i+1);

Upvotes: 0

Alexander Petrov
Alexander Petrov

Reputation: 9492

Instead of thinking about the filters as individual filters think of them as a bulk. You get the list of filters you re-arrange them in a new list. You are satisfied with the order then you update all of them instead of one by one of them. You should not worry of performance for this operation as hibernate will manage to differentiate the changed filters from the unchanged.

something like:

    List<Filter> originalList;
    List<Filter> newlyOrderedList;

//do your ordering here

filterRepository.saveAll(newlyOrderedList);

Upvotes: 2

Related Questions