我有一个使用 Hibernate 作为 ORM 实现的 Spring Data JPA 后端。
这是模型:
__________ _________________________
|Person | |MailConfig |
|________| |_______________________|
| id PK | | uid PK-FK(Person.uid) |
| uid | | ... |
| ... | | |
|________| |_______________________|
@Entity
@Table(name="Person")
public class PersonEntity{
@Id
private String id;
private String uid;
@OneToOne(mappedBy="id", fetch=FetchType.EAGER)
private MailConfigEntity mailConfigNotes;
...
}
@Entity
@Table(name="MailConfig")
public class MailConfigEntity implements Serializable{
@Id
@OneToOne
@JoinColumn(name="uid", table="Person", referencedColumnName="uid", insertable = false, updatable = false)
private PersonEntity id;
...
}
Person 表通过一个不是Person 主键的字段与MailConfig 表连接。当我使用 personDAO.findOne(id)
加载实体时,我可以看到查询中的连接是针对 person.id 而不是 person.uid(on personent0_.id=mailconfig2_.uid
)。知道为什么这不起作用吗?
查询日志:
select
personent0_.id as id8_2_,
personent0_.uid as uid8_2_,
mailconfig2_.uid as uid5_1_
from
Person personent0_
left outer join
mailconfig mailconfig2_
on personent0_.id=mailconfig2_.uid
where
personent0_.id=?
最佳答案
根据文档,检查这是否是外键
There are three cases for one-to-one associations: either the associated entities share the same primary keys values, a foreign key is held by one of the entities (note that this FK column in the database should be constrained unique to simulate one-to-one multiplicity), or a association table is used to store the link between the 2 entities (a unique constraint has to be defined on each fk to ensure the one to one multiplicity).
此外,JoinColumn 应该在关系的所有者端
关于java - JPA - 非主键字段上的@OneToOne 关系不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29670105/