인프런 커뮤니티 질문&답변

유승현님의 프로필 이미지

작성한 질문수

실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발

상품 엔티티 개발(비즈니스 로직 추가)

테이블 설계 관련 질문

21.09.02 00:28 작성

·

259

0

프론트 엔드에서 전체 category를 조회해서, 화면에 카테고리를 선택할수 있도록 출력해주는 화면이 있고

유저가 게시글을 등록한다고 한다면

---

1. 아래와 같이 Category 테이블에 모든 카테고리를 저장해 (init),

2. 이 리스트를 전달해주고, (미리 카테고리들은 정해져 있다고 할때, 추가도 할수 있겠지만)

3. user가 게시글을 등록할때 client가 입력한 category를 category table에서 찾아오고

4. 그 값을 기반으로 post와 postCategory에 저장해주는 방식이 되어야 하는거 같은데 

(강의들중 어디에서 질문하는게 좋을지 약간 애매해서 여기에 글 올립니다.)

------

이렇게 하는 방식이 맞을까요? 뭔가 동작 하게끔 할수 는 있는데 올바른 방법같지 않아서 영한님 다른강의들도 들어보면서 같이 몇일째 고민중인데 찜찜하고 명확하게 확신이 안섭니다.

카테고리 목록은 initService를 하나 만들어서 미리 저장해두었습니다. (강의에서 하신 initDb처럼)

답변주시면 감사드리겠습니다.

몇일째 해결이 안되요 ㅠㅠ

post테이블의 CATEGORY_TAG는 삭제 예정입니다

public class Post {

@Id @GeneratedValue
@Column(name = "post_id")
private Long id;

private String title;

@Lob
private String desc;

private int price;

@Enumerated(EnumType.STRING)
private Status status;

@ManyToOne
@JoinColumn(name = "account_id")
private Account seller;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "post_category_id")
private PostCategory postCategory;

// old
@Enumerated(EnumType.STRING)
private CategoryTag categoryTag;
/*@OneToOne
@JoinColumn(name = "category_id")
private Category category;*/

public Post(String title, Account seller){
this.title = title;
this.seller = seller;
status = Status.NEW;
}

// old
public Post(String title, String desc, int price, CategoryTag categoryTag, Account seller){
this.title = title;
this.desc = desc;
this.price = price;
// @Converter
this.categoryTag = categoryTag;
this.seller = seller;
status = Status.NEW;
seller.addPost(this);
}

public Post(String title, String desc, int price, Account seller){
this.title = title;
this.desc = desc;
this.price = price;
// @Converter
this.postCategory = postCategory;
this.seller = seller;
status = Status.NEW;
seller.addPost(this);
}

//== 연관관계 메서드 ==/
public void setSeller(Account seller) {
this.seller = seller;
seller.addPost(this);
}

//== 바즈니스 로직 ==//
// old
public static Post post(String title, Account seller, CategoryTag categoryTag){
Post post = new Post(title, seller);
post.setCategoryTag(categoryTag);
return post;
}

public void setPostCategory(PostCategory postCategory){
this.postCategory = postCategory;
postCategory.setPost(this);
}

}

@Entity
@Setter
@Getter
public class PostCategory {
@Id @GeneratedValue
@Column(name = "post_category_id")
private Long id;

@OneToOne(mappedBy = "postCategory")
private Post post;

@OneToOne
@JoinColumn(name = "category_id")
private Category category;
}

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

@Id @GeneratedValue
@Column(name= "category_id")
private Long id;

@Enumerated(EnumType.STRING)
@Column(unique = true)
private CategoryTag categoryTag;

public Category(CategoryTag categoryTag){
this.categoryTag = categoryTag;
}

}

@PostMapping("/new2")
public PostResponseDto postV2(@RequestBody PostRequestDto postRequestDto, @ApiIgnore HttpSession session){

Account account = getSessionCheckedAccount(session);

Post post = new Post(postRequestDto.getTitle(), postRequestDto.getDesc(),
postRequestDto.getPrice(), account);

Category category = categoryJpaRepository.findByCategoryTag(postRequestDto.getCategoryTag());

PostCategory postCategory = new PostCategory();
postCategory.setCategory(category);
post.setPostCategory(postCategory);


Long postId = postService.post(post);

return new PostResponseDto(postId);
}

답변 1

0

김영한님의 프로필 이미지
김영한
지식공유자

2021. 09. 02. 22:03

안녕하세요. 유승현님^^

잘 구현하셨습니다. 그리고 PostCategory는 없어도 될 것 같아요. Post에 합쳐버리세요.

그리고 죄송하지만 앞으로는 질문 안내에 있는 것 처럼 학습에 관련된 질문을 올려주시길 부탁드립니다.

저도 마음으로는 도움을 드리고 싶지만, 하루에도 수 많은 분들이 질문을 올려주십니다. 그래서 학습과 관련된 질문에 초점을 맞추는 것이 맞다 생각합니다. 다시한번 이해를 부탁드립니다.

감사합니다.

유승현님의 프로필 이미지
유승현
질문자

2021. 09. 03. 06:36

넵 알겠습니다. 덕분에 도움많이 됐습니다.

항상 친절히 답변해주셔서 너무 감사드립니다.

김영한님의 프로필 이미지
김영한
지식공유자

2021. 09. 03. 21:47

네 승현님 응원합니다^^!