쿠릉쿠릉 쾅쾅
쿠릉쿠릉 쾅쾅
쿠릉쿠릉 쾅쾅
250x250
전체 방문자
오늘
어제
  • 분류 전체보기
    • HTML CSS
    • 잡담
    • 프로그래밍 꿀팁 사이트
    • 코딩 도서
    • [자바]
      • 디자인 패턴
      • 자바의 정석 - 3판
      • 자바
      • 자바 문법
    • git
    • [TDD]
    • 개발 서적 독후감
      • 클린 코더
      • 토비 스프링3
      • 객체지향의 사실과 오해
      • 모던 자바 인 액션
      • 엘레강트 오브젝트
    • CS
      • 운영체제
      • HTTP
    • [SQL]
      • SQL 기초
      • 혼자공부하는SQL
    • [ Spring ]
      • REST API
      • Spring Toy
      • Spring 에러
      • Spring
      • Spring 입문
      • Spring 핵심 원리
      • SpringMVC 1편
      • SpringMVC 2편
      • Spring Boot를 이용한 RESTful We..
      • Batch
    • [JPA]
      • JPA
      • JPA 에러
      • JPA 프로그래밍 - 기본편
      • 스프링 부트와 JPA 활용 1 - 웹 애플리케이..
      • 실전! 스프링 부트와 JPA 활용2 - API 개..
      • 실전! 스프링 데이터 JPA
      • 실전! Querydsl
    • 인텔리제이
    • [DB]
      • DB
      • H2
    • Gradle
    • 면접
    • [알고리즘]
      • 알고리즘
      • 자료구조
      • 자바 알고리즘 공부
    • [프로젝트]
    • 쿠릉식 객체지향 사고
    • 리눅스

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • http
  • REST API
  • 자바
  • 깃허브
  • 함수형인터페이스
  • 재귀
  • 자료구조
  • 스프링부트
  • SQL
  • querydsl
  • Spring
  • MVC
  • Git
  • 스프링
  • JPA
  • GitHub
  • springboot
  • 알고리즘
  • 백준
  • java

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
쿠릉쿠릉 쾅쾅

쿠릉쿠릉 쾅쾅

[JPA] 프록시와 연관관계 관리
[JPA]/JPA 프로그래밍 - 기본편

[JPA] 프록시와 연관관계 관리

2022. 3. 30. 04:11
728x90

 

 

프록시

데이터베이스의 테이블과 다르게 객체가 주는 장점은 객체 그래프를 통해 연관된 객체를 탐색할 수 있다는 것이다. 테이블 중심으로 객체를 탐색하려면 참조할 객체의 정보를 미리 알아내고 조인 쿼리를 통해 정보를 가져와야 한다. JPA는 이러한 문제를 해결하려고 '프록시' 기술을 사용한다. 프록시를 사용하면 연관된 객체를 처음부터 데이터베이스에서 조회하는 것이 아니라, 실제 사용하는 시점에 데이터베이스에서 조회할 수 있다.

엔티티를 조회할 때 연관된 엔티티들이 항상 사용된느 것은 아니다. 예를 들어 회원 엔티티를 조회할 때 연관된 Team 엔티티는 로직에 따라 사용될 때도 있지만 그렇지 않을 때도 있다. 로직에서 사용하지 않는 정보임에도 Team 엔티티를 조인해서 정보를 갖고 있는 것은  비효율적이다.

  • em.find() : 데이터 베이스를 통해서 실제 엔티티 객체를 조회한다.
  • em.getReference() : 데이터베이스 조회를 미루는 가짜(프록시) 엔티티 객체를 조회한다.
  • 여기서 em은 EntityManager(엔티티 매니저)다.

 

1. 프록시 객체 

MemberV2 refMember = em.getReference(MemberV2.class, 1L);
  • em.getReference() 메서드를 통해 프록시 객체를 반환 받았다.
  • 프록시 내부는 텅 비워져있고, 실제 엔티티를 가리키는 Entity target 이라는 멤버변수를 가진다.

 

2. 프록시 특징

  • 프록시 객체는 실제 클래스를 상속 받아서 만들어진다.
  • 그래서 실제 클래스와 겉 모양이 같다.
  • 사용하는 입장에서는 진짜 객체인지 프록시 객체인지 구분하지 않고 사용하면 된다.

  • 프록시 객체는 실제 객체의 참조(target)를 보관하고 있다.
  • 프록시 객체를 호출하면 프록시 객체는 실제 객체의 메서드를 호출한다.
  • 프록시 객체에 target 객체가 생기고 나서부터는 target 조회할 때 더 이상 DB를 조회하지 않는다.
    • 초기화는 무조건 한 번만 이뤄진다.
  • 프록시 객체를 초기화할 때, 프록시 객체가 실제 엔티티로 바뀌는 것이 아니다. 초기화가 되면 프록시 객체를 통해서 실제 엔티티에 접근하는 것이다.
  • 프록시 객체는 원본 엔티티를 상속 받는다.  따라서 타입 체크시 '==' 을 절대 쓰지 말고 instanceof 를 사용해야한다.
    • 근데 타입 비교를 쓸 일이 많이 없다.
  • 영속성 컨텍스트에 도움을 받을 수 없는 준영속 상태일 때는 프록시를 초기화하면 문제가 발생한다.
    • 하이버네이트는 org.hibernate.LazyInitalizationException 예외를 터트린다.
  • 영속성 컨텍스트에 존재하는 엔티티는 em.getReference()로 프록시 객체를 생성해도 영속성 컨텍스트에 존재하는 원본 엔티티로 반환 받는다. 그래야 성능 최적화가 가능하다. 굳이 영속성 컨텍스트에 있는 객체를 프록시로 만들어봐야 얻는 이점도 없다.
  • 영속성 컨텍스트에 프록시가 먼저 반환이 될 경우 실제 객체를 반환하려고 해도 프록시 객체가 반환된다.
    • 왜냐하면 JPA는 한 트랜잭션 안에서는 객체의 동일성을 보장하기 때문이다.

 

3. 프록시 객체의 초기화

Member member = em.getReference(Member.class, “id1”);
member.getName();

  • 코드라인에서 em.getReference()를 호출하여 프록시 객체(Member 프록시 객체)를 가져온다.
  • 프록시 객체의 getName() 메서드를 호출하려고 하지만 target은 비워져있다.
  • 그래서 JPA는 영속성 컨텍스트에 초기화 요청을 한다.
    • 초기화는 실제 DB를 조회해서 엔티티를 가져오는 과정이다.
    • 이 때 target은 DB에서 가져온 엔티티(Member 엔티티)다.
  • 프록시 객체는 target에 들어있는 실제 엔티티(Member 엔티티)를 연결해서  targer.getName() 메서드를 호출해서 값을 가져온다.
  • 이제 초기화가 한 번 이뤄졌기 때문에 더이상 프록시 객체는 초기화하지 않는다.

프록시 매커니즘은 JPA 표준 스펙이라기보단 JPA 구현체인 하이버네이트 기준에 따른다.

 

4. 프록시 확인

  • 프록시 인스턴스의 초기화 여부 확인
    • PersistenceUnitUtil.isLoaded(Object entity)
  • 프록시 클래스 확인 방법
    • entity.getClass().getName() 출력
  • 프록시 강제 초기화
    • org.hibernate.Hibernate.initialize(entity);
  • 참고로 JPA 표준은 강제 초기화 기능이 없다.
    • 강제 호출 : member.getName()

 

Hibernate: 
    /* insert hellojpa.domain2.MemberV2
        */ insert 
        into
            MemberV2
            (TEAM_ID, USERNAME, MEMBER_ID) 
        values
            (?, ?, ?)
findMember = class hellojpa.domain2.MemberV2$HibernateProxy$46uNHV1N
findMember.getId() = 1
Hibernate: 
    select
        memberv2x0_.MEMBER_ID as MEMBER_I1_0_0_,
        memberv2x0_.TEAM_ID as TEAM_ID3_0_0_,
        memberv2x0_.USERNAME as USERNAME2_0_0_,
        team1_.TEAM_ID as TEAM_ID1_1_1_,
        team1_.name as name2_1_1_ 
    from
        MemberV2 memberv2x0_ 
    left outer join
        Team team1_ 
            on memberv2x0_.TEAM_ID=team1_.TEAM_ID 
    where
        memberv2x0_.MEMBER_ID=?
findMember.getUsername() = hello

 


 

즉시 로딩과 지연 로딩

  • 결론 : 실무에서는 모든 연관관계는 지연 로딩으로 사용할 것.
  • 지연 로딩은 프록시 객체를 사용하여 엔티티가 실제로 사용되기 전까지 데이터베이스 조회를 지연하는 기능이다. 
  • 즉시 로딩은 특정 엔티티를 조회할 때 연관관계가 있는 모든 것을 다 가져오는 기능이다.
  • @XXXToMany 의 기본 세팅은 지연 로딩(FetchType.LAZY)이다.
  • @XXXToOne 의 기본 세팅은 즉시 로딩(FetchType.EAGER)이다.
    • 즉시 로딩을 무조건 지연 로딩으로 바꿔줘야 한다.
    • @ManyToOne(fetch = FetchType.LAZY)
    • @OneToOne(fetch = FetchType.LAZY). 

📌 Team Entity

package hellojpa.domain2;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

@Entity
@Getter @Setter
public class Team {

    @Id @GeneratedValue
    @Column(name = "TEAM_ID")
    private Long id;

    private String name;

    @OneToMany(mappedBy = "team")
    private List<Member> members = new ArrayList<>();

    public void addMember(Member member) {
        memberv2.setTeam(this);
        members.add(member);
    }
}

📌 Member Entity

package hellojpa.domain2;

import javax.persistence.*;

@Entity
@Getter @Setter
public class Member {

    @Id
    @GeneratedValue
    @Column(name = "MEMBER_ID")
    private Long id;

    @Column(name = "USERNAME")
    private String username;

    @ManyToOne
    @JoinColumn(name = "TEAM_ID")
    private Team team;
}

Member를 조회할 때 Team도 함께 조회해야 할까?

  • 단순히 member 정보만 사용하는 비즈니스 로직일 경우 Team 테이블을 조회하지 않아도 된다.
  • 그러므로 지연로딩을 통해 Team 객체를 프록시로 대체하는 것이 좋다.

지연 로딩을 사용해서 프록시로 조회

📌 Member Entity

package hellojpa.domain2;

import javax.persistence.*;

@Entity
@Getter @Setter
public class Member {

    @Id
    @GeneratedValue
    @Column(name = "MEMBER_ID")
    private Long id;

    @Column(name = "USERNAME")
    private String username;

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name = "TEAM_ID")
    private Team team;
}

📌 Main 메서드

package hellojpa;

import hellojpa.domain2.MemberV2;
import hellojpa.domain2.Team;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import java.util.List;

public class JpaMain {

    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
        EntityManager em = emf.createEntityManager();

        EntityTransaction tx = em.getTransaction();

        tx.begin();

        try {

            Team team = new Team();
            team.setName("teamA");
            em.persist(team);
            
            Member member1 = new Member();
            member1.setUsername("member1");
            member1.setTeam(team);
            em.persist(member1);

            tx.commit();
        } catch (Exception e) {
            System.out.println("e.getMessage=" +e.getMessage());
            tx.rollback();
        } finally {
            em.close();
        }
        emf.close();
    }
}

 

1. 프록시와 즉시 로딩 주의

즉시 로딩을 적용하면 예상지 못한 SQL이 발생한다.
 → 즉시 로딩은 JPQL에서 N+1 문제를 일으킨다.

package hellojpa;

import hellojpa.domain2.MemberV2;
import hellojpa.domain2.Team;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import java.util.List;

public class JpaMain {

    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
        EntityManager em = emf.createEntityManager();

        EntityTransaction tx = em.getTransaction();

        tx.begin();

        try {

            Team team = new Team();
            team.setName("teamA");
            em.persist(team);

            Team teamB = new Team();
            team.setName("teamB");
            em.persist(teamB);

            Member member1 = new Member();
            member1.setUsername("member1");
            member1.setTeam(team);
            em.persist(member1);

            Member member2 = new Member();
            member2.setUsername("member2");
            member2.setTeam(teamB);
            em.persist(member2);

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

            List<Member> members = em.createQuery("select m from Member m", Member.class)
                    .getResultList();

            tx.commit();
        } catch (Exception e) {
            System.out.println("e.getMessage=" +e.getMessage());
            tx.rollback();
        } finally {
            em.close();
        }
        emf.close();
    }
}
/* 출력 구문 */

Hibernate: 
    /* select
        m 
    from
        MemberV2 m  */ select
            memberv2x0_.MEMBER_ID as MEMBER_I1_0_,
            memberv2x0_.TEAM_ID as TEAM_ID3_0_,
            memberv2x0_.USERNAME as USERNAME2_0_ 
        from
            MemberV2 memberv2x0_
Hibernate: 
    select
        team0_.TEAM_ID as TEAM_ID1_1_0_,
        team0_.name as name2_1_0_ 
    from
        Team team0_ 
    where
        team0_.TEAM_ID=?
Hibernate: 
    select
        team0_.TEAM_ID as TEAM_ID1_1_0_,
        team0_.name as name2_1_0_ 
    from
        Team team0_ 
    where
        team0_.TEAM_ID=?
3월 30, 2022 4:57:48 오후 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:h2:tcp://localhost/~/test]

Process finished with exit code 0
  • JPQL로 select 구문을 1줄 작성 했지만 2개 줄이 추가적을 더 나갔다. 그래서 총 select 구문이 3줄이 작성된다.
  • 이것처럼 즉시로딩으로 할 경우 SQL 구문 1줄에 N 줄이 더 생겨 N+1 문제를 일으킨다.
  • 이것은 성능 저하로 이어진다.

 

2. N+1 문제 해결하는 방법 → 글로벌 페치 전략

  • 즉시 로딩 / 지연 로딩에서 둘 다 N+1 문제가 발생한다.
    • 지연 로딩은 member 엔티티 안에 있는 team 엔티티를 조회시 N+1 문제가 발생한다.
  • N+1 문제를 해결하기 위해 페치 전략을 사용한다.
  • 페치 전략은 프록시 엔티티를 이용하여 동적으로 필요할 때만 선별적으로 조인하는 전략이다.
    • fetch를 통해서 조인 쿼리를 조회한다.
    • 즉 페치 조인을 사용하게 되면 연관된 엔티티는 프록시가 아닌 실제 엔티티를 조회하게 되므로 연관관계 객체까지 한 번의 쿼리로 가져올 수 있다.

fetch join 사용

package hellojpa;

import hellojpa.domain2.MemberV2;
import hellojpa.domain2.Team;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import java.util.List;

public class JpaMain {

    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
        EntityManager em = emf.createEntityManager();

        EntityTransaction tx = em.getTransaction();

        tx.begin();

        try {

            Team team = new Team();
            team.setName("teamA");
            em.persist(team);

            Team teamB = new Team();
            team.setName("teamB");
            em.persist(teamB);

            MemberV2 member1 = new MemberV2();
            member1.setUsername("member1");
            member1.setTeam(team);
            em.persist(member1);

            MemberV2 member2 = new MemberV2();
            member2.setUsername("member2");
            member2.setTeam(teamB);
            em.persist(member2);

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

            // 페치 조인 추가
            List<MemberV2> members = em.createQuery("select m from MemberV2 m join fetch m.team", MemberV2.class)
                    .getResultList();

            tx.commit();
        } catch (Exception e) {
            System.out.println("e.getMessage=" +e.getMessage());
            tx.rollback();
        } finally {
            em.close();
        }
        emf.close();
    }
}
Hibernate: 
    /* select
        m 
    from
        MemberV2 m 
    join
        fetch m.team */ select
            memberv2x0_.MEMBER_ID as MEMBER_I1_0_0_,
            team1_.TEAM_ID as TEAM_ID1_1_1_,
            memberv2x0_.TEAM_ID as TEAM_ID3_0_0_,
            memberv2x0_.USERNAME as USERNAME2_0_0_,
            team1_.name as name2_1_1_ 
        from
            MemberV2 memberv2x0_ 
        inner join
            Team team1_ 
                on memberv2x0_.TEAM_ID=team1_.TEAM_ID

🔍 페치 조인의 한계

  • 컬렉션을 페치 조인하면 페이징 API를 사용할 수 없다.
    • 하이버네이트에서 컬렉션을 페치 조인하고 페이징 API를 사용하면 메모리에서 페이징 처리를 진행한다.
    • 즉 데이터베이스에서는 FULL Scan한 이후 모든 데이터를 메모리에 올린 이후 limit에 맞게 데이터를 만들게 된다.
    • 우선 데이터베이스에 Full Scan하는 것도 문제지만 그것을 메모리에 올리기 때문에 메모리를 심하게 잡아먹게 된다.
    • 그래서 컬렉션을 페치 조인하면 페이징 API를 사용할 수 없는 것이다.
    • 하지만 컬렉션이 아닌 단일 값 연관 필드의 경우에는 페치 조인을 사용해도 페이징 API를 사용할 수 있다.
  • 둘 이상 컬렉션을 페치할 수 없다.
    • 켈렉션의 카세티안 곱이 만들어지므로 하이버네이트는 주의해야 한다.
    • 하이버네이트는 annotsimultaneously fetch multiple bag 예외가 발생한다.
    • 가장 쉬운 해결 방법으로는 자료형 List을 Set으로 변경하는 것이다.
    • 하지만 자료형을 변경하는 것은 좋은 해결 방법이 아니다.

 

 

 


 

영속성 전이(CASCADE)와 고아 객체

1. 영속성 전이 (CASCADE)

  • 영속성 전이는 연관관계와 관련이 없다.
  • 특정 엔티티를 영속 상태로 만들 때 연관된 엔티티도 함께 영속 상태로 만들고 싶을 때 사용한다.
    • 예) 부모 엔티티를 저장할 때 자식 엔티티도 함께 저장한다.

🔍 영속성 전이 사용 전

📌 Parent Entity

package hellojpa.domain2;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

@Entity
@Getter @Setter
public class Parent {

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    @OneToMany(mappedBy = "parent")
    private List<Child> childList = new ArrayList<>();

    public void addChild(Child child) {
        childList.add(child);  // 이전 child 가 있으면 뺴고 그런 작업이 있어야 한다.
        child.setParent(this);
    }
}

📌 Child Entity

package hellojpa.domain2;

import javax.persistence.*;

@Entity
@Getter @Setter
public class Child {

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    @ManyToOne
    @JoinColumn(name = "parent_id")
    private Parent parent;
}

📌 Main 메서드

package hellojpa;

import hellojpa.domain2.Child;
import hellojpa.domain2.Parent;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

public class JpaMain {

    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
        EntityManager em = emf.createEntityManager();

        EntityTransaction tx = em.getTransaction();

        tx.begin();

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

            Parent parent = new Parent();
            parent.addChild(child1);
            parent.addChild(child2);

            em.persist(parent);
            em.persist(child1);
            em.persist(child2);

            tx.commit();
        } catch (Exception e) {
            System.out.println("e.getMessage=" +e.getMessage());
            tx.rollback();
        } finally {
            em.close();
        }
        emf.close();
    }
}
  • em.persist()를 엔티티 개수 만큼 3번 호출하여 parent, child1, child2 엔티티들을 영속성 컨텍스트에 저장했다.

🔍 영속성 전이 사용

package hellojpa.domain2;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

@Entity
public class Parent {

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    // cascade 추가 (영속성 전이 사용)
    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
    private List<Child> childList = new ArrayList<>();

    public void addChild(Child child) {
        childList.add(child);  // 이전 child 가 있으면 뺴고 그런 작업이 있어야 한다.
        child.setParent(this);
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

📌 Main 메서드

package hellojpa;

import hellojpa.domain2.Child;
import hellojpa.domain2.Parent;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

public class JpaMain {

    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
        EntityManager em = emf.createEntityManager();

        EntityTransaction tx = em.getTransaction();

        tx.begin();

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

            Parent parent = new Parent();
            parent.addChild(child1);
            parent.addChild(child2);

            em.persist(parent);

            tx.commit();
        } catch (Exception e) {
            System.out.println("e.getMessage=" +e.getMessage());
            tx.rollback();
        } finally {
            em.close();
        }
        emf.close();
    }
}
/* 출력 결과 */

Hibernate: 
    /* insert hellojpa.domain2.Parent
        */ insert 
        into
            Parent
            (name, id) 
        values
            (?, ?)
Hibernate: 
    /* insert hellojpa.domain2.Child
        */ insert 
        into
            Child
            (name, parent_id, id) 
        values
            (?, ?, ?)
Hibernate: 
    /* insert hellojpa.domain2.Child
        */ insert 
        into
            Child
            (name, parent_id, id) 
        values
            (?, ?, ?)
3월 30, 2022 6:11:57 오후 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:h2:tcp://localhost/~/test]

Process finished with exit code 0
  • Parent 엔티티에 @OneToMany 애노테이션의 cascade 속성을 사용하여 Parent 엔티티가 영속성 상태가 될 때 List에 들어있는 Child 엔티티들도 같이 영속성 상태가 된다.

🔍 영속성 전이(CASCADE) 주의

  • 영속성 전이는 연관관계를 매핑하는 것과 아무 관련이 없다.
  • 엔티티를 영속화할 때 연관된 엔티티도 함께 영속화하는 기능 하나만 제공한다.

🔍 CASCADE 종류

  • cascade=ALL : 모두 적용
  • cascade=PERSIST : 영속
  • cascade=REMOVE : 삭제
  • cascade=MERGE : 병함
  • cascade=REFRESH : REFRESH
  • cascade=DETACH : DETACH

ALL / PERSIST / REMOVE 를 자주 쓴다.

🔍 영속성 전이를 사용하는 경우

  • 전이 되 대상이 한 군데에서만 사용된다면 써도 된다.
    • 하지만, 해당 엔티티(Child)가 특정 엔티티(Parent)에 정속되지 않고 여러 곳에서 사용한다면 사용하지 않는게 좋다.
  • 라이플 사이클이 동일할 때
  • 단일 소유자 관계일 때
    • 해당 엔티티(Child)가 특정 엔티티(Parent)에 100% 종속될 때
    • 다른 엔티티가 해당 엔티티(Child)를 알면 안된다.
    • 그러나 해당 엔티티(Child)가 다른 엔티티를 알아도 된다.

 

2. 고아 객체

  • 고아 객체 제거 : 부모 엔티티와 연관관계가 끊어진 자식 엔티티를 자동으로 삭제한다.
  • orphanRemoval=true
    • 기본값은 false
    • 예) @OneToMany(orphanRemoval=true)
  • @OneToOne / @OneToMany 애노테이션에서만 사용할 수 있다.
  • 개념적으로 부모를 제거하면 자식은 고아가 된다. 따라서 고아 객체 제거 기능을 활성화 하면, 부모를 제거할 때 자식도 같이 제거된다. 마치 CascadeType.REMOVE 처럼 동작한다.

🔍 고아 객체 주의

  • 영속성 전이처럼 특정 엔티티가 100% 소유 할 때 사용해야한다.
  • 참조하는 곳이 하나일 때만 사용해야한다. 

 

3. 영속성 전이 + 고아 객체 - 생명주기

CascadeType.ALL + orphanRemoval=true

  • 스스로 생명주기를 관리하는 엔티티(부모 엔티티)를 em.persist()로 영속화할 수 있고, em.remove()로 제거할 수 있다.
  • 영속성전이와 고아 객체 옵션을 둘 다 활성화 하면 부모 엔티티를는 자식의 생명 주기를 관리한다.
  • 도메인 주도 설계(DDD)의 Aggregate Root 개념을 구현할 때 유용하다.
    • 연관깊은 도메인들을 각각이 아닌 하나의 집합으로 다루는 것을 Aggregate라고 한다. 즉, 데이터 변경의 단위로 다루는 연관 객체의 묶음이다.
    • Aggregate Root 개념을 참고하자면 
      • 부모 엔티티가 자식 엔티티를 관리하므로 자식 엔티티의 Repository는 없는게 낫다.
      • 자식 엔티티는 부모 엔티티를 통해서만 다뤄진다.
    • 참고) DDD에서 루트 엔티티는 전역 식별성 Global Identity를 가진 엔티티다.
      • 예) 주문 시스템의 Order Entity

 

 

 

 

 

 


👀 참고 자료

https://www.inflearn.com/course/ORM-JPA-Basic/dashboard

 

자바 ORM 표준 JPA 프로그래밍 - 기본편 - 인프런 | 강의

JPA를 처음 접하거나, 실무에서 JPA를 사용하지만 기본 이론이 부족하신 분들이 JPA의 기본 이론을 탄탄하게 학습해서 초보자도 실무에서 자신있게 JPA를 사용할 수 있습니다., - 강의 소개 | 인프런

www.inflearn.com

 

https://blog.naver.com/adamdoha?Redirect=Log&logNo=222111782623&from=postView 

 

[JPA] 프록시(Proxy)란?

서론 @XtoOne 은 기본 Fetch 전략이 Eager이기 때문에 N+1 이슈를 방지하기 위해 fetch 전략을 Lazy...

blog.naver.com

 

https://catsbi.oopy.io/820584fe-b34c-442f-b9bb-32dae8ec4ef0

 

프록시와 연관관계 관리

프록시

catsbi.oopy.io

 

https://cheese10yun.github.io/jpa-nplus-1/

 

JPA N+1 발생원인과 해결방법 - Yun Blog | 기술 블로그

JPA N+1 발생원인과 해결방법 - Yun Blog | 기술 블로그

cheese10yun.github.io

 

728x90

'[JPA] > JPA 프로그래밍 - 기본편' 카테고리의 다른 글

[JPA] 객체지향 쿼리 언어1 - 기본 문법  (0) 2022.03.31
[JPA] 값 타입  (0) 2022.03.31
[JPA] 고급 매핑  (0) 2022.03.29
[JPA] 다양한 연관관계 매핑  (0) 2022.03.29
[JPA] 연관관계 매핑 기초  (0) 2022.03.28
    '[JPA]/JPA 프로그래밍 - 기본편' 카테고리의 다른 글
    • [JPA] 객체지향 쿼리 언어1 - 기본 문법
    • [JPA] 값 타입
    • [JPA] 고급 매핑
    • [JPA] 다양한 연관관계 매핑
    쿠릉쿠릉 쾅쾅
    쿠릉쿠릉 쾅쾅
    깃허브 주소 : https://github.com/kureung

    티스토리툴바