지금은 댓글이 잘 정렬돼서 나오고 있지만 댓글의 순서를 바꾸고 싶다면 @OrderBy 어노테이션을 사용하면 된다.
@JsonIgnoreProperties({"board"})
@OneToMany(mappedBy = "board", fetch = FetchType.EAGER)
@OrderBy("id asc") // id를 기준으로 오름차순, 안쓰면 default는 오름차순 (내림차순 정렬은 desc)
private List<Reply> replys;
detail.jsp
<!-- 댓글 작성 영역 -->
<div class="card">
<form>
<input type="hidden" id="boardId" value="${board.id }">
<div class="card-body">
<textarea id="reply-content" class="form-control" rows="2"></textarea>
</div>
<div class="card-footer">
<button type="button" id="btn-reply-save" class="btn btn-primary">등록</button>
</div>
</form>
</div>
board.js
let index = {
init: function() {
$("#btn-reply-save").on("click", () => {
this.replySave();
});
}
, replySave: function() {
let data = {
content: $("#reply-content").val()
};
let boardId = $("#boardId").val();
console.log(data);
$.ajax({
type: "POST",
url: `/api/board/${boardId}/reply`,
data: JSON.stringify(data),
contentType: "application/json; charset=UTF-8",
dataType: "json"
}).done(function(resp) {
alert("댓글 작성이 완료되었습니다.");
console.log(resp)
location.href = `/board/${boardId}`;
}).fail(function(error) {
alert(JSON.stringify(error));
});
}
}
index.init();
BoardApiController.java
@RestController
public class BoardApiController {
@Autowired
private BoardService boardService;
@PostMapping("/api/board/{boardId}/reply")
public ResponseDto<Integer> replySave(@PathVariable int boardId, @RequestBody Reply reply, @AuthenticationPrincipal PrincipalDetail principal) {
boardService.댓글쓰기(principal.getUser(), boardId, reply);
return new ResponseDto<Integer>(HttpStatus.OK.value(), 1);
}
}
BoardService.java
@Service
public class BoardService {
@Autowired
private BoardRepository boardRepository;
@Autowired
private ReplyRepository replyRepository;
@Transactional
public void 댓글쓰기(User user, int boardId, Reply requestReply) {
Board board = boardRepository.findById(boardId).orElseThrow(()->{
return new IllegalArgumentException("댓글 쓰기 실패 : 게시글 id를 찾을 수 없습니다.");
});
requestReply.setUser(user);
requestReply.setBoard(board);
replyRepository.save(requestReply);
}
}
테스트