항해99/스프링 심화

재영매니저님 강의

숲별 2022. 10. 17. 22:54
728x90

package com.sparta.jwt_submit_try4.entity;


import com.fasterxml.jackson.annotation.JsonIgnore;
import com.sparta.jwt_submit_try4.controller.dto.CommentRequestDto;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import javax.persistence.*;

@NoArgsConstructor
@Setter
@Getter
@Entity
public class Comment extends Timestamped{

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@Column(nullable = true)
private String comments;

// ManyToOne, OneToMany 양방향 연관관계에서 ManyToOne이 연관관계의 주인이 됩니다.
// 연관관계의 주인이란 상대방의 primary key(PK)를 관리하는 것입니다. 이를 foreign key (외래키) 라고 합니다.
// 연관 관계의 주인 쪽에서 저장 수정쪽에서 나타납니다.
@ManyToOne
@JsonIgnore
@JoinColumn(name = "post_id")
private Post post;

public Comment(String contents) {
this.comments = contents;
}
public Comment(CommentRequestDto requestDto) {
this.comments = requestDto.getComments();
}

// requestDto, post를 받아서 comment를 생성할께 (구현)
public Comment(CommentRequestDto requestDto, Post post) {
this.comments = requestDto.getComments();
this.post = post;
}

public void update(CommentRequestDto requestDto) {
this.comments = requestDto.getComments();
}


}

///////////////////
////////////
package com.sparta.jwt_submit_try4.service;

import com.sparta.jwt_submit_try4.controller.dto.CommentRequestDto;
import com.sparta.jwt_submit_try4.entity.Comment;
import com.sparta.jwt_submit_try4.entity.Post;
import com.sparta.jwt_submit_try4.repository.CommentRepository;
import com.sparta.jwt_submit_try4.repository.PostRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class CommentService {

private final CommentRepository commentRepository;
private final PostRepository postRepository;

/*public List<Comment> getAllcomment() {
}*/

public Comment createComment(CommentRequestDto requestDto) {
// 상황: 사용자가 게시글 a에 댓글 b를 달아놓은 상태에요
// a라는 게시글을 들고옵니다.
Post post = postRepository.findById(requestDto.getPostId()).orElseThrow(
() -> new IllegalArgumentException("게시글을 찾을 수 없습니다.")
);

// comment라는 entity를 생성할거야
// requestDto, post라는 정보를 같이 넣어줄 테니까, 이것을 이용해서 comment를 생성해줘
Comment comment = new Comment(requestDto, post);

Comment savedComment = commentRepository.save(comment);
return savedComment;
}

/*public Optional<Post> updateComment(CommentRequestDto requestDto, Long id) {
}

public void deleteComment(CommentRequestDto requestDto, Long id) {
}*/
}
package com.sparta.jwt_submit_try4.controller;


import com.sparta.jwt_submit_try4.controller.dto.CommentRequestDto;
import com.sparta.jwt_submit_try4.entity.Comment;
import com.sparta.jwt_submit_try4.service.CommentService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RequiredArgsConstructor
@RestController
public class CommentController {
private final CommentService commentService;
//모든 글 읽어 오기
/*@GetMapping("/dev/comment")
public List<Comment> getAllpost(){return commentService.getAllpost();}*/

//댓글 쓰기
@PostMapping("/dev/comment/{id}")
// 사용자가 댓글을 저장하면
// front에서 게시글의 id와 댓글의 내용을 같이 보내줍니다. (postman, ARC)
// backend 에서는 @RequestBody annotation과 requestDto를 이용하여 front가 보내준 정보를 전달받습니다.
// 부족한점: 일단 entity 외부의 노출되지 않아야 합니다.
// return 할 때는 dto에 다시 정보를 전달해서 return을 합니다.
// responseDto를 새로 만들어서 보여줄 내용만 return합니다. (정석)
public Comment createComment(@RequestBody CommentRequestDto requestDto) {
Comment comment = commentService.createComment(requestDto);
return comment;
// 위 아래가 동일한 코드입니다.
//return commentService.createComment(requestDto);
}

// passwordEncoder라는 것을 비밀번호를 encoding 해줍니다.

/*//댓글 수정
@PutMapping("/dev/comment/{id}")
public Optional<Comment> updateComment(@RequestBody CommentRequestDto requestDto, @PathVariable Long id){
return commentService.updateComment(requestDto, id);}


//댓글 삭제
@DeleteMapping("/dev/comment/{id}")
public void deleteComment(@RequestBody CommentRequestDto requestDto, @PathVariable Long id) {
commentService.deleteComment(requestDto,id);
}*/
}
////////////
///////////
package com.sparta.jwt_submit_try4.entity;


import com.sparta.jwt_submit_try4.controller.dto.PostRequestDto;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

@NoArgsConstructor
@Setter
@Getter
@Entity
public class Post extends Timestamped{

@Id
@Column(name = "post_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@Column(nullable = false)
private String title;
@Column(nullable = true)
private String contents;

@Column(nullable = true)
private String nickname;

@ManyToOne
@JoinColumn(name="member_Id")
private Member member;

@OneToMany(mappedBy = "post")
List<Comment> comments = new ArrayList<>();


public Post(String contents, String title) {
this.contents = contents;
this.title = title;
}
public Post(PostRequestDto requestDto) {
this.contents = requestDto.getContents();
this.title = requestDto.getTitle();
}

public Post(PostRequestDto requestDto,Member member) {
this.contents = requestDto.getContents();
this.title = requestDto.getTitle();
this.nickname = member.getNickname();
}


public void update(PostRequestDto requestDto) {
this.contents = requestDto.getContents();
this.title = requestDto.getTitle();
}


}