일단 질문과 유저사이의 추천을 구현해보자.
추천을 누르면 +1 이된다.
@Getter
@Setter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Entity
public class QuestionReco {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne(fetch = FetchType.LAZY)
private SiteUser user;
@ManyToOne(fetch = FetchType.LAZY)
private Question question;
}
@Controller
@RequestMapping("/question/vote")
@RequiredArgsConstructor
@Slf4j
public class QuestionRecoController {
private final QuestionRecoService questionRecoService;
private final QuestionService questionService;
private final UserService userService;
@PreAuthorize("isAuthenticated()")
@GetMapping("/{id}")
public String questionVote(Principal principal, @PathVariable("id") Integer id) {
log.info("추천 시작");
Question question = questionService.getQuestion(id);
SiteUser user = userService.getUser(principal.getName());
QuestionReco Reco = questionRecoService.findReco(user, question);
if (Reco != null) {
questionRecoService.delete(Reco);
} else {
questionRecoService.insert(user, question);
}
log.info("추천 종료");
return String.format("redirect:/question/detail/%s", id);
}
}
@RequiredArgsConstructor
@Service
public class QuestionRecoService {
private final QuestionRecoRepository questionRecoRepository;
@Transactional
public void insert(SiteUser user, Question question){
QuestionReco questionReco = new QuestionReco();
questionReco.setUser(user);
questionReco.setQuestion(question);
questionRecoRepository.save(questionReco);
}
@Transactional
public void delete(QuestionReco questionReco){
questionRecoRepository.delete(questionReco);
}
public QuestionReco findReco(SiteUser user, Question question){
Optional<QuestionReco> checking = questionRecoRepository.findByUserIdAndQuestionId(user.getId(), question.getId());
if(checking.isPresent()){
return checking.get();
}
return null;
}
}