기본 키 열에 대한 OneToOne 관계
-
21-12-2019 - |
문제
다른 하나와 onetoone 관계가있는 엔티티를 쿼리 할 때 문제가 발생합니다.이것은 시나리오입니다.
데이터베이스 테이블 :
create table people (
id decimal(10,0) NOT NULL,
email varchar(512) NOT NULL
);
create table users (
email varchar(512) NOT NULL
);
.
테스트 데이터 :
insert into users (email) values ('jhon@domain.com');
insert into users (email) values ('mary@domain.com');
insert into people (id, email) values (1, 'jhon@domain.com');
insert into people (id, email) values (2, 'mary@domain.com');
.
엔티티 :
@Entity(name = "people")
public class Person implements Serializable {
@Column
@Id
private long id;
@Column
private String email;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
@Entity(name = "tbl_users")
public class User implements Serializable {
@Id
private String email;
@OneToOne(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
@JoinColumn(name = "email", referencedColumnName = "email")
private Person person;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
.
호출 :
...
User user = entityManager.find(User.class, "jhon@domain.com");
...
.
DE 호출 후 Hibernate의 로그가 표시됩니다.
select user1_.email as email2_0_, person2_.id as id1_1_, person2_.email as email1_1_
from users user1_ left outer join people person2_ on user1_.email=person2_.id
where user1_.email=?
.
볼 수 있듯이 사용자를 비교하고 있기 때문에 조인이 잘못되었습니다 .ID ( user1_.email= person2_.id )와 함께 사용자 해당 사람
.어떻게 해결할 수있는 방법에 대한 아이디어가 있습니까?
감사합니다!
해결책
DataModel을 다시 생각해야합니다.사용자와 사람 간의 관계는 상속 중 하나와 더 많이 보입니다.
맵핑에 대한 문제가 발생할 때
JPA.제공 업체 : 왜 관계 / fks가 비 pk 열이 Hibernate 및 EclipseLink에서 작동합니까?
다른 팁
엄격하게 말하기, JPA 사양이 수행합니다.비 기본 키 열에 대한 참조가 허용되지 않습니다. .일부 JPA 구현에서 작동 할 수 있지만 적절하지는 않습니다.
그러나 나는 당신이 관계를 양방향으로 만들고, 비표준 키가 아닌 옆에있는 측면에 의해이를 수행 할 수 있다고 생각합니다.
@Entity
public class Person {
@Id
private long id;
@OneToOne
@JoinColumn(name = "email")
private User user;
public String getEmail() {
return user.getEmail();
}
public void setEmail(String email) {
// left as an exercise for the reader
}
}
@Entity
public class User {
@Id
private String email;
@OneToOne(mappedBy = "user")
private Person person;
}
.
나는 실제로 그것을 시도하지 않았지만, 그래서 경고 해커
제휴하지 않습니다 StackOverflow