์ฌํด ์ด ๋ณตํฉํค, ์ธ๋ํค ์ฌ์ฉ์ด ๋ง์ ํ ์ด๋ธ์ JPA Entity๋ก ๊ตฌํํ์ด์ผ ํ๋๋ฐ, JPA ์ฌ์ฉ์ด ์ฒ์์ด์์ด์ ์ต์ํ์ง ์์ ๋ณต์กํ๊ฒ ๋๊ปด์ก์๋ค. ๋๊ฐ์ ์ฌ๋์ ์ํด ์ ๋ฆฌํด ๋ณธ๋ค!
Entity์ ๋ณตํฉํค๋ฅผ ํตํ ์๋ณ๊ด๊ณ๋ฅผ ๋งคํํ๋ ๋ฐฉ๋ฒ์ @IdClass, @EmbededId ๋๊ฐ์ง๊ฐ ์๋๋ฐ ๋ณธ์ธ์ @IdClass๋ฅผ ์ฌ์ฉํ๋ค.
@EmbededId๋ @IdClass ๋ฐฉ์ ๋ณด๋ค ์ข๋ ๊ฐ์ฒด์งํฅ ๋ฐฉ์์ด๋ผ๊ณ ํ๋ค.
ํ์ง๋ง ํน์ ๊ฐ์ฒด๋ฅผ ์ฌ์ฉํ๊ธฐ ์ํด์ ๊ฐ์ฒด ๊ทธ๋ํ๋ฅผ ๊น๊ฒ ํ์ํด์ผํ๋ ๊ฒฝ์ฐ๊ฐ ์๊ณ , ๊น์ด ๊ฐ์ถฐ์ ธ ์์ด์ ๋ช
์์ ์ผ๋ก ๋ณด์ด์ง ์๋๋ค๊ณ ..
์๋ฅผ ๋ค์ด grandChild Entity์์ parent_id๋ฅผ ๊ตฌํ๊ธฐ ์ํด์ ์๋์ ๊ฐ์ด ํ์ํด์ผ ํ๋ค.
grandChild.getGId().getCId().getPId().getParentId();
IdClass๋ค์ด ์ค์ฒฉ๊ตฌ์กฐ๋ก ๊ฒน๊ฒน์ด ์์ฌ์ง๋ ๊ฒ์ ๋ณผ ์ ์๋ค.
@IdClass ๋ฐฉ์์ ์ฌ์ฉํ ๊ฒฝ์ฐ๋ ์๋์ ๊ฐ๋ค.
grandChid.getChild().getParent().getParentId();
@IdClass ๋ฐฉ์๊ณผ @EmbededId ๋ฐฉ์์ depth๊ฐ ํ๋๋ฐ์ ์ฐจ์ด๋์ง ์์ง๋ง @IdClass ๋ฐฉ์์ IdClass๊ฐ ์ค์ฒฉ๊ตฌ์กฐ๋ก ์์ฌ์ง๋๊ฒ ์๋๋ผ Entity๊ฐ ์ค์ฒฉ๊ตฌ์กฐ๋ก ์์ฌ์ ธ์ ๋ช ์์ ์ธ ๋ฉด์์ ๋ ๋์๋ณด์ด๋ ๋ฏ?!
(๋จ์ํ ํ๋์ ๋ณตํฉํค๋ง ์กด์ฌํ๋ค๊ณ ํ๋ฉด @EmbededId ๋ฅผ ์ฌ์ฉํ๊ณ , ๋ณตํฉํค๋ฅผ ํตํ ์๋ณ๊ด๊ณ ๋งคํ์ด ์ฌ๊ธฐ์ ๊ธฐ ์กด์ฌํ๋ค๋ฉด @IdClass๋ฅผ ์ด์ฉํ๋ผ๊ณ ๊ถํ๋ค๊ณ ํ๋๋ผ)
์๋๋ @IdClass๋ฅผ ์ฌ์ฉํ์ฌ Entity๋ฅผ ์ด๋ป๊ฒ ๊ตฌํํ๋์ง ๋ณด์ฌ์ฃผ๊ณ ์ ํ๋ค.
Parent
- Parent Entity
@ToString
@Entity
@Table(name = "PARENT")
public class Parent {
@Id
@Column(name = "PARENT_ID", columnDefinition ="VARCHAR(36)", nullable = false)
private String parentId;
@Column(name = "PARENT_NAME", columnDefinition ="VARCHAR(32)", nullable = false)
private String parentName;
}
parent๋ ํน๋ณํ ์ถ๊ฐ๋ก ์ธํ ํด์ฃผ๋๊ฒ์ด ์๋ค
Child
- Child Entity
@ToString
@Entity
@IdClass(ChildId.class)
@Table(name = "CHILD")
public class Child {
@Id
@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name="PARENT_ID", columnDefinition ="VARCHAR(36)", nullable = false)
public Parent parent;
@Id
@Column(name = "CHILD_ID", columnDefinition ="VARCHAR(36)", nullable = false)
private String childId;
@Column(name = "CHILD_NAME", columnDefinition ="VARCHAR(64)", nullable = false)
private String childName;
}
- ChildId.class
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
@Getter
@Setter
public class ChildId implements Serializable {
private String parent;
private String childId;
}
GrandChild
- GrandChild Entity
@Entity
@ToString
@Table(name = "GRANDCHILD")
@IdClass(GrandChildId.class)
public class GrandChild {
@Id
@Column(name = "GRAND_CHILD_ID", columnDefinition ="VARCHAR(36)")
private String grandChildId;
@Id
@ManyToOne
@JoinColumns({
@JoinColumn(name = "PARENT_ID", columnDefinition ="VARCHAR(36)", referencedColumnName = "PARENT_ID"),
@JoinColumn(name = "CHILD_ID", columnDefinition ="VARCHAR(36)", referencedColumnName = "CHILD_ID")
})
private Child child;
@Column(name = "GRAND_CHILD_NAME", columnDefinition ="VARCHAR(64)", nullable = false)
private String grandChildName;
}
- GrandChildId.class
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
@Getter
@Setter
public class GrandChildId implements Serializable {
private ChildId child;
private String grandChildId;
}
์ฐธ๊ณ ํ ์ฌ์ดํธ
๋๊ธ