JPA에서는 @ManyToOne
을 사용할 때 엔티티 간에 양방향 및 단방향의 두 가지 유형의 관계가 있다.
연결은 관계의 한쪽에서만 정의되고 관리된다.
예를들어 유저와 게시글의 관계에서 유저는 여러 게시글을 작성할 수 있으므로 게시글에 ManyToOne
주석을 넣는다.
단방향의 관계이므로 게시글을 관리하는 로직에서만 유저오브젝트에 접근이 된다.
@Entity
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String content;
@ManyToOne
private User author;
// other fields, getters, and setters
}
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// other fields, getters, and setters
}
연결은 관계의 양쪽에서 정의되고 관리된다.
서로가 서로를 참조하고 있으므로 어느 오브젝트 사용해도 참조된 오브젝트에 접근이 가능하다.
게시글에는 ManyToOne
주석을 이용하고 유저에는 OneToMany
주석을 이용한다.
@Entity
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String content;
@ManyToOne
private User author;
// other fields, getters, and setters
}
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
@OneToMany(mappedBy = "author")
private Set<Post> posts;
// other fields, getters, and setters
}
두개의 테이블의 1:1의 관계로 연결되어 있다면OneToOne
주석을 이용한다.
아래의 상황에서는 한사람은 하나의 여권을 소유하므로 1:1의 관계가 된다.
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToOne
private Passport passport;
// other fields, getters, and setters
}
@Entity
public class Passport {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String number;
// other fields, getters, and setters
}
양방향이 된다면 서로가 서로를 참조가능하게 된다.
양방향일 경우에는 mappedBy
속성을 이용해서 매핑되는 필드를 지정한다.
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToOne(mappedBy = "person")
private Passport passport;
// other fields, getters, and setters
}
@Entity
public class Passport {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String number;
@OneToOne
private Person person;
// other fields, getters, and setters
}