2022-12-22 20:16:33.920 WARN 11872 --- [nio-8080-exec-3] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [javax.validation.ConstraintViolationException: Validation failed for classes [com.example.practice.entity.User] during persist time for groups [javax.validation.groups.Default, ]<EOL>List of constraint violations:[<EOL>?ConstraintViolationImpl{interpolatedMessage='아이디는 최소 4자 최대 10자 입니다. 소문자 숫자만 가능, 특수문자 사용 불가', propertyPath=username, rootBeanClass=class com.example.practice.entity.User, messageTemplate='아이디는 최소 4자 최대 10자 입니다. 소문자 숫자만 가능, 특수문자 사용 불가'}<EOL>]]
문제
@Valid ->Pattern 정규표현식 익셉션 처리시 포스트맨에서 지저분하게나옴
해결 및 알게된 것
Exception은 오류코드를 보면 어떤 오류인지 나온다. 그것을 핸들링해주면된다. ex) ConstraintViolationException
시도해본것
MethodArgumentNotValidException 해봤으나 500에러 발생
Exception 해봤으나 당연히 500에러 발생
문제
서비스 부분에 인증/인가부분을 같이 넣어둠. 작동은 잘 되나 코드가 더러움.
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false)
private String title;
@Column(nullable = false)
private String content;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private User user;
@OneToMany(mappedBy = "post", cascade = CascadeType.REMOVE) // 게시글 삭제시 댓글삭제도 같이되어야힘.
@OrderBy("id desc") //id기준으로 댓글 정렬
private List<Comment> comments = new ArrayList<>();
public Post(PostRequest postDTO, User user) {
this.title = postDTO.getTitle();
this.content = postDTO.getContent();
this.user = user;
}
해결 및 알게된 것
컨트롤러 부분에 인증/인가를 넣어주고 필요한 객체를 넘겨주는 식으로 처리.
또 다른 생각나는 문제 -> 객체를 넘기는 것은 좋지 않고 DTO를 이용하여 처리하여야 하나 성공하지 못함.
시도해본것
DTO를 만들어 넘길려고 하였으나, Entity부분에 User를 연관관계로 만들어 이 부분을 어떻게 처리해야 할지 모르겠음. 물론 간단하게 연관관계를 끊고 만들 수 있으나, 연관관계를 사용해서 한번 해보고 싶음.
문제
객체를 응답으로 넘겨줘서 무한루프 걸림.
public class PostViewResponse {
private Long id;
private String username;
private String title;
private String content;
private LocalDateTime createdAt;
private LocalDateTime modifiedAt;
//이전부분
private List<Comment> comments;
//수정부분
private List<CommentResponse> comments;
public PostViewResponse(Post post) {
List<CommentResponse> list = new ArrayList<>();
this.id = post.getId();
this.username = post.getUser().getUsername();
this.title = post.getTitle();
this.content = post.getContent();
this.createdAt = post.getCreatedAt();
this.modifiedAt = post.getModifiedAt();
//이전부분
this.comments = post.getComments();
//수정부분
for (Comment comment : post.getComments()) {
list.add(new CommentResponse(comment));
}
this.comments = list;
해결 및 알게된 것
@JsonIgnore을 ManyToOne에 설정하여 무한루프를 멈출 수 있음.
하지만 무한루프를 임의로 끊는 것이기 때문에 안좋다고 느껴짐
-> 수정 부분을 보면 해당 객체가 아닌 CommentReponse로 필요한 부분을 넘기므로, 무한루프가 끊어지게 된다. -> JsonIgnore사용 할 필요 없음.