Hello everyone, I get a standard repository method a list of all records that have a parent_id == null field, to define the parent task in my application, then stream I go over this list, take the fields I need from the main list and add another new field, I create a new list, use this method to create a response to the client:

@GetMapping public List<TaskResponse> getTitleTask(@CurrentUser UserPrincipal userPrincipal) { User currentUser = userRepo.findById(userPrincipal.getId()).get(); List<TaskResponse> responseList = taskRepo .findAllByUserAndParentIdNullOrderByIdAsc(currentUser) .stream() .map(task -> new TaskResponse( task.getId(), task.getName(), task.getColor(), task.getImageUrl(), task.getCreated(), task.getExpiredDate(), task.getIsDone(), taskRepo.countByParentId(task) )).collect(Collectors.toList()); return responseList; } 

Task.class:

 @Entity @Data public class Task { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @NotBlank @Size(max = 30, min = 3) private String name; @Column(length = 4096) private String description; private String color; private String imageUrl; private LocalDateTime created; private LocalDateTime expiredDate; @NotNull private Boolean isDone; @JsonIgnore @ManyToOne @JoinColumn(name = "user_id") private User user; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "parent_task_id") private Task parentId; 

The way is working, but I don’t like that when I cycle through it, I turn to the database each time to get the number of child tasks of the current Task. Tell me how to do it right?

Table:

 create table if not exists task( id bigint not null constraint task_pkey primary key, color varchar(255), created timestamp, description varchar(4096), expired_date timestamp, image_url varchar(255), is_done boolean not null, name varchar(30), parent_task_id bigint constraint task_constraint references task, user_id bigint constraint user_constraint references usr); 

Task

    0