Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,12 @@ protected CommonResult RefreshTokenException(HttpServletRequest request, Excepti
return responseService.getFailResultWithMsg("잘못된 Refresh 토큰입니다. 다시 입력해주세요.");
}


@ExceptionHandler(CSchoolNotFoundException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
protected CommonResult SchoolNotFoundException(HttpServletRequest request, Exception e) {
return responseService.getFailResultWithMsg("해당 학교가 존재하지 않거나 잘못된 학교입니다.");
}
@ExceptionHandler(CCategoryExistedException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
protected CommonResult CategoryExistedException(HttpServletRequest request, Exception e) {
Expand Down Expand Up @@ -145,5 +151,6 @@ protected CommonResult BattleExistedException(HttpServletRequest request, Except
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
protected CommonResult BattleNotFoundException(HttpServletRequest request, Exception e) {
return responseService.getFailResultWithMsg("해당 경기가 존재하지 않습니다.");

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package org.battles.battles.exception.exception;

public class CSchoolNotFoundException extends RuntimeException{

public CSchoolNotFoundException(String msg, Throwable t) {
super(msg, t);
}

public CSchoolNotFoundException(String msg) {
super(msg);
}

public CSchoolNotFoundException() {
super();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package org.battles.battles.post.Dto;

import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.battles.battles.common.Status;
import org.battles.battles.post.Post;
import org.battles.battles.post.PostType;
import org.battles.battles.school.School;
import org.battles.battles.user.User;

import java.util.Optional;

@Getter
@NoArgsConstructor
public class PostsSaveRequestDto {
private String title;
private String content;



@Builder
public PostsSaveRequestDto(String title, String content, PostType postType, Status status) {
this.title = title;
this.content = content;

}

public Post toEntity(PostType postType, User user) {
return Post.builder()
.title(title)
.content(content)
.status(Status.ACTIVE)
.postType(postType)
.user(user)
.build();
}

public Post toEntity2(PostType postType, School school, User user) {
return Post.builder()
.title(title)
.content(content)
.status(Status.ACTIVE)
.postType(postType)
.school(school)
.user(user)
.build();
}
}
21 changes: 12 additions & 9 deletions src/main/java/org/battles/battles/post/Post.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import lombok.NoArgsConstructor;
import org.battles.battles.common.Status;
import org.battles.battles.common.TimeStamped;
import org.battles.battles.school.School;
import org.battles.battles.user.User;

import javax.persistence.*;

Expand All @@ -15,20 +17,21 @@
@AllArgsConstructor
@Entity
@Table(name = "Post_Table")

public class Post extends TimeStamped {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long postId;

// fix me = fk mapping 필요
@Column(nullable = false)
private Long userId;
// fix me = fk mapping 필요
@ManyToOne
@JoinColumn(name = "userId", nullable = true)
private User user;

// fix me = fk mapping 필요
@Column(nullable = true)
private Long schoolId;
@ManyToOne
@JoinColumn(name = "schoolId", nullable = true)
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

매핑 잘 하셨는데 지금 언뜻 서치해보니까 fk null이면 에러가 난다는.... 설계를 다시 해봐야겠네요 ㅠㅠㅠ

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

fk null 허용되지 않나요? JPA라서 그런가요??

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

jpa라서 그런건 아니고.. 아 fk가 pk 동시일때 null허용은 안되는구나 원래 db상으로는... 음 고민이되네요 null이 좋은 방식은 아닌 것 같긴 해요 ㅠㅠ 고민고민

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

음 더 알아보겠습니다. @yejipractice

Copy link
Copy Markdown
Member Author

@imchanyang imchanyang Aug 28, 2022

Choose a reason for hiding this comment

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

  1. Post의 schooId 컬럼에 값을 전부(전체/학교) 다 넣어준다.
  2. Post의 schoolId 컬럼을 빼고 필요할 때 마다 User를 통해 조회한다.

정도 고민이 있는 것 같습니다.

개발하고 있는데 schoolID가 NULL이 되면 코드가 많아지기도 했습니다..

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

  1. 둘의 테이블을 나눠버린다?

private School school;

@Column(nullable = false)
private String title;
Expand All @@ -45,9 +48,9 @@ public class Post extends TimeStamped {
private Status status;

@Builder
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

빌더는 빼주세요~!

public Post(Long userId, Long schoolId, String title, String content, PostType postType, Status status) {
this.userId = userId;
this.schoolId = schoolId;
public Post(User user, School school, String title, String content, PostType postType, Status status) {
this.user = user;
this.school = school;
this.title = title;
this.content = content;
this.postType = postType;
Expand Down
44 changes: 44 additions & 0 deletions src/main/java/org/battles/battles/post/PostController.java
Original file line number Diff line number Diff line change
@@ -1,4 +1,48 @@
package org.battles.battles.post;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.battles.battles.post.Dto.PostsSaveRequestDto;
import org.battles.battles.response.ResponseService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.core.Authentication;

@Api(tags = {"6. 게시판 컨트롤러"})
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/post")
@Slf4j
public class PostController {
//
private final ResponseService responseService;

private final PostService postService;
@ApiImplicitParams({
@ApiImplicitParam(name = "AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
})
@ApiOperation(value = "전체 게시글 작성", notes = "회원정보와 제목, 내을 입력하여 전체 게시글을 작성한다.")
@PostMapping("/all")
public Long saveAll(@RequestBody PostsSaveRequestDto requestDto) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String email = authentication.getName();

return postService.save(email, requestDto);
}

@ApiImplicitParams({
@ApiImplicitParam(name = "AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
})
@ApiOperation(value = "학교 게시글 작성", notes = "회원정보와 제목, 내을 입력하여 학교 게시글을 작성한다.")
@PostMapping("/{schoolId}")
public Long saveSchool(@RequestBody PostsSaveRequestDto requestDto, @PathVariable Long schoolId) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String email = authentication.getName();

return postService.saveSchool(email, requestDto, schoolId);
}
}
47 changes: 47 additions & 0 deletions src/main/java/org/battles/battles/post/PostService.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,52 @@
package org.battles.battles.post;

import lombok.RequiredArgsConstructor;
import org.battles.battles.exception.exception.CSchoolNotFoundException;
import org.battles.battles.exception.exception.CUserNotFoundException;
import org.battles.battles.post.Dto.PostsSaveRequestDto;
import org.battles.battles.school.School;
import org.battles.battles.school.SchoolRepository;
import org.battles.battles.user.User;
import org.battles.battles.user.UserService;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class PostService {
private final PostRepository postRepository;

private final SchoolRepository schoolRepository;

private final UserService userService;

@Transactional
public Long save(String email, PostsSaveRequestDto requestDto) {
PostType postType;
postType = PostType.ENTIRE;

Optional<User> user = userService.getUserByEmail(email);
if(user.isEmpty()) {
throw new CUserNotFoundException();
}
return postRepository.save(requestDto.toEntity(postType, user.get())).getPostId();
}

@Transactional
public Long saveSchool(String email, PostsSaveRequestDto requestDto, Long schoolId) {
PostType postType;
postType = PostType.SCHOOL;

Optional<User> user = userService.getUserByEmail(email);
if(user.isEmpty()) {
throw new CUserNotFoundException();
}

Optional<School> school = schoolRepository.findById(schoolId);
if(school.isEmpty()) {
throw new CSchoolNotFoundException();
}
return postRepository.save(requestDto.toEntity2(postType, school.get(), user.get())).getPostId();
}
}
13 changes: 7 additions & 6 deletions src/main/java/org/battles/battles/school/School.java
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
package org.battles.battles.school;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.*;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.battles.battles.common.TimeStamped;
import org.battles.battles.post.Post;

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

@Getter
@Setter
Expand All @@ -32,4 +32,5 @@ public class School extends TimeStamped {

@Column(nullable = true)
private String schoolDomainName;

}