객체는 객체 그래프로 연관된 객체들을 탐색한다. 그런데 객체가 데이터베이스에 저장되어 있으므로 연관된 객체를 마음껏 탐색하기가 어렵다. JPA 구현체들은 이 문제를 해결하려고 프록시라는 기술을 사용한다.
프록시 객체
라고 한다.JPA 표준 명세는 지연로딩의 구현방법을 JPA 구현체에 위임했다. 따라서 지금부터 나오는 내용은 하이버네이트 구현체에 대한 내용이다. 하이버네이트는 지연 로딩을 사용하기 위해 프록시를 사용하는 방법과 바이트코드를 사용하는 방법이 있다.
// Persistence Context 에 Entity가 없으면 데이터베이스를 조회
// 엔티티를 사용하지 않아도 데이터베이스를 조회함
Member member = em.find(Member.class, "member1");
// 엔티티를 직접 사용하는 시점까지 데이터베이스 조회를 미룸
Member member = em.getReference(Member.class, "member2");
한 번만 초기화
된다.프록시가 엔티티로 바뀌는 것이 아니다!!
target
값에 채워지는 것이다.instance of
사용-타입 비교 ) em.getReference()
를 호출해도 프록시가 아닌 실제 엔티티를 반환한다.반대로,
처음에 프록시로 조회
하고 em.find()로 조회하게 되면 엔티티객체가 아닌 프록시 객체로 반환해준다!a == :a
를 만족해주어야 하기 때문!영속성 컨텍스트
의 도움을 받아야 한다.프록시의 초기화는
영속성 컨텍스트
에 의해서 이루어진다.
실제 사용될 때 데이터베이스를 조회해서 실제 엔티티 객체를 생성하는데 이것을 프록시 객체의 초기화라고 한다.//Meber Proxy를 반환한다. Member member = em.getReference(Member.class, "id1"); member.getName();
Member member = em.getReference...
transaction.commit();
em.close(); // 영속성 컨텍스트 종료
member.getName();
//결과
org.hibernate.LazyInitializationException 예외 발생 !
org.hibernate.Hibernate.initialize(entry);
JPA표준은 강제 초기화가 없음
, 강제 호출 : member.getName()Team team = em.getReference(Team.class, "team1"); // 식별자 보관
team.getId(); // 초기화되지 않음
boolean isLoad = PersistenceUnitUtil.isLoaded(entity);
// 프록시 인스턴스 초기화 여부 확인
@Entity
public class Member {
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name= "TEAM_ID")
private Team team;
// ...
}
Member member = em.find(Member.class,"member1");
Team team = member.getTeam();
// SQL
SELECT *
FROM
MEMBER M LEFT OUTER JOIN TEAM T
ON M.TEAM_ID=T.TEAM_ID
WHERE
M.MEMBER_ID = 'member1';
NULL 제약 조건과 JPA 조인 전략
외부 조인보다는 내부조인이 성능이 최적화에 더 유리하다. 내부 조인(inner join)을 사용하기 위해서는 외래 키에 NOT NULL 제약 조건을 설정하면 값이 있는 것을 보장한다.@JoinColumn(name="TEAM_ID", nullable=false)
처럼 명시해주면 내부조인을 사용한다.
또는
@ManyToOne(fetch = FetchType.EAGER, optional = false )
@JoinColum(name ="TEAM_ID")
private Team team;
</br>
### 지연 로딩(lazy)
``` java
Member member = em.find(Member.class,"member1");
Team team = member.getTeam(); // 프록시 객체
team.getName(); // 팀 객체 실제 사용
컬렉션에 FetchType.EAGER 사용 시 주의점
1. 컬렉션 즉시 로딩은 항상 외부 조인을 사용한다.
2. 컬렉션을 하나 이상 즉시 로딩하는 것은 권장하지 않는다.
특정 엔티티를 영속 상태로 만들 때 연관된 엔티티도 함께 영속 상태로 만들고 싶으면
영속성 전이기능
을 사용하면 된다. JPA는 CASCADE 옵션으로 영속성 전이를 제공한다. 쉽게 말해서 영속성 전이를 사용하면 부모 엔티티를 정장할 때 자식 엔티티도 함께 저장할 수 있다.
@Entity
public class Parent {
@OneToMany( mappedBy = "parent", cascade = CascadeType.PERSIST )
private List<Child> children = Lists.newArrayList();
}
private static void save(EntityManager em) {
Parent parent = new Parent();
child1.setParent(parent);
child2.setParent(parent);
parent.getChildren().addAll(child1,child2);
em.persist(parent);
}
Parent findParent = em.find(Parent.class, 1L);
em.remove(findParent);
부모 Entity
를 삭제한다면, 외래 키 제약조건으로 인해 외래키 무결성 예외
가 발생한다. 참고로 CascadeType.PERSIST, REMOVE는 em.persist(), em.remove()를 실행할 때 바로 전이가 발생하지 안ㄹ고 플러시를 호출할 때 전이가 발생한다.
JPA는 부모 엔티티와 연관관계가 끊어진 자식 엔티티를 자동으로 삭제하는 기능을 제공하는데 이것을 고아 객체(ORPHAN) 제거라 한다.
//엔티티
@OneToMany(mappedBy = "parent", orphanRemoval = true)
private List<Child> children = new ArrayList<>();
// 코드
Parent paren = em.find(Parent.class, parentId);
parent.getChildren().remove(removeObject);
CascadeType.All + orphanRemoval = true를 동시에 사용하면?
- 부모 엔티티를 통해서 자식의 생명주기를 관리할 수 있다.
- 자식을
저장
하려면 부모에 등록만 하면 된다.(CASCADE)
Parent parent = em.find(Parent.class, parentId); parent.addChild(child1);
- 자식을
삭제
하려면 부모에서 제거 하면 된다.(OrphanRemoval)
Parent parent = em.find(Parent.class, parentId); parent.getChildren.remove(removeObject);