jpa
JPA 저장은 ID, 조회는 객체로 사용하는법
songjb
2023. 10. 10. 20:05
Comment
@Getter
@Entity
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Comment extends BaseEntity {
private Long roomId;
@Column(length = 500)
private String comment;
@ManyToOne(targetEntity = Member.class, fetch = FetchType.LAZY)
@JoinColumn(name = "member_id")
private Member member;
...
}
Member
@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Member extends BaseEntity {
@NonNull
private String username;
@Embedded
private Password password;
@Embedded
private Nickname nickname;
...
}
저장 로직
public CommentResponse comment(final Long roomId, final Long memberId, final CommentRequest request) {
validateExistRoom(roomId);
Member member = memberRepository.getMemberById(memberId);
Comment comment = new Comment(roomId, request.comment(), member);
commentRepository.save(comment);
return CommentResponse.of(comment);
}
Comment를 저장하기 위해서는 Member 객체가 필요하고 Member 객체를 가져오기위해서 MemberRepository에서 Member를 조회하는 쿼리가 필요하다.
create table comment
(
id bigint auto_increment,
comment varchar(500),
member_id bigint,
room_id bigint,
created_at timestamp(6),
updated_at timestamp(6),
primary key (id),
constraint fk_comment_member_id foreign key (member_id) references member (id)
)
그러나 실제 테이블을 고려할 때, Comment를 저장하는 데는 Member Id가 필요하지만 Member 객체가 필요하지 않습니다.
Comment에 Member 필드를 Member Id로 변경하는 방법도 있지만 댓글을 조회할 때 Member의 NickName과 같은 필드가 필요합니다
저장은 ID, 조회는 객체로 사용
@Getter
@Entity
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Comment extends BaseEntity {
private Long roomId;
@Column(length = 500)
private String comment;
@ManyToOne(targetEntity = Member.class, fetch = FetchType.LAZY)
@JoinColumn(name = "member_id", insertable = false, updatable = false)
private Member member;
@Column(name = "member_id")
private Long memberId;
public Comment(final Long roomId, final String comment, final Long memberId) {
this.roomId = roomId;
this.comment = comment;
this.memberId = memberId;
}
...
}
public CommentResponse comment(final Long roomId, final Long memberId, final CommentRequest request) {
validateExistRoom(roomId);
Comment comment = new Comment(roomId, request.comment(), memberId);
commentRepository.save(comment);
return CommentResponse.of(comment);
}
insertable = false 및 updatable = false 설정을 사용하면 Comment를 저장할 때 Member 정보를 필요하지 않고 Member Id만을 사용하여 Comment와 Member를 연결할 수 있습니다.
위 방법으로 데이터베이스에 불필요한 업데이트 작업을 방지하고 Comment를 효율적으로 저장할 수 있습니다.
https://stackoverflow.com/questions/27930449/jpa-many-to-one-relation-need-to-save-only-id