Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8주차] cow mvc practice(BaekJaehyuk) #3

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.cow.cow_mvc_practice.comment.controller;

import com.cow.cow_mvc_practice.comment.controller.request.CreateCommentRequest;
import com.cow.cow_mvc_practice.comment.controller.response.CreateCommentResponse;
import com.cow.cow_mvc_practice.comment.service.CommentService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/comments")
@RequiredArgsConstructor
public class CommentController {
private final CommentService commentService;

@PostMapping()
BaekJaehyuk marked this conversation as resolved.
Show resolved Hide resolved
public CreateCommentResponse create(@RequestBody final CreateCommentRequest createCommentRequest) {
return commentService.createComment(createCommentRequest);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.cow.cow_mvc_practice.comment.controller.request;

import com.cow.cow_mvc_practice.comment.entity.Comment;
import lombok.Getter;

@Getter
public class CreateCommentRequest {
Long memberId;
Long postId;
String content;
BaekJaehyuk marked this conversation as resolved.
Show resolved Hide resolved

public Comment toEntity() {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

사용 안하시고 계신데 toEntity를 만들어 놓은 이유가 있을까요

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Hoya324 호야씨가 만들어 놓으셨어요

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

사용하셔야죠

return Comment.builder()
.content(content)
.build();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.cow.cow_mvc_practice.comment.controller.response;

import com.cow.cow_mvc_practice.comment.entity.Comment;
import com.cow.cow_mvc_practice.member.controller.dto.response.CreateMemberResponse;
import com.cow.cow_mvc_practice.member.entity.Member;
import lombok.Builder;
import lombok.Getter;

@Getter
public class CreateCommentResponse {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

댓글을 생성하는 response? 라는 생각이 들어서 프론트에게 Comment 생성에 대한 정보를 넘겨줘야하는가? 라는 생각이 들게 됩니다! 만약 Comment 생성한 후 정보를 반환하고 싶은거라면 CommentResponse 또는CreatedCommnetReponse 와 같은 클래스 명을 사용할거 같아요! 반환의 이유가 있는지 확인해보고 결정해주세요!

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

고민해 보겠습니다

private final Long id;
private final String content;

@Builder
public CreateCommentResponse(Long id, String content) {
BaekJaehyuk marked this conversation as resolved.
Show resolved Hide resolved
this.id = id;
this.content = content;
}

public static CreateCommentResponse from(final Comment comment) {
return CreateCommentResponse.builder()
.id(comment.getId())
.content(comment.getContent())
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.cow.cow_mvc_practice.comment.entity;

import com.cow.cow_mvc_practice.member.entity.Member;
import com.cow.cow_mvc_practice.post.entity.Post;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
BaekJaehyuk marked this conversation as resolved.
Show resolved Hide resolved
public class Comment {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "comment_id")
private Long id;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

id를 Long type으로 설정한 이유가 있나요?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

경험상 uuid를 사용하는게 좋을 때도 많아서 한번쯤 알아두면 좋을거 같습니다

uuid


private String content;

@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
BaekJaehyuk marked this conversation as resolved.
Show resolved Hide resolved
@JoinColumn(name = "post_id")
private Post post;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "member_id")
private Member member;

@Builder
private Comment(final Long id, final String content, final Post post, final Member member) {
this.id = id;
this.content = content;
this.post = post;
this.member = member;
}

public static Comment of(final String content, final Post post, final Member member) {
return Comment.builder()
.content(content)
.post(post)
.member(member)
.build();
}
}
BaekJaehyuk marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.cow.cow_mvc_practice.comment.repository;

import com.cow.cow_mvc_practice.comment.entity.Comment;
import org.springframework.data.jpa.repository.JpaRepository;

public interface CommentJPARepository extends JpaRepository<Comment, Long> {

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.cow.cow_mvc_practice.comment.service;

import com.cow.cow_mvc_practice.comment.controller.request.CreateCommentRequest;
import com.cow.cow_mvc_practice.comment.controller.response.CreateCommentResponse;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;

@Transactional
@Service
public interface CommentService {

CreateCommentResponse createComment(CreateCommentRequest createCommentRequest);

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.cow.cow_mvc_practice.comment.service;

import com.cow.cow_mvc_practice.comment.controller.request.CreateCommentRequest;
import com.cow.cow_mvc_practice.comment.controller.response.CreateCommentResponse;
BaekJaehyuk marked this conversation as resolved.
Show resolved Hide resolved
import com.cow.cow_mvc_practice.comment.entity.Comment;
import com.cow.cow_mvc_practice.comment.repository.CommentJPARepository;
import com.cow.cow_mvc_practice.member.entity.Member;
import com.cow.cow_mvc_practice.member.repository.MemberJPARepository;
import com.cow.cow_mvc_practice.post.entity.Post;
import com.cow.cow_mvc_practice.post.repository.PostJPARepository;
import jakarta.persistence.EntityNotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@RequiredArgsConstructor
@Service
@Transactional
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Transactional을 interface에도 달고 구현체에도 달게 되면 어떻게 될까요?

public class CommentServiceImpl implements CommentService{
private final CommentJPARepository commentRepository;
private final MemberJPARepository memberRepository;
private final PostJPARepository postRepository;

@Override
public CreateCommentResponse createComment(CreateCommentRequest createCommentRequest) {
Member member = findMemberById(createCommentRequest.getMemberId());
Post post = findPostById(createCommentRequest.getPostId());

Comment comment = Comment.of(createCommentRequest.getContent(), post, member);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

comment 객체를 만들때 연관관계 주입을 해주지 않고, 따로 편의 메소드로 작성하는 것이 좋을 것 같습니다.(post,member)

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CraeteCommentRequest의 toEntity메소드를 사용하여 인스턴스 생성하는 것이 더 좋아보입니다.

commentRepository.save(comment);
post.addComment(comment);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

연관관계 편의 메소드를 만들어 한번에 관리해주세요

return CreateCommentResponse.from(comment);
}

private Post findPostById(Long postId) {
BaekJaehyuk marked this conversation as resolved.
Show resolved Hide resolved
return postRepository.findById(postId)
.orElseThrow(() -> new EntityNotFoundException("[Error] 게시글를 찾을 수 없습니다."));
}

private Member findMemberById(Long memberId) {
return memberRepository.findById(memberId)
.orElseThrow(() -> new EntityNotFoundException("[Error] 회원를 찾을 수 없습니다."));
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.cow.cow_mvc_practice.member.controller;

import com.cow.cow_mvc_practice.member.controller.dto.request.UpdateMemberRequest;
import com.cow.cow_mvc_practice.member.controller.dto.response.CreateMemberResponse;
import java.util.List;

import org.springframework.web.bind.annotation.GetMapping;
Expand All @@ -10,9 +12,7 @@
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.cow.cow_mvc_practice.member.controller.dto.request.MemberRequest;
import com.cow.cow_mvc_practice.member.controller.dto.response.MemberResponse;
import com.cow.cow_mvc_practice.member.entity.Member;
import com.cow.cow_mvc_practice.member.controller.dto.request.CreateMemberRequest;
import com.cow.cow_mvc_practice.member.service.MemberService;

import lombok.RequiredArgsConstructor;
Expand All @@ -24,39 +24,29 @@ public class MemberController {

private final MemberService memberService;

/* 기본 */
// @PostMapping("/new")
// public String create(@RequestBody final MemberRequest memberRequest) {
// memberService.join(memberRequest);
// return "회원저장 성공!";
// }
//
// @GetMapping("/{memberId}")
// public String findMember(@PathVariable final Long memberId) {
// Member member = memberService.findOne(memberId);
// return "member 아이디: " + member.getId() + ", member 이름: " + member.getName();
// }
//

/* MemberResponse dto 적용 */
@PostMapping("/new")
public MemberResponse create(@RequestBody final MemberRequest memberRequest) {
return memberService.join(memberRequest);
public CreateMemberResponse create(@RequestBody final CreateMemberRequest createMemberRequest) {
return memberService.join(createMemberRequest);
}

@GetMapping("/{memberId}")
public MemberResponse findMember(@PathVariable final Long memberId) {
public CreateMemberResponse findMember(@PathVariable final Long memberId) {
return memberService.findOne(memberId);
}

@GetMapping()
public MemberResponse findMemberQuery(@RequestParam final Long memberId) {
public CreateMemberResponse findMemberQuery(@RequestParam final Long memberId) {
return memberService.findOne(memberId);
}

@GetMapping("all")
public List<MemberResponse> findMembers() {
@GetMapping("/all")
public List<CreateMemberResponse> findMembers() {
return memberService.findAll();
}

@PostMapping("/{memberId}")
public CreateMemberResponse editMember(@PathVariable final Long memberId, final UpdateMemberRequest updateMemberRequest) {
return memberService.update(memberId, updateMemberRequest);
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@
import lombok.Getter;

@Getter
public class MemberRequest {
String name;
public class CreateMemberRequest {
String name;

public Member toEntity() {
return Member.builder()
.name(name)
.build();
}
public Member toEntity() {
return Member.builder()
.name(name)
.build();
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
package com.cow.cow_mvc_practice.member.controller.dto.request;

import com.cow.cow_mvc_practice.member.entity.Member;
import lombok.Getter;

@Getter
public class UpdateMemberRequest {

private String name;

public Member toEntity() {
return Member.builder()
.name(name)
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,22 @@
import lombok.Getter;

@Getter
public class MemberResponse {
public class CreateMemberResponse {
private final Long id;
private final String name;

@Builder
private MemberResponse(final Long id, final String name) {
private CreateMemberResponse(final Long id, final String name) {
this.id = id;
this.name = name;
}

public static MemberResponse from(final Member member) {
return MemberResponse.builder()
public static CreateMemberResponse from(final Member member) {
return CreateMemberResponse.builder()
.id(member.getId())
.name(member.getName())
.build();
}


}
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.cow.cow_mvc_practice.member.entity;

import com.cow.cow_mvc_practice.comment.entity.Comment;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.cow.cow_mvc_practice.post.entity.Post;
Expand Down Expand Up @@ -50,4 +52,12 @@ public static Member of(Long id, String name) {
.name(name)
.build();
}

public void updateName(String name) {
this.name = name;
}

@OneToMany(mappedBy = "member")
private Collection<Comment> comment;

}
BaekJaehyuk marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,8 @@

@Repository
public class MemberRepositoryImpl implements MemberRepository {
/**
* 원래라면 HashMap이 아닌, concurrentHashMap이 적합함. HashMap은 멀티 쓰레드 환경에서 사용할 수 없기 때문.(동시성 이슈)
*/
private static Map<Long, Member> store = new HashMap<>();

private static Map<Long, Member> store = new HashMap<>();

@Override
public void save(Member member) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,22 +1,21 @@
package com.cow.cow_mvc_practice.member.service;

import java.util.ArrayList;
import com.cow.cow_mvc_practice.member.controller.dto.request.CreateMemberRequest;
import com.cow.cow_mvc_practice.member.controller.dto.request.UpdateMemberRequest;
import com.cow.cow_mvc_practice.member.controller.dto.response.CreateMemberResponse;
import java.util.List;

import com.cow.cow_mvc_practice.member.controller.dto.request.MemberRequest;
import com.cow.cow_mvc_practice.member.controller.dto.response.MemberResponse;
import com.cow.cow_mvc_practice.member.entity.Member;

public interface MemberService {

/* 기본 */
// void join(MemberRequest memberRequest);
// void join(CreateMemberRequest memberRequest);
// Member findOne(Long memberId);


/* MemberResponse dto 적용 */
MemberResponse findOne(Long memberId);
MemberResponse join(MemberRequest memberRequest);
List<MemberResponse> findAll();
/* CreateMemberResponse dto 적용 */
CreateMemberResponse findOne(Long memberId);
CreateMemberResponse join(CreateMemberRequest memberRequest);
List<CreateMemberResponse> findAll();
CreateMemberResponse update(Long memberId, UpdateMemberRequest updateMemberRequest);
}

Loading