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

[렉스] 2단계: 연관 관계 매핑 #43

Open
wants to merge 9 commits into
base: seongwon97
Choose a base branch
from
2 changes: 2 additions & 0 deletions src/main/java/qna/Application.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

@EnableJpaAuditing
@SpringBootApplication
public class Application {

Expand Down
36 changes: 21 additions & 15 deletions src/main/java/qna/domain/Answer.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;

import qna.NotFoundException;
import qna.UnAuthorizedException;
Expand All @@ -18,9 +20,13 @@ public class Answer extends BaseEntity {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private Long writerId;
@ManyToOne
@JoinColumn(name = "writer_id")
private User writer;

private Long questionId;
@ManyToOne
@JoinColumn(name = "question_id")
private Question question;

@Lob
private String contents;
Expand All @@ -45,17 +51,17 @@ public Answer(Long id, User writer, Question question, String contents) {
throw new NotFoundException();
}

this.writerId = writer.getId();
this.questionId = question.getId();
this.writer = writer;
this.question = question;
this.contents = contents;
}

public boolean isOwner(User writer) {
return this.writerId.equals(writer.getId());
return this.writer.equals(writer);
}

public void toQuestion(Question question) {
this.questionId = question.getId();
this.question = question;
}

public Long getId() {
Expand All @@ -66,20 +72,20 @@ public void setId(Long id) {
this.id = id;
}

public Long getWriterId() {
return writerId;
public User getWriter() {
return writer;
}

public void setWriterId(Long writerId) {
this.writerId = writerId;
public void setWriter(User writer) {
this.writer = writer;
}

public Long getQuestion() {
return questionId;
public Question getQuestion() {
return question;
}

public void setQuestionId(Question question) {
this.questionId = question.getId();
this.question = question;
}

public String getContents() {
Expand All @@ -102,8 +108,8 @@ public void setDeleted(boolean deleted) {
public String toString() {
return "Answer{" +
"id=" + id +
", writerId=" + writerId +
", questionId=" + questionId +
", writer=" + writer +
", question=" + question +
", contents='" + contents + '\'' +
", deleted=" + deleted +
'}';
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/qna/domain/AnswerRepository.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

public interface AnswerRepository extends JpaRepository<Answer, Long> {

List<Answer> findByQuestionIdAndDeletedFalse(Long questionId);
List<Answer> findByQuestionAndDeletedFalse(Long questionId);

Choose a reason for hiding this comment

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

Suggested change
List<Answer> findByQuestionAndDeletedFalse(Long questionId);
List<Answer> findByQuestionIdAndDeletedFalse(Long questionId);

매개변수와 메서드명이 다르네요.

Copy link
Author

Choose a reason for hiding this comment

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

네오 아무리 수정을 해보려해도 findByQuestionIdAndDeletedFalse라는 이름으로 변경을 하면 오류가 발생하더라고요ㅠ 다른 크루들의 코드와 비교하여도 Answer 도메인의 필드명과 메서드 명이 같은데 오류를 가 발생하는 이유를 잘 모르겠습니다ㅠ


Optional<Answer> findByIdAndDeletedFalse(Long id);
}
13 changes: 9 additions & 4 deletions src/main/java/qna/domain/BaseEntity.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,20 @@
import java.time.LocalDateTime;

import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;

import org.hibernate.annotations.CreationTimestamp;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

@EntityListeners(AuditingEntityListener.class)
@MappedSuperclass
public class BaseEntity {

@CreationTimestamp
@CreatedDate
@Column(nullable = false)
private LocalDateTime createdAt;

@DateTimeFormat
private LocalDateTime updatedAt;

public LocalDateTime getCreatedAt() {
Expand All @@ -25,4 +26,8 @@ public LocalDateTime getCreatedAt() {
public LocalDateTime getUpdatedAt() {
return updatedAt;
}

public void updateTimeOfUpdated() {
this.updatedAt = LocalDateTime.now();
}
}
28 changes: 19 additions & 9 deletions src/main/java/qna/domain/DeleteHistory.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,20 @@
import java.util.Objects;

import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

import org.hibernate.annotations.CreationTimestamp;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

@EntityListeners(AuditingEntityListener.class)
@Entity
public class DeleteHistory {

Expand All @@ -21,19 +27,23 @@ public class DeleteHistory {

@Enumerated(value = EnumType.STRING)
private ContentType contentType;

private Long contentId;
private Long deletedById;

@CreationTimestamp
@ManyToOne
@JoinColumn(name = "deleted_by_id")
private User deletedBy;

@CreatedDate
private LocalDateTime createDate;

protected DeleteHistory() {
}

public DeleteHistory(ContentType contentType, Long contentId, Long deletedById) {
public DeleteHistory(ContentType contentType, Long contentId, User deletedBy) {
this.contentType = contentType;
this.contentId = contentId;
this.deletedById = deletedById;
this.deletedBy = deletedBy;
}

public Long getId() {
Expand All @@ -48,8 +58,8 @@ public Long getContentId() {
return contentId;
}

public Long getDeletedById() {
return deletedById;
public User getDeletedBy() {
return deletedBy;
}

public LocalDateTime getCreateDate() {
Expand All @@ -68,12 +78,12 @@ public boolean equals(Object o) {
return Objects.equals(id, that.id) &&
contentType == that.contentType &&
Objects.equals(contentId, that.contentId) &&
Objects.equals(deletedById, that.deletedById);
Objects.equals(deletedBy, that.deletedBy);
}

@Override
public int hashCode() {
return Objects.hash(id, contentType, contentId, deletedById);
return Objects.hash(id, contentType, contentId, deletedBy);
}

@Override
Expand All @@ -82,7 +92,7 @@ public String toString() {
"id=" + id +
", contentType=" + contentType +
", contentId=" + contentId +
", deletedById=" + deletedById +
", deletedBy=" + deletedBy +
", createDate=" + createDate +
'}';
}
Expand Down
30 changes: 15 additions & 15 deletions src/main/java/qna/domain/Question.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;

@Entity
public class Question extends BaseEntity {
Expand All @@ -20,30 +22,28 @@ public class Question extends BaseEntity {
@Lob
private String contents;

private Long writerId;
@ManyToOne
@JoinColumn(name = "writer_id")
private User writer;

private boolean deleted;

protected Question() {
}

public Question(String title, String contents) {
this(null, title, contents);
public Question(String title, String contents, User writer) {
this(null, title, contents, writer);
}

public Question(Long id, String title, String contents) {
public Question(Long id, String title, String contents, User writer) {
this.id = id;
this.title = title;
this.contents = contents;
}

public Question writeBy(User writer) {
this.writerId = writer.getId();
return this;
this.writer = writer;
}

public boolean isOwner(User writer) {
return this.writerId.equals(writer.getId());
return this.writer.equals(writer);
}

public void addAnswer(Answer answer) {
Expand Down Expand Up @@ -74,12 +74,12 @@ public void setContents(String contents) {
this.contents = contents;
}

public Long getWriterId() {
return writerId;
public User getWriter() {
return writer;
}

public void setWriterId(Long writerId) {
this.writerId = writerId;
public void setWriterId(User writer) {
this.writer = writer;
}

public boolean isDeleted() {
Expand All @@ -96,7 +96,7 @@ public String toString() {
"id=" + id +
", title='" + title + '\'' +
", contents='" + contents + '\'' +
", writerId=" + writerId +
", writer=" + writer +
", deleted=" + deleted +
'}';
}
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/qna/domain/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public class User extends BaseEntity {
@Column(length = 50)
private String email;

public User() {
protected User() {
}

public User(String userId, String password, String name, String email) {
Expand Down
21 changes: 15 additions & 6 deletions src/main/java/qna/service/QnaService.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@
public class QnaService {
private static final Logger log = LoggerFactory.getLogger(QnaService.class);

private QuestionRepository questionRepository;
private AnswerRepository answerRepository;
private DeleteHistoryService deleteHistoryService;
private final QuestionRepository questionRepository;
private final AnswerRepository answerRepository;
private final DeleteHistoryService deleteHistoryService;

public QnaService(QuestionRepository questionRepository, AnswerRepository answerRepository,
DeleteHistoryService deleteHistoryService) {
Expand All @@ -39,14 +39,23 @@ public Question findQuestionById(Long id) {
.orElseThrow(NotFoundException::new);
}

@Transactional
public void updateQuestionContent(Long id, String contents) {
Question question = questionRepository.findByIdAndDeletedFalse(id)
.orElseThrow(NotFoundException::new);
question.setContents(contents);
question.updateTimeOfUpdated();
}

@Transactional
public void deleteQuestion(User loginUser, Long questionId) throws CannotDeleteException {
Question question = findQuestionById(questionId);
if (!question.isOwner(loginUser)) {
throw new CannotDeleteException("질문을 삭제할 권한이 없습니다.");
}

List<Answer> answers = answerRepository.findByQuestionIdAndDeletedFalse(questionId);
List<Answer> answers = answerRepository.findByQuestionAndDeletedFalse(questionId);

for (Answer answer : answers) {
if (!answer.isOwner(loginUser)) {
throw new CannotDeleteException("다른 사람이 쓴 답변이 있어 삭제할 수 없습니다.");
Expand All @@ -55,10 +64,10 @@ public void deleteQuestion(User loginUser, Long questionId) throws CannotDeleteE

List<DeleteHistory> deleteHistories = new ArrayList<>();
question.setDeleted(true);
deleteHistories.add(new DeleteHistory(ContentType.QUESTION, questionId, question.getWriterId()));
deleteHistories.add(new DeleteHistory(ContentType.QUESTION, questionId, question.getWriter()));
for (Answer answer : answers) {
answer.setDeleted(true);
deleteHistories.add(new DeleteHistory(ContentType.ANSWER, answer.getId(), answer.getWriterId()));
deleteHistories.add(new DeleteHistory(ContentType.ANSWER, answer.getId(), answer.getWriter()));
}
deleteHistoryService.saveAll(deleteHistories);
}
Expand Down
Loading