자바/JPA
[JPA]고아 객체
OverTheHorizon3410
2023. 11. 4. 23:23
@Entity
@Getter
@ToString
public class Parent {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "parent", orphanRemoval = true, fetch = LAZY)
@ToString.Exclude
private List<Child> children = new ArrayList<>();
}
- 테스트
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class SpringTest {
@Autowired
private EntityManager em;
@Test
public void test() {
saveWithCascade(em);
removeOrphan(em);
findWithCascade(em);
}
private static void removeOrphan(EntityManager em) {
Parent parent = em.find(Parent.class, 1L);
parent
.getChildren()
.remove(0);
em.flush();
}
private static void saveWithCascade(EntityManager em) {
Parent parent = new Parent();
Child child1 = new Child();
child1.setParent(parent);
Child child2 = new Child();
child2.setParent(parent);
parent
.getChildren()
.add(child1);
parent
.getChildren()
.add(child2);
em.persist(parent);
em.flush();
}
private static void removeWithCascade(EntityManager em) {
Parent parent = em.find(Parent.class, 1L);
em.remove(parent);
em.flush();
}
private static void findWithCascade(EntityManager em) {
Parent parent = em.find(Parent.class, 1L);
System.out.println(parent);
parent
.getChildren()
.forEach(System.out::println);
}
}
- 고아 객체 제거 기능은
- 부모 엔티티와 연관관계가 끊어진 자식 엔티티를 자동으로 삭제하는 JPA 기능
orphanRemoval 속성을 true
로 설정
parent
.getChildren()
.remove(0);
- 는 flush 수행시
delete
from
child
where
id=?
가 수행되게 된다.
Uploaded by N2T