
객체와 테이블의 연관관계의 차이!
1. 참조를 통한 연관관계는 언제나 단방향
-> 결국, 연관관계를 추가해서 양쪽 참조를 해야 함
2. 단, 참조를 통한 양쪽 참조 != 양방향 관계
-> 서로 다른 단방향 2개

@Entity
@Data
public class A {
@Id
@Column(name = "A_ID")
private Long id;
@ManyToOne
@JoinColumn(name = "B_ID")
private B b;
private String aa;
}
// 🔺는 A 클래스 , 🔻는 B클래스
@Entity
@Data
public class B {
@Id
@Column(name = "B_ID")
private Long id;
private String bb;
}

@Entity
@Data
public class A {
@Id
@Column(name = "A_ID")
private Long id;
@ManyToOne
@JoinColumn(name = "B_ID")
private B b;
private String aa;
}
// 🔺는 A 클래스 , 🔻는 B클래스
@Entity
@Data
public class B {
@Id
@Column(name = "B_ID")
private Long id;
@OneToMany(mappedBy = "b")
private List<A> b = new ArrayList<>();
private String bb;
}
테이블은 외래 키 하나로 연관관계 관리
객체는 두 객체간 서로를 참조
->어떤 관계를 사용해서 외래 키를 관리해야할까?
JPA에서는 두 객체 연관관계 중 하나를 정해서 테이블의 외래 키 관리를 지시
두 연관관계 중 하나를 연관관계의 주인으로 정해야 함
public class Main {
public static void main(String[] args) {
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("myJpaUnit");
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
try {
transaction.begin();
B bc = new B(1L, new ArrayList<>(), "firstB");
A ac1 = new A(1L, null, "firstA");
A ac2 = new A(2L, null, "secondA");
bc.getA().add(ac1);
bc.getA().add(ac2);
// 비영속 -> 영속
em.persist(bc);
// DB에 데이터 저장
transaction.commit();
// find -> 1차 캐시에 영속 Entity 존재하므로 1차캐시에서 Get
/*
B(
id=1,
a=[
A(id=1, b=null, aa=firstA),
A(id=2, b=null, aa=secondA)
],
bb=firstB
)
*/
System.out.println(em.find(B.class, 1L));
// 영속 -> 준영속
em.detach(bc);
// find -> 1차 캐시에 영속 Entity ❌, DB에서 1차 캐시에 영속 Entity 저장 후 1차 캐시에서 Get
// B(id=1, a=[], bb=firstB)
System.out.println(em.find(B.class, 1L));
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
em.close();
}
}
}