Member member = em.getReference(Member.class, 1L);
member.getName(); // 1. getName();
em.getReference(...)
를 호출해도 프록시가 아닌 실제 엔티티를 반환org.hibernate.LazyInitializationException
예외 발생PersistenceUnitUtil.isLoaded(Object entity)
Hibernate.isInitialized(Object entity)
boolean isLoaded = em.getEntityManagerFactory()
.getPersistenceUnitUtil()
.isLoaded(entity);
boolean isLoaded2 = Hibernate.isInitialized(entity);
Hibernate.initialize(Object entity)
@ManyToOne(fetch = FetchType.EAGER)
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(nullable = true)
@ManyToOne(fetch = FetchType.EAGER, optional = true)
@JoinColumn(nullable = false)
@ManyToOne(fetch = FetchType.EAGER, optional = false)
@ManyToOne
, @OneToOne
OneToMany
, ManyToMany
⚠️ JPA에서 엔티티를 저장할 때, 연관된 모든 엔티티는 영속 상태이어야 한다!
@Getter
@Entity
public class Parent {
@Id
@GeneratedValue
private Long id;
private String name;
@OneToMany(mappedBy = "parent", cascade = CascadeType.PERSIST)
private List<Child> childeren = new ArrayList<>();
}
Child child1 = new Child();
Child child2 = new Child();
Parent parent = new Parent();
child1.setParent(parent); // 연관 관계 추가
child2.setParent(parent); // 연관 관계 추가
parent.getChilderen().addchild(child1);
parent.getChilderen().addchild(child2);
em.persist(parent);
public enum CascadeType {
ALL, // 모두 적용
PERSIST, // 영속
MERGE, // 병합
REMOVE, // 삭제
REFRESH, // REFRESH
DETACH. // DETACH
}
@Getter
@Entity
public class Parent {
@Id
@GeneratedValue
private Long id;
private String name;
@OneToMany(mappedBy = "parent", orpahnRemoval = true)
private List<Child> childeren = new ArrayList<>();
}
Parent parent = em.find(Parent.class, 1L);
parent.getChilderen().remove(0); // 자식 엔티티를 컬렉션에서 제거
// DELETE FROM CHILD WHERE ID=?
Parent parent = em.find(Parent.class, 1L);
parent.getChildren().add(child);
Parent parent = em.find(Parent.class, 1L);
parent.getChildren().remove(child);