Life Developer
인생 개발자
[JPA]불쌍한 고아객체..

 

 

고아객체가 뭐냐면 부모 엔티티와 연관관계가 끊어진 자식 엔티티를 고아객체라고 하는데

 

이것을 자동으로 삭제해주는 기능이있다.

 

orphanRemoval = true 를 주면된다.

 

@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL,orphanRemoval = true)
private List<Child> childList = new ArrayList<>();

 

 

예제코드는 아래다.

 

 

Child child1 = new Child();
Child child2 = new Child();

Parent parent = new Parent();

parent.addChild(child1);
parent.addChild(child2);

em.persist(parent);

em.flush();
em.clear();

Parent findParent = em.find(Parent.class, parent.getId());
for (Child c : findParent.getChildList()) {
System.out.println("c.getId() = " + c.getId());
}
findParent.getChildList().remove(0);
for (Child c : findParent.getChildList()) {
System.out.println("c.getId() = " + c.getId());
}

System.out.println(" ================================== ");
tx.commit(); //이시점에 DB 쿼리가 날라감

 

 

그리고 부모를 제거하면 자식도 제거된다. (고아기 때문에)

  Comments,     Trackbacks