필수 구현 단계의 마지막 6단계를 작업했다.
- 6단계 : 일정 조회 개선
🔻 조건
- 일정 단건 조회 시 담당 유저들의 고유 식별자, 유저명, 이메일이 추가로 포함됩니다.
- 일정 전체 조회 시 담당 유저 정보가 포함되지 않습니다.
- JPA의 지연 로딩 기능을 활용합니다.
담당 유저들의 정보(id, username, email)를 응답받을 TodoUserResponseDto를 생성하고 이것을 담을 TodoResponseDto도 수정한다. 또한 TodoService도 수정한다.
@Getter
public class TodoUserResponseDto {
private Long userId;
private String username;
private String email;
public TodoUserResponseDto(UserTodo userTodo) {
this.userId = userTodo.getUser().getId();
this.username = userTodo.getUser().getUsername();
this.email = userTodo.getUser().getEmail();
}
}
담당 유저의 정보를 담을 필드 추가
private Set<TodoUserResponseDto> users;
또한 이러한 정보를 조회할 때 포함할지 안 할지도 수정
public TodoResponseDto(Todo todo, boolean includeUsers) {
this.id = todo.getId();
this.title = todo.getTitle();
this.content = todo.getContent();
this.createdAt = todo.getCreatedAt();
this.modifiedAt = todo.getModifiedAt();
if (includeUsers) {
// 지연 로딩을 강제로 트리거하여 userTodos를 로딩
todo.getUserTodos().size();
this.users = todo.getUserTodos().stream()
.map(TodoUserResponseDto::new)
.collect(Collectors.toSet());
} else {
this.users = Set.of(); // 전체 조회 시 유저 정보 미포함
}
this.commentCount = todo.getComments() != null ? todo.getComments().size() : 0;
}
- 생성 - 조회 X
- 유저 추가 - 조회 X
- 단일 조회 - 조회 O
- 전체 조회 - 조회 X
- 수정 - 조회 X
만약 조회할 필요가 없으면 밑에 처럼 수정
return new TodoResponseDto(newTodo, false);
조회할 필요가 있으면 밑에 처럼 수정
return new TodoResponseDto(todo, true);
또한 일정을 생성할 때 담당 유저를 추가하는 과정에서 중복을 허용하지 않도록 코드를 수정했다.
// 추가 담당 유저 설정
if (requestDto.getUserIds() != null) {
List<User> additionalUsers = userRepository.findAllById(requestDto.getUserIds());
for (User additionalUser : additionalUsers) {
// 중복된 담당 유저 추가 방지
if (userTodoRepository.findByTodoAndUser(newTodo, additionalUser) == null) {
UserTodo additionalUserTodo = new UserTodo();
additionalUserTodo.setTodo(newTodo);
additionalUserTodo.setUser(additionalUser);
userTodoRepository.save(additionalUserTodo);
}
}
}
그러면 일정을 CRUD를 할 때 담당 유저 정보의 유무를 구분했다.