디자인너 코딩하기

1:1 연관관계 본문

spring/연관관계

1:1 연관관계

designercoding 2022. 4. 24. 19:38

관계형 DB에서 특정Table의 PK를 다른Table FK(Foreign Key)로 활용하여 연결

 

Contributors: Linda DeMichiel

 

외부 키 열을 매핑하는 일대일 연결(종속관계)

종속관계

Customer class

@OneToOne(optional=false)
@JoinColumn(name="CUSTREC_ID", unique=true, nullable=false, updatable=false)
public CustomerRecord getCustomerRecord() { 
      return customerRecord; 
}

 

CustomerRecord class

@OneToOne(optional=false, mappedBy="customerRecord")
public Customer getCustomer() { 
	return customer; 
}

optional = false

관계 연결에 있어 선택요소여부. false로 설정 → Null이 아닌 관계가 항상 존재해야 함

 

mappedBy = "customerRecord"

관계연결에 있어 종속관계를 나타내는 필드로 종속되는 필드에만 표시

 


동등한 1:1 관계

Employee class

@Entity
  public class Employee {
    @Id Integer id;

    @OneToOne @MapsId
    EmployeeInfo info;
    ...
  }

EmployeeInfo class

@Entity
  public class EmployeeInfo {
    @Id Integer id;
    ...
  }

 


 

엠베디드형 1:1 관계

@Entity
public class Employee {
  @Id int id;
  @Embedded LocationDetails location;
  ...
}

@Embeddable
public class LocationDetails {
  int officeNumber;
  @OneToOne ParkingSpot parkingSpot;
  ...
}

@Entity
public class ParkingSpot {
  @Id int id;
  String garage;
  @OneToOne(mappedBy="location.parkingSpot") Employee assignedTo;
  ... 
}

fetch( )

FetchType fetch() default EAGER

가급적으로 Lazy로딩을 사용해야 함

EAGER 로딩의 문제점

  • 예상치 못한 SQL 발생
  • JPQL에서 N+1 문제 발생

Lazy로딩 문제의 해결

  • JPQL fetch join
  • entity Graph

 

optional = false

관계 연결에 있어 선택요소여부. false로 설정 → Null이 아닌 관계가 항상 존재해야 함

true이면 SQL에서 left outer join으로 처리

false이면 SQL에서 inner join으로 처리

 


StackOverFlowError

tostring 메서드 등에서 순환참조에러

relationship을 단방향으로 처리하거나 tostring에서 제외

  @OneToOne(mappedBy = "book")
  @ToString.Exclude
  private BookReviewInfo bookReviewInfo;

 

반응형