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

[14주차] 심규창 학습 PR 제출합니다. #1

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ repositories {
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-validation'
compileOnly 'org.projectlombok:lombok'
implementation 'mysql:mysql-connector-java'
runtimeOnly 'com.mysql:mysql-connector-j'
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.example.jpa.board.controller;

import com.example.jpa.board.dto.request.BoardUpdateRequest;
import com.example.jpa.board.dto.request.BoardCreateRequest;
import com.example.jpa.board.dto.response.BoardResponse;
import com.example.jpa.board.service.BoardService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
Copy link
Member

Choose a reason for hiding this comment

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

@RestContoller@Controller 알아보기!

@RequestMapping("api/boards")
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
@RequestMapping("api/boards")
@RequestMapping("/api/boards")

@RequiredArgsConstructor
public class BoardController {

private final BoardService boardService;

@PostMapping
public ResponseEntity<Void> createBoard(@RequestBody BoardCreateRequest boardCreateRequest) {
boardService.createBoard(boardCreateRequest);
return ResponseEntity.ok().build();
}

@GetMapping("/{id}")
public ResponseEntity<BoardResponse> retrieveBoardById(@PathVariable("id") Long id) {
BoardResponse boardresponse = boardService.retrieveBoardById(id);
return ResponseEntity.ok(boardresponse);
}

@GetMapping
public ResponseEntity<List<BoardResponse>> retrieveBoards() {
return ResponseEntity.ok(boardService.retrieveBoards());
}

@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteBoard(@PathVariable("id") Long id) {
boardService.deleteBoard(id);
return ResponseEntity.ok().build();
}

@PutMapping
public ResponseEntity<Void> updateBoard(@RequestBody BoardUpdateRequest boardUpdateRequest) {
boardService.updateBoard(boardUpdateRequest);
return ResponseEntity.ok().build();
}

}
49 changes: 49 additions & 0 deletions src/main/java/com/example/jpa/board/domain/Board.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.example.jpa.board.domain;

import com.example.jpa.board.dto.request.BoardUpdateRequest;
import com.example.jpa.member.domain.Member;
import com.example.jpa.reply.domain.Reply;
import jakarta.persistence.*;
import lombok.*;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Board {

// @Builder - 생성자를 통해 반환하기 때문에 필요 X
// @Setter - update 메서드를 통해 수정하기 때문에 필요 X

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

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

@OneToMany(mappedBy = "board", orphanRemoval = true)
private List<Reply> replyList = new ArrayList<>();
Comment on lines +29 to +30
Copy link
Member

Choose a reason for hiding this comment

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

List<Reply>를 가지고 있는게 좋은 지 고민해보기


private String title;
private String content;
private LocalDate date;
Copy link
Member

Choose a reason for hiding this comment

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

createdDate, UpdatedDate같은 명확한 네이밍 가져가기

Suggested change
private LocalDate date;
private LocalDate createdDate;


@Builder
public Board(Member writer, String title, String content, LocalDate date) {
this.writer = writer;
this.title = title;
this.content = content;
this.date = date;
}

public void update(BoardUpdateRequest boardUpdateRequest) {
this.title = boardUpdateRequest.getTitle();
this.content = boardUpdateRequest.getContent();
this.date = LocalDate.now();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.example.jpa.board.dto.request;

import com.example.jpa.board.domain.Board;
import com.example.jpa.member.domain.Member;
import jakarta.validation.constraints.NotBlank;
import lombok.Getter;

import java.time.LocalDate;

@Getter
public class BoardCreateRequest {
Copy link
Member

Choose a reason for hiding this comment

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

record 활용해보기


@NotBlank
private Long id;

@NotBlank
private String title;

@NotBlank
private String content;

public Board toEntity(Member writer) {
return Board.builder()
.writer(writer)
.title(this.title)
.content(this.content)
.date(LocalDate.now())
.build();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.example.jpa.board.dto.request;

import jakarta.validation.constraints.NotBlank;
import lombok.Getter;

@Getter
public class BoardUpdateRequest {

@NotBlank
private Long id;

@NotBlank
private String title;

@NotBlank
private String content;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.example.jpa.board.dto.response;

import com.example.jpa.board.domain.Board;
import lombok.Getter;

import java.time.LocalDate;

@Getter
public class BoardResponse {

private Long id;
private String memberName;

private String title;
private String content;
private LocalDate date;

public BoardResponse(Long id, String memberName, String title, String content, LocalDate date) {
this.id = id;
this.memberName = memberName;
this.title = title;
this.content = content;
this.date = date;
}

public static BoardResponse from(Board board) {
return new BoardResponse(board.getId(), board.getWriter().getName(), board.getTitle(), board.getContent(), board.getDate());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.example.jpa.board.repository;

import com.example.jpa.board.domain.Board;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface BoardRepository extends JpaRepository<Board, Long> {

}
57 changes: 57 additions & 0 deletions src/main/java/com/example/jpa/board/service/BoardService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package com.example.jpa.board.service;

import com.example.jpa.board.domain.Board;
import com.example.jpa.board.dto.request.BoardCreateRequest;
import com.example.jpa.board.dto.request.BoardUpdateRequest;
import com.example.jpa.board.dto.response.BoardResponse;
import com.example.jpa.board.repository.BoardRepository;
import com.example.jpa.member.domain.Member;
import com.example.jpa.member.service.MemberService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class BoardService {

private final BoardRepository boardRepository;
private final MemberService memberService;

@Transactional
public void createBoard(BoardCreateRequest boardCreateRequest) {
Member targetMember = memberService.checkExist(boardCreateRequest.getId());
boardRepository.save(boardCreateRequest.toEntity(targetMember));
}

public BoardResponse retrieveBoardById(Long id) {
return BoardResponse.from(checkExist(id));
}

public List<BoardResponse> retrieveBoards() {
return boardRepository.findAll().stream().map(BoardResponse::from).collect(Collectors.toList());
}

@Transactional
public void deleteBoard(Long id) {
boardRepository.delete(checkExist(id));
}

@Transactional
public void updateBoard(BoardUpdateRequest boardUpdateRequest) {
Board targetBoard = checkExist(boardUpdateRequest.getId());
targetBoard.update(boardUpdateRequest);
}

public Board checkExist(Long id) {
Board targetBoard = boardRepository.findById(id)
.orElseThrow(() -> new NoSuchElementException("게시판이 존재하지 않습니다."));
return targetBoard;
}
Comment on lines +51 to +55
Copy link
Member

Choose a reason for hiding this comment

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

chekcExist라면 boolean 응답을 기대할 것 같음. get이나 fetch로 쓰는게 적절할듯

Copy link
Member

@stophwan stophwan Jan 3, 2024

Choose a reason for hiding this comment

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

도진님 말씀 굉장히 동감합니다. 메서드가 직관적이지 않은것 가타용.


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.example.jpa.exception;

public class DuplicateMemberException extends Exception{

public DuplicateMemberException(String message) {
super(message);
}

}
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
package com.example.jpa.member.controller;

import com.example.jpa.member.dto.request.MemberCreateRequest;
import com.example.jpa.member.dto.request.MemberUpdateRequest;
import com.example.jpa.member.dto.response.MemberResponse;
import com.example.jpa.member.service.MemberService;
import lombok.RequiredArgsConstructor;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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;
import org.springframework.web.bind.annotation.*;
Copy link
Member

Choose a reason for hiding this comment

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

전체 import 지양하기


import java.util.List;

@RestController
@RequestMapping("api/members")
Expand All @@ -22,9 +20,7 @@ public class MemberController {

@PostMapping
public ResponseEntity<Void> create(@RequestBody MemberCreateRequest memberCreateRequest) {

memberService.create(memberCreateRequest);

return ResponseEntity.ok().build();
}

Expand All @@ -35,4 +31,21 @@ public ResponseEntity<MemberResponse> findOne(@PathVariable("id") Long id) {

return ResponseEntity.ok(memberResponse);
}

@GetMapping()
public ResponseEntity<List<MemberResponse>> retrieveMembers() {
return ResponseEntity.ok(memberService.retrieveMembers());
}

@PutMapping()
public ResponseEntity<Void> updateMember(@RequestBody MemberUpdateRequest memberUpdateRequest) {
memberService.updateMember(memberUpdateRequest);
return ResponseEntity.ok().build();
}

@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteMember(@PathVariable("id") Long id) {
memberService.deleteMember(id);
return ResponseEntity.ok().build();
}
}
42 changes: 31 additions & 11 deletions src/main/java/com/example/jpa/member/domain/Member.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
package com.example.jpa.member.domain;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import com.example.jpa.board.domain.Board;
import com.example.jpa.exception.DuplicateMemberException;
import com.example.jpa.member.dto.request.MemberUpdateRequest;
import com.example.jpa.reply.domain.Reply;
import jakarta.persistence.*;
import lombok.*;

import java.util.ArrayList;
import java.util.List;

@Entity
@Getter
Expand All @@ -16,16 +17,35 @@ public class Member {

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

private String name;
private int age;
private String phoneNumber;

@OneToMany(mappedBy = "writer", orphanRemoval = true)
private List<Board> boardList = new ArrayList<>();

@OneToMany(mappedBy = "member", orphanRemoval = true)
private List<Reply> replyList = new ArrayList<>();

@Builder
public Member(String name) {
public Member(Long id, String name, int age, String phoneNumber) {
this.name = name;
this.age = age;
this.phoneNumber = phoneNumber;
}

void update(String name) {
this.name = name;
public void update(MemberUpdateRequest memberUpdateRequest) {
this.name = memberUpdateRequest.getName();
this.age = memberUpdateRequest.getAge();
this.phoneNumber = memberUpdateRequest.getPhoneNumber();
}

public void hasSamePhoneNumber(String phoneNumber) throws DuplicateMemberException {
if(this.phoneNumber.equals(phoneNumber)) {
throw new DuplicateMemberException("이미 가입한 사용자입니다.");
}
}
}
Loading