Backend Ddevelopment
โ๐[Backend Development] mappedBy๋ ๋ฌด์์ผ๊น์?โ
๐ Intro.
- mappedBy๋ ์๋ฐฉํฅ ์ฐ๊ด๊ด๊ณ์์ ์ฌ์ฉ๋๋ ์์ฑ์ผ๋ก, ์ฐ๊ด ๊ด๊ณ์ ์ฃผ์ธ์ด ์๋(์ฝ๊ธฐ ์ ์ฉ) ์ชฝ์์ ์ฌ์ฉํฉ๋๋ค.
- ์ฆ, ์ธ๋ ํค(FK)๋ฅผ ๊ด๋ฆฌํ์ง ์๋ ์ชฝ์์ mappedBy๋ฅผ ์ฌ์ฉํ์ฌ ์ฐ๊ด ๊ด๊ณ๋ฅผ ๋งคํํฉ๋๋ค.
โ
1๏ธโฃ mappedBy์ ํ์์ฑ.
- ์๋ฐฉํฅ ๊ด๊ณ์์๋ ๋ ๊ฐ์ ์ํฐํฐ๊ฐ ์๋ก๋ฅผ ์ฐธ์กฐํ๊ฒ ๋๋๋ฐ, JPA๋ ์ธ๋ ํค(FK)๋ฅผ ๊ด๋ฆฌํ โ์ฃผ์ธโ์ ํ๋๋ง ์ง์ ํด์ผ ํฉ๋๋ค.
- ์ด๋, ์ฐ๊ด ๊ด๊ณ์ ์ฃผ์ธ์ด ์๋ ์ชฝ์์ mappedBy๋ฅผ ์ฌ์ฉํ์ฌ ์ฃผ์ธ์ ๋ช
์ํฉ๋๋ค.
โ
2๏ธโฃ @OneToOne ์๋ฐฉํฅ ๊ด๊ณ์์ mappedBy ์ฌ์ฉ ์์
1๏ธโฃ User ์ํฐํฐ (์ฐ๊ด ๊ด๊ณ์ ์ฃผ์ธ)
@Entity
public class User {
@Id
@GeneratedValue(strategy = Generation.IDENTITY)
private Long id;
private String username;
@OneToOne
@JoinColumn(name = "profile_id") // FK๋ฅผ ๊ด๋ฆฌํ๋ ์ฃผ์ธ (user ํ
์ด๋ธ์ profile_id FK ์์ฑ)
private UserProfile profile;
// Getter, Setter
}
2๏ธโฃ UserProfile ์ํฐํฐ(mappedBy ์ฌ์ฉ)
@Entity
public class UserProfile {
@Id
@GenerationValue(strategy = Generation.IDENTITY)
private Long id;
private String bio;
private String website;
@OneToOne(mappedBy = "profile") // User ์ํฐํฐ์ profile ํ๋๊ฐ ๊ด๊ณ์ ์ฃผ์ธ
private User user;
// Getter, Setter
}
โ
3๏ธโฃ mappedBy = โprofileโ์ ์๋ฏธ
- โprofileโ์ User ์ํฐํฐ์ profile ํ๋๋ช
์ ๊ฐ๋ฆฌํต๋๋ค.
- ์ฆ, ์ด ๊ด๊ณ์ ์ฃผ์ธ์ User.profile์ด๋ฉฐ, UserProfile ์ํฐํฐ๋ ์ฝ๊ธฐ ์ ์ฉ์
๋๋ค.
- ๋ฐ๋ผ์ UserProfile.user ํ๋๋ ์ธ๋ ํค(FK)๋ฅผ ์์ฑํ์ง ์๊ณ , ๋งคํ๋ง ์ํํฉ๋๋ค.
โ
4๏ธโฃ ๋ฐ์ดํฐ๋ฒ ์ด์ค ํ
์ด๋ธ ๊ตฌ์กฐ
- ์ ์ฝ๋๋ฅผ ์คํํ๋ฉด user ํ
์ด๋ธ๋ง profile_id๋ผ๋ FK ์ปฌ๋ผ์ ๊ฐ์ง๋ฉฐ, user_profile ํ
์ด๋ธ์๋ ์ถ๊ฐ ์ปฌ๋ผ์ด ์์ฑ๋์ง ์์ต๋๋ค.
๐ user ํ
์ด๋ธ
id |
username |
profile_id (FK) |
1 |
Alice |
101 |
2 |
Bob |
102 |
๐ user_profile ํ
์ด๋ธ
id |
bio |
website |
101 |
โGamerโ |
โalice.comโ |
102 |
โDeveloperโ |
โbob.devโ |
- ๐ ์ธ๋ ํค๋ user.profile_id์๋ง ์กด์ฌํ๋ฉฐ, user_profile ํ
์ด๋ธ์๋ FK ์ปฌ๋ผ์ด ์์ต๋๋ค.
โ
5๏ธโฃ mappedBy๋ฅผ ์ฌ์ฉํ ๋ฐ์ดํฐ ์กฐํ
โ
User โ UserProfile ์กฐํ(๊ฐ๋ฅ โ
)
User user = entityManager.find(User.class, 1L);
UserProfile profile = user.getProfile(); // ์ ์ ์๋
โ
UserProfile โ User ์กฐํ(๊ฐ๋ฅ โ
)
UserProfile profile = entityManager.find(UserProfile.class, 101L);
User user = profile.getUser(); // mappedBy๋ฅผ ์ฌ์ฉํ์ผ๋ฏ๋ก ๊ฐ๋ฅ!
๐ ์ ๋ฆฌ.
- โ๏ธ ์ฐ๊ด ๊ด๊ณ์ ์ฃผ์ธ(Owner)์ด ์๋ ์ชฝ์์ mappedBy๋ฅผ ์ฌ์ฉํด์ผ ํ๋ค.
- โ๏ธ โmappedBy = ์ฃผ์ธ ์ํฐํฐ ํ๋๋ช
โ์ผ๋ก ์ค์ ํด์ผ ํ๋ค.
- โ๏ธ ์ธ๋ ํค(FK)๋ mappedBy๋ฅผ ์ฌ์ฉํ ์ชฝ์ด ์๋๋ผ ์ฃผ์ธ์ด ๊ด๋ฆฌํ๋ค.
- โ๏ธ mappedBy๋ ์ฝ๊ธฐ ์ ์ฉ์ด๋ฏ๋ก @JoinColumn์ ์ฌ์ฉํ์ง ์๋๋ค.
๐ mappedBy๋ฅผ ์ฌ์ฉํ๋ฉด ๋ถํ์ํ FK ์ปฌ๋ผ ์์ฑ ๋ฐฉ์ง ๋ฐ ๋ฐ์ดํฐ๋ฒ ์ด์ค ํ
์ด๋ธ์ ๊น๋ํ๊ฒ ์ ์งํ ์ ์์ต๋๋ค.