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 μ»¬λΌ μμ± λ°©μ§ λ° λ°μ΄ν°λ² μ΄μ€ ν
μ΄λΈμ κΉλνκ² μ μ§ν μ μμ΅λλ€.