외래키 / hibernate / join / spring boot / spring / java / orm / 연결 / 관계 설정 / relation entity
JPA 의 entity 로 foreign key 설정하는 법
user table 의 profile_id 가 profile table 의 id 를 참조하도록 하는 예시이다.
아래 code example 이 있다.
import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToOne;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "profile_id", referencedColumnName = "id", nullable=false)
private Profile profile;
...
}
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.OneToOne;
import java.time.LocalDateTime;
@Entity
public class Profile {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToOne(mappedBy = "profile")
private User user;
create table user (id bigint not null auto_increment, profile_id bigint not null, primary key (id)) engine=InnoDB;
create table profile (id bigint not null, primary key (id)) engine=InnoDB;
alter table user add constraint FKl6pykqur53o90qdnhjko0r8ni foreign key (profile_id) references profile (id);
어느 값이 어느값을 가리키는지는 아래 그림을 참고하자.
댓글 없음:
댓글 쓰기