当我查询与另一个实体具有 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");
...
调用后,休眠的日志显示:
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=?
如您所见,连接是错误的,因为将 users.email 与 people.id ( user1_.email=person2_.id ) 进行比较,因此它返回的User没有对应的Person。
关于如何解决它的任何想法?
非常感谢 !!