728x90
Domain
comment
@Entity
@Table
class Comment(
@Id @GeneratedValue(strategy = IDENTITY)
val id: Long? = null,
@ManyToOne(fetch = LAZY)
@JoinColumn(name = "issue_id")
val issue: Issue,
@Column
val userId: Long,
@Column
val username: String,
@Column
var body: String,
): BaseEntity() {
}
Issue 필드 추가
@Entity
@Table
class Issue(
//...
@OneToMany(fetch = EAGER)
val comments: MutableList<Comment> = mutableListOf(),
//..
) : BaseEntity() {
}
Repository
interface CommentRepository : JpaRepository<Comment, Long> {
}
Service
@Service
class CommentService(
private val commentRepository: CommentRepository,
private val issueRepository: IssueRepository,
) {
@Transactional
fun create(
issueId: Long,
userId: Long,
username: String,
request: CommentRequest,
) : CommentResponse {
val issue = issueRepository.findByIdOrNull(issueId) ?: throw NotFoundException("이슈가 존재하지 않습니다.")
val comment = Comment(
issue = issue,
userId = userId,
username = username,
body = request.body,
)
issue.comments.add(comment)
return commentRepository.save(comment).toResponse()
}
}
- issue를 조회해야 하므로, issueRepository도 주입받는다.
- 확장 함수 기능을 이용하여 Comment을 toReponse 함수를 작성해 Comment를 CommentResponse로 변경해준다.
Controller
@RestController
@RequestMapping("/api/v1/issues/{issueId}/comments")
class CommentController(
private val commentService: CommentService,
) {
@PostMapping
fun create(
authUser: AuthUser,
@PathVariable issueId: Long,
@RequestBody request: CommentRequest,
): CommentResponse {
return commentService.create(issueId, authUser.userId, authUser.username, request)
}
}
728x90
'실무 프로젝트로 배우는 Kotlin & Spring > 이슈 관리 서비스 개발하기' 카테고리의 다른 글
| 코멘트 수정/ 코멘트 삭제 (0) | 2022.11.27 |
|---|---|
| 이슈 수정 / 이슈 삭제 (0) | 2022.11.27 |
| 이슈 목록 조회/ 이슈 상세 조회 (0) | 2022.11.27 |
| 이슈 등록 (0) | 2022.11.27 |
| 공통 에러 처리 (0) | 2022.11.26 |