java - JPA - 非主键字段上的@OneToOne 关系不起作用

标签 java hibernate jpa spring-data-jpa one-to-one

我有一个使用 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/

相关文章:

java - 在 Java 中,当你有一个未指定可见性关键字的方法时会发生什么?

java - 如何在 Jenkins 执行期间管理每个构建的特定文件?

java - netty http 请求 getContent 有时会在正文中给出标题

performance - 来自 Hibernate App 的查询不使用数据库索引

java - 更新配置有删除孤儿 : can't save the parent object 的集合时出现 HibernateException

java - JPA - Eager - Lazy 最佳实践

jpa - 在eclipselink中启用静态编织

java - 如何使用 Play Framework 上传多个文件?

jpa - 从 EntityManager 获取 JDBC 连接

java - ParameterizedType 和创建通用 dao