댓글필드 | 데이터 유형 |
---|---|
아이디(고유번호) | bigint |
댓글내용 | varchar |
사용자 아이디 | varchar |
일정 아이디 | bigint |
작성일자 | timestamp |
User
todo
comment
사용자 필드 | 데이터 유형 |
---|---|
아이디(고유번호) | bigint |
별명 | varchar |
사용자 이름 | varchar |
비밀번호 | varchar |
권한 | varchar |
생성일 | timestamp |
User 테이블이 생기면서 기존 Todo에 존재하는 password field가 중복된다고 판단.
일정 필드 | 데이터 유형 |
---|---|
아이디(고유번호) | bigint |
사용자 이름 | varchar |
제목 | varchar |
내용 | varchar |
비밀번호 | varchar |
생성일 | timestamp |
package io._2minus.todoapp.entity;
import jakarta.persistence.*;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Entity
@Getter
@Setter
@NoArgsConstructor
public class Comment extends Timestamped{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long commentId;
@Column(nullable = false)
private String content;
@ManyToOne
@JoinColumn(name = "user_id", nullable = false)
private User user;
@ManyToOne
@JoinColumn(name = "todo_id",nullable = false)
private Todo todo;
@Builder
public Comment(User user, Todo todo, String content) {
this.user = user;
this.todo = todo;
this.content = content;
}
}
수정 : entity.Todo
package io._2minus.todoapp.entity;
import jakarta.persistence.*;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Entity
@NoArgsConstructor
@Table(name = "todo")
public class Todo extends Timestamped {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "todo_id", nullable = false)
private long todoId;
@Column(nullable = false)
private String title;
@Column(nullable = false)
private String content;
@Column(nullable = false)
private String userName;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
private User user;
@Builder
public Todo(User user, String title, String content, String userName) {
this.user = user;
this.title = title;
this.content = content;
this.userName = userName;
}
}
구현 : entity.User
package io._2minus.todoapp.entity;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Entity
@Getter
@Setter
@NoArgsConstructor
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String nickname;
@Column(nullable = false, unique = true)
private String username;
@Column(nullable = false)
private String password;
@Column(nullable = false)
@Enumerated(value = EnumType.STRING)
private UserRoleEnum role;
public User(String nickname, String username, String password, UserRoleEnum role) {
this.nickname = nickname;
this.username = username;
this.password = password;
this.role = role;
}
}
고유번호
, 댓글 내용
, 댓글을 작성한 사용자 아이디
, 댓글이 작성된 일정 아이디
, 작성일자
를 저장할 수 있습니다.CommentService.createComment
// todoRepository에서 id로 조회 및 예외처리
Todo todo = todoRepository.findById(dto.getTodo().getTodoId()).orElseThrow(()->
new NullPointerException("잘못된 접근입니다."));
CommentRequestDTO
// validation으로 예외처리
@NotBlank
private String content;
CommentService.createComment
// save 후 commentRepository에서 조회 및 예외처리
commentRepository.save(comment);
return commentRepository.findById(comment.getCommentId()).orElseThrow(()
-> new IllegalArgumentException("저장에 오류가 발생했습니다."));
package io._2minus.todoapp.repository;
import io._2minus.todoapp.entity.Comment;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CommentRepository extends JpaRepository<Comment, Long> {
}
service.CommentService.createComment
import io._2minus.todoapp.repository.CommentRepository;
import io._2minus.todoapp.repository.TodoRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@RequiredArgsConstructor
public class CommentService {
private final CommentRepository commentRepository;
private final TodoRepository todoRepository;
@Transactional
public Comment createComment(Long todoId, User user, CommentRequestDTO dto) {
Todo todo = todoRepository.findById(todoId).orElseThrow(()->
new NullPointerException("잘못된 접근입니다."));
var comment = dto.toEntity(user, todo);
commentRepository.save(comment);
return commentRepository.findById(comment.getCommentId()).orElseThrow(()
-> new IllegalArgumentException("저장에 오류가 발생했습니다."));
}
}
controller.CommentController.postComment
@RequestMapping("/v1.0/todo/{todoId}/comments")
@RestController
@RequiredArgsConstructor
public class CommentController {
public final CommentService commentService;
@PostMapping
public ResponseEntity<CommonResponse<CommentResponseDTO>> postComment(@PathVariable Long todoId, @AuthenticationPrincipal UserDetailsImpl userDetails, @RequestBody CommentRequestDTO dto) {
Comment comment = commentService.createComment(todoId, userDetails.getUser(), dto);
CommentResponseDTO response = new CommentResponseDTO(comment);
return ResponseEntity.ok().body(CommonResponse.<CommentResponseDTO>builder()
.statusCode(HttpStatus.OK.value())
.msg("생성이 완료되었습니다.")
.data(response)
.build());
}
}
댓글 내용
만 수정 가능합니다.위와 다르지 않음.
@Transactional
public Comment updateComment(Long todoId, User user, Long commentId, CommentRequestDTO dto) {
Comment comment = checkUserAndGetComment(todoId, user, commentId);
comment.setContent(dto.getContent());
return commentRepository.save(comment);
}
controller.CommentController.putComment
@PutMapping("/{commentId}")
public ResponseEntity<CommonResponse<CommentResponseDTO>> putComment(@PathVariable Long todoId, @AuthenticationPrincipal UserDetailsImpl userDetails, @PathVariable Long commentId, @RequestBody CommentRequestDTO dto) {
Comment comment = commentService.updateComment(todoId, userDetails.getUser(), commentId, dto);
CommentResponseDTO response = new CommentResponseDTO(comment);
return ResponseEntity.ok().body(CommonResponse.<CommentResponseDTO>builder()
.statusCode(HttpStatus.OK.value())
.msg("수정 내용 : " + comment.getContent())
.data(response)
.build());
}
@Transactional
public void deleteComment(Long todoId, User user, Long commentId) {
Comment comment = checkUserAndGetComment(todoId, user, commentId);
commentRepository.delete(comment);
}
controller.CommentController.deleteComment
@DeleteMapping("/{commentId}")
public ResponseEntity<CommonResponse> deleteComment(@PathVariable Long todoId, @AuthenticationPrincipal UserDetailsImpl userDetails, @PathVariable Long commentId, @RequestBody CommentRequestDTO dto) {
commentService.deleteComment(todoId, userDetails.getUser(), commentId);
return ResponseEntity.ok().body(CommonResponse.<CommentResponseDTO>builder()
.statusCode(HttpStatus.OK.value())
.msg("삭제가 완료되었습니다.")
.build());
}