Backend Ddevelopment
โ๐[Backend Development] ๋จ๋ฐฉํฅ๊ณผ @OneToOne์ด๋ ๋ฌด์์ผ๊น์?โ
๐ Intro.
- ๋จ๋ฐฉํฅ @OneToOne ๊ด๊ณ๋ ์ํฐํฐ ๊ฐ์ 1:1 ๊ด๊ณ๋ฅผ ๋งคํํ ๋, ํ์ชฝ ์ํฐํฐ์์๋ง ๊ด๊ณ๋ฅผ ๊ด๋ฆฌํ๋ ๋ฐฉ์์
๋๋ค.
- ์ฆ, ํ ์ํฐํฐ์์๋ง ๋ค๋ฅธ ์ํฐํฐ๋ฅผ ์ฐธ์กฐํ๊ณ , ๋ฐ๋์ชฝ์์๋ ์ด๋ฅผ ์์ง ๋ชปํ๋ ์ํ์
๋๋ค.
โ
1๏ธโฃ ์์ ์ฝ๋
- ์๋ฅผ ๋ค์ด, User ์ํฐํฐ์ UserProfile ์ํฐํฐ๊ฐ 1:1 ๊ด๊ณ๋ฅผ ๊ฐ์ง๋ค๊ณ ๊ฐ์ ํด๋ด
์๋ค.
๐ User ์ํฐํฐ์์ UserProfile ์ํฐํฐ๋ฅผ ๋จ๋ฐฉํฅ์ผ๋ก ์ฐธ์กฐํ๋ ๊ฒฝ์ฐ:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
@OneToOne
@JoinColumn(name = "profile_id") // User ํ
์ด๋ธ์ profile_id ์ปฌ๋ผ์ด UserProfile์ id๋ฅผ ์ฐธ์กฐ
private UserProfile profile;
// Getter, Setter
}
๐ UserProfile ์ํฐํฐ:
@Entity
public class UserProfile {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String bio;
private String website;
// Getter, Setter
}
โ
์ค๋ช
:
-
- @OneToOne์ ์ฌ์ฉํ์ฌ User ์ํฐํฐ๊ฐ UserProfile ์ํฐํฐ๋ฅผ ์ฐธ์กฐํฉ๋๋ค.
-
- @JoinColumn(name = โprofile_idโ)๋ฅผ ์ฌ์ฉํ์ฌ User ํ
์ด๋ธ์ profile_id ์ปฌ๋ผ์ด ์์ฑ๋ฉ๋๋ค.
-
User ํ
์ด๋ธ์ profile_id๋ผ๋ ์ธ๋ ํค(FK) ์ปฌ๋ผ์ ์ถ๊ฐํ๊ณ , ์ด ์ปฌ๋ผ์ด UserProfile ํ
์ด๋ธ์ id(PK)๋ฅผ ์ฐธ์กฐํ๋๋ก ๋ง๋ญ๋๋ค.
- ์ฆ, User ํ
์ด๋ธ์ profile_id๊ฐ UserProfile ํ
์ด๋ธ์ id๋ฅผ ์ฐธ์กฐํ๋ FK์ด๋ค.
-
- ํ์ง๋ง UserProfile ์ํฐํฐ์๋ User์์ ๊ด๊ณ๋ฅผ ์ ์ ์๋ ์ ๋ณด๊ฐ ์์ต๋๋ค. โ ์ด๊ฒ์ด ๋จ๋ฐฉํฅ ๊ด๊ณ์
๋๋ค.
โ
์ด์ ๋ฐ์ดํฐ๋ฒ ์ด์ค ํ
์ด๋ธ ์์:
- ์ด ์ฝ๋๋ฅผ ๊ธฐ๋ฐ์ผ๋ก JPA๊ฐ ์์ฑํ๋ ํ
์ด๋ธ์ ๋ณด๋ฉด ๋ค์๊ณผ ๊ฐ์ด ๋ฉ๋๋ค.
๐ 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.id๋ฅผ ์ฐธ์กฐ(FK)ํ๋ ๊ตฌ์กฐ์
๋๋ค.
- ๋ฐ๋ผ์ UserProfile ์ํฐํฐ์๋ profile_id๊ฐ ๋ฐ๋ก ํ์ํ์ง ์์ต๋๋ค.
- ๋์ ๊ธฐ๋ณธ ํค(id)๊ฐ User ์ํฐํฐ์ ์ธ๋ ํค(profile_id)๋ก ์ฌ์ฉ๋ฉ๋๋ค.
โ
2๏ธโฃ ๋จ๋ฐฉํฅ ๊ด๊ณ์ ํน์ง.
โ
์ฅ์ .
- ๊ตฌ์กฐ๊ฐ ๋จ์ํ๊ณ ์ดํดํ๊ธฐ ์ฝ๋ค.
- ํ์ชฝ์์๋ง ์ฐธ์กฐํ๋ฏ๋ก ๋ถํ์ํ ์ฐ๊ด๊ด๊ณ ๋ก๋ฉ์ ๋ฐฉ์งํ ์ ์๋ค.
โ ๋จ์ .
- ๋ฐ๋์ชฝ(UserProfile)์์ User๋ฅผ ์กฐํํ ๋ฐฉ๋ฒ์ด ์๋ค.
- UserProfile์ด ์์ ์ ์ฐธ์กฐํ๋ User๊ฐ ๋๊ตฌ์ธ์ง ์๊ณ ์ถ๋ค๋ฉด ๋ณ๋์ ์ฟผ๋ฆฌ๋ฅผ ์์ฑํด์ผ ํ๋ค.
โ
3๏ธโฃ ๋จ๋ฐฉํฅ ๊ด๊ณ ์กฐํ.
- ์ฌ์ฉ์๊ฐ ํ๋กํ ์ ๋ณด๋ฅผ ๊ฐ์ ธ์ค๋ ์ฝ๋๋ฅผ ์์ฑํ๋ฉด ๋ค์๊ณผ ๊ฐ์ต๋๋ค.
User user = entityManager.find(User.class, 1L);
UserProfile profile = user.getProfile(); // User -> UserProfile ์กฐํ ๊ฐ๋ฅ.