photocard backend server 개발일기
JPA Cascade 사용하기 위한 정리
한둥둥
2024. 5. 1. 01:47
JPA는 연관 관계에 있는 엔티티를 제거하기 위해 사용되는 두 가지 방식의 차이점이 있음.
가장 큰 차이점은 JPA에 의해 처리되느냐, DDL에 의해 처리되느냐이다. 전자 방식을 사용하는 경우 JPA에 의해 참조하는 레코드 제거 따라서 JPA 상에서 참조하는 레코드 수만큼 제거된다.
후자의 방식을 취할 경우, 데이터베이스 자체에서 on delete cascade 걸리게 된다. 따라서 JPA에서 관계형 데이터를 만들다보면 CASCADE를 다룰 일이 많아진다. 참조의 관계를 맺은 테이터베이스를 신뢰성 있는 상태로 유지해준다.
1. PERSIST - 엔티티를 영속화할 때, 연속된 엔티티도 함께 영속화하는 옵션이다.
Card card = new Card();
Comment comment = new Comment();
card.addComment(comment);
entityManager.persist(card);
2. MERGE - 엔티티 상태 병합할 때, 연관된 엔티티도 함께 병합하는 옵션이다.
Card card = new Card("this is card");
Comment comment = new Comment("this is card comment");
card.addComment(comment);
entityManager.persist(card);
entityManager.persist(comment);
card.setTitle("photocard sale");
comment.setValue("this is changed comment"):
entityManager.merge(card);
3. REMOVE - 엔티티 제거할 때 연관된 엔티티들도 함께 제거
Card card = new Card();
Comment comment = new Comment();
entityManager.persist(card);
entityManager.persist(comment);
entityManager.remove(card);
4. REFESH - 엔티티를 새로고침 할 때, 연관된 엔티티들도 함께 새로고침된다. => 새로고침 .. 데이터베이스로 부터 값을 즉시 로딩
Card card = new Card("This is photocard");
Comment comment = new Comment("this is comment");
card.addComment(comment);
entityManger.persist(card);
entityManger.persist(comment);
entityManger.flush();
card.setTitle("this is photocard changed");
comment.setValue("this is changed comment");
5. DETACH - 엔티티를 영속성 컨텍스트로부터 분리하면 연관된 엔티티들도 분리
Card card = new Card("this is card");
Comment comment = new Comment("this is comment");
card.addComment(card);
entityManager.persist(card);
entityManager.persist(comment);
entityManager.detach(post);
6. ALL 위에 있는 모든 내용을 적용함.
고아 객체
부모 엔티티와 연관 관계가 끊어진 자식 엔티티 가르킴
- 부모가 제거될 때, 부모와 관련된 모든 인티티들이 고아 객체이다.
- 부모와 자식 엔티티 사이의 연관 관계를 삭제할 때, 해당 엔티티는 고아 객체된다. << JPA