질문 부분에 author를 넣어서 진행.
마찬가지로 답변을 적은 사람도 누군지 알수 있게 적기.
public class Question {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "question_id")
private Integer id;
@Column(length = 200)
private String subject;
@Column(columnDefinition = "TEXT")
private String content;
@ManyToOne(fetch = FetchType.LAZY)
private SiteUser author;
private LocalDateTime createDate;
@JsonIgnore
@OneToMany(mappedBy = "question",cascade = CascadeType.REMOVE)
private List<Answer> answerList = new ArrayList<>();
public Question(String subject, String content, LocalDateTime createDate) {
this.subject = subject;
this.content = content;
this.createDate = createDate;
}
}
public class Answer {
@Id
@GeneratedValue(strategy = IDENTITY)
private Integer id;
@Column(columnDefinition = "TEXT")
private String content;
@ManyToOne(fetch = FetchType.LAZY)
private SiteUser author;
private LocalDateTime createDate;
@ManyToOne(fetch = FetchType.LAZY)
private Question question;
}
public SiteUser getUser(String username) {
Optional<SiteUser> siteUser = userRepository.findByusername(username);
if (siteUser.isPresent()) {
return siteUser.get();
} else {
throw new DataNotFoundException("siteUser Not found");
}
}
로그아웃 상황에서 principal 객체가 붙어있는 메서드를 사용하게되면 당연하게도 principal 객체가 비어있기 때문에 500 에러를 내보내게된다.
@PreAuthorize("isAuthenticated()")
@PostMapping("/create")
public String questionCreate(@Valid QuestionForm questionForm,
BindingResult bindingResult, Principal principal) {
if (bindingResult.hasErrors()) {
return "question_form";
}
SiteUser siteUser = userService.getUser(principal.getName());
questionService.create(questionForm.getSubject(), questionForm.getContent(), siteUser);
return "redirect:/question/list";
}
SecurityConfig에 밑의 애너테이션을 추가해줘야한다.
@EnableMethodSecurity(prePostEnabled = true)