[내일배움캠프] Spring 베이직 일정관리 앱 Step3.

김재진·2026년 1월 2일

내일배움캠프

목록 보기
29/70

1. 댓글 기능 추가

  • 댓글 생성(댓글 작성하기)
    • 일정에 댓글을 작성할 수 있습니다.
    • 댓글 생성 시, 포함되어야할 데이터
      • 댓글 내용, 작성자명, 비밀번호, 작성/수정일, 일정 고유식별자(ID)를 저장
      • 작성/수정일은 날짜와 시간을 모두 포함한 형태
    • 각 일정의 고유 식별자(ID)를 자동으로 생성하여 관리
    • 최초 생성 시, 수정일작성일과 동일
    • 작성일, 수정일 필드는 JPA Auditing을 활용하여 적용합니다.
    • 하나의 일정에는 댓글을 10개까지만 작성할 수 있습니다.
    • API 응답에 비밀번호는 제외해야 합니다

2. Github 주소

일정관리 github

3. 댓글 기능 코드

  • Entity
@Getter
@Entity
@Table(name = "comments")
@NoArgsConstructor (access = AccessLevel.PROTECTED)
public class Comment extends BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long commentId;
    private String contents;
    private String name;
    private String password;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "schedulerId")
    private Scheduler scheduler;

    public Comment(String contents, String name, String password, Scheduler scheduler) {
        this.contents = contents;
        this.name = name;
        this.password = password;
        this.scheduler = scheduler;
    }
}
  • Controller
@RestController
@RequiredArgsConstructor
public class CommentController {

    private final CommentService commentService;

    @PostMapping("schedulers/{schedulerId}/comments")
    public ResponseEntity<CommentCreateResponse> commentCreate(
            @PathVariable Long schedulerId,
            @RequestBody CommentCreateRequest request
    ) {
        return ResponseEntity.status(HttpStatus.CREATED).body(commentService.save(schedulerId, request));
    }

}
  • Service
@Service
@RequiredArgsConstructor
public class CommentService {

    private final CommentRepository commentRepository;
    private final SchedulerRepository schedulerRepository;

    @Transactional
    public CommentCreateResponse save(Long schedulerId, CommentCreateRequest request) {
        // 게시글 확인
        Scheduler scheduler = schedulerRepository.findById(schedulerId).orElseThrow(
                () -> new RuntimeException("해당 게시글이 없습니다."));

        // 댓글 개수 제한 (10개)
        long commentCount = commentRepository.count();
        if (commentCount > 10) {
            throw new IllegalStateException("10개 이상 작성이 불가합니다.");
        }

        // 댓글 생성
        Comment comment = new Comment(
                request.getContents(),
                request.getName(),
                request.getPassword(),
                scheduler
        );

        // 댓글 저장
        Comment savedComment = commentRepository.save(comment);
        return new CommentCreateResponse(
                savedComment.getCommentId(),
                savedComment.getContents(),
                savedComment.getName(),
                savedComment.getScheduler(),
                savedComment.getCreatedAt(),
                savedComment.getModifiedAt()
        );
    }
}
  • Repository
public interface CommentRepository extends JpaRepository<Comment, Long> {
}

-> 원문과 연결하여 댓글을 달 수 있는 기능을 추가했다.

profile
개발공부 처음해보는 사람

0개의 댓글