본문 바로가기
유용한 사이트 및 정보

JPA의 양방향 연관관계의 주인 @MappedBy

by pyogowoon 2023. 2. 6.

 

Post

@Builder
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Entity
public class Post {

										.
                                        .
                                        .
                                        .
                                        .
                                        .
			
   @JsonIgnoreProperties({"post"})
    @OneToMany(mappedBy = "post")
    private List<PostLikes> postLikes;

  

  

}

 Post ( 게시판 ) 에 postLikes (좋아요) 의 정보를 가져오고 싶을 때

사용한 @OneToMany(MappedBy = "post")

 

OneToMany는 하나의 게시판에서 여러개의 좋아요를 가져와야하기 때문에 OneToMany고 

MappedBy 는 PostLikes(도메인)가 가진 Post타입의 변수 ( 아래 코드를 보면 post) 

 


@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
@Builder
@Entity
@Table(
        uniqueConstraints = {
                @UniqueConstraint(
                        name = "postLikes_uk",
                        columnNames = {"postId", "userId"}

                )
        }
)
public class PostLikes {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    private int id;

    @JsonIgnoreProperties({"user"})
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "postId")
    private Post post;


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "userId")
    private User user;

    private LocalDateTime createDate;


    @PrePersist
    public void createDate(){
        this.createDate = LocalDateTime.now();

    }



}

 

 

그렇기 때문에 두 객체중 하나의 객체만 테이블을 관리할 수 있도록 정하는 것이 MappedBy 옵션이다.

예제에서는 postLikes 객체에 MappedBy가 적용되어 있는 것을 볼 수 있는데 이 경우에는 postLikes 객체는 MEMBER 테이블을 관리할 수 없고 post 객체만이 권한을 받고 주인이 아닌 쪽은 읽기(조회)만 가능해진다. 즉, MappedBy가 정의되지 않은 객체가 주인(Owner)가 되는 것이다.

일반적으로 외래키를 가진, 간단하게 말하면, ManyToOne을 지닌 객체를 주인으로 정의하는 것이 좋다.

(외래키를 가지고있는 객체니까.)

 

 그리고 MappedBy("") 의 대상은 @OneToMany 를 달고있는 객체 속의 변수명을 정하면 된다.

댓글