gpt4 book ai didi

java - 非主键列的一对一关系

转载 作者:搜寻专家 更新时间:2023-10-31 20:34:41 25 4
gpt4 key购买 nike

当我查询与另一个实体具有 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");
...

取消调用后,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=?

如您所见,连接是错误的,因为比较 users.email 和 people.id (user1_.email=person2_.id),因此它返回一个 User 没有相应的

关于如何修复它有什么想法吗?

非常感谢!!

最佳答案

严格来说,the JPA specification does not allow references to non-primary key columns .它可能适用于某些 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;

}

不过,我还没有实际尝试过,所以警告黑客

关于java - 非主键列的一对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20041215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com