댓글 내용, 작성자명, 비밀번호, 작성/수정일, 일정 고유식별자(ID)를 저장작성/수정일은 날짜와 시간을 모두 포함한 형태수정일은 작성일과 동일작성일, 수정일 필드는 JPA Auditing을 활용하여 적용합니다.비밀번호는 제외해야 합니다@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;
}
}
@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
@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()
);
}
}
public interface CommentRepository extends JpaRepository<Comment, Long> {
}
-> 원문과 연결하여 댓글을 달 수 있는 기능을 추가했다.