https://www.baeldung.com/jpa-one-to-one#1-modeling-with-a-shared-primary-key
위의 자료를 이용해 만들었습니다.
ERD

user_profile 테이블이 uid를 PK이자 FK로 가지고 있습니다.
user_profile 테이블
@Entity
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserProfile {
@Id
private String uid;
@Column(nullable = false, length = 256)
private String filePath;
@Column(nullable = false, length = 12)
private String nickname;
@Column(nullable = false)
private boolean hasSurveyed;
@OneToOne
@MapsId
@JoinColumn(name = "uid")
private UserAuth userAuth;
}
@MapsId를 이용해 외래키에 매핑한 연관관계를 기본키에도 매핑한다고 명시합니다.
@JoinColumn을 이용해 현재 테이블의 uid 컬럼과 조인합니다.
이렇게만 하면 단방향 관계를 만들 수 있습니다.
양방향 관계를 만들기 위해 user_auth 엔티티도 만들어 보겠습니다.
user_auth 테이블
@Entity
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserAuth {
@Id
private String uid;
@Column(nullable = false, length = 32)
private String email;
@Column(nullable = false, length = 25)
private String emailCompany;
@Column(nullable = false, length = 128)
private String authToken;
@OneToOne(mappedBy = "userAuth", cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn
private UserProfile userProfile;
}
@OneToOne mappedBy를 통해 UserProfile 테이블의 userAuth와 연결시킵니다.
@PrimaryKeyJoinColumn은 현재 테이블의 PK를 상대 테이블의 FK로 설정하는 것을 명시합니다.
'Backend > JPA' 카테고리의 다른 글
[ERROR] org.hibernate.AssertionFailure: null identifier (0) | 2021.09.20 |
---|