Spring으로 커뮤니티 기능 중 회원(member) 생성, 조회, 수정, 삭제 기능을 구현하기
ex) 멤버 조회
위의 예시처럼 4개 필드만 보고 싶은데, 조회 시 응답에 memberId
필드가 포함된다.
MemberResponseDto.java
코드@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class MemberResponseDto {
private Long memberId;
private String email;
private String nickname;
private String university;
private String studentId;
public MemberResponseDto(Long memberId, String email, String nickname, String university, String studentId){
this.memberId = memberId;
this.email = email;
this.nickname = nickname;
this.university = university;
this.studentId = studentId;
}
public static MemberResponseDto from(Member member){
return new MemberResponseDto(
member.getMemberId(),
member.getEmail(),
member.getNickname(),
member.getUniversity(),
member.getStudentId());
}
}
memberId
삭제가장 간단하다.
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class MemberResponseDto {
private String email;
private String nickname;
private String university;
private String studentId;
public MemberResponseDto(String email, String nickname, String university, String studentId){
this.email = email;
this.nickname = nickname;
this.university = university;
this.studentId = studentId;
}
public static MemberResponseDto from(Member member){
return new MemberResponseDto(
member.getEmail(),
member.getNickname(),
member.getUniversity(),
member.getStudentId());
}
}
생성자에서 memberId
를 삭제하고,
@JsonInclude(JsonInclude.Include.NON_NULL)
를 추가해준다.
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MemberResponseDto {
private Long memberId; //필드에서는 삭제하지 않음
private String email;
private String nickname;
private String university;
private String studentId;
public MemberResponseDto(String email, String nickname, String university, String studentId){
this.email = email;
this.nickname = nickname;
this.university = university;
this.studentId = studentId;
}
public static MemberResponseDto from(Member member){
return new MemberResponseDto(
member.getEmail(),
member.getNickname(),
member.getUniversity(),
member.getStudentId());
}
}
어노테이션을 추가하지 않으면
memberId
필드가 제외되는 것이 아니라
"memberId" : null, ...
null로 출력된다.
따라서 null값을 갖는 필드를 제외하는 어노테이션을 추가해주었다.