【问题标题】:JPA - @OneToOne relation on non-primary-key field not workingJPA - 非主键字段上的@OneToOne 关系不起作用
【发布时间】:2015-06-22 14:05:43
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    根据文档,检查这是否是外键

    一对一关联有三种情况: 关联实体共享相同的主键值,外键 由其中一个实体持有(请注意, 数据库应该被限制唯一以模拟一对一 多重性),或者使用关联表来存储链接 在 2 个实体之间(必须在每个实体上定义一个唯一约束 fk 以确保一对一的多重性)。

    JoinColumn 也应该在关系的所有者方面

    【讨论】:

    • 所以...您的意思是 OneToOne 关联不支持加入非主键?
    • @WornOutSoles - 是的,我相信,您可以查看有关 oneToOne 注释的文档:docs.jboss.org/hibernate/stable/annotations/reference/en/…
    • 我不同意,它似乎得到了支持。从您链接的文档中,第 2.2.5.1 节。一对一:Note that when using referencedColumnName to a non primary key column, the associated class has to be Serializable. Also note that the referencedColumnName to a non primary key column has to be mapped to a property having a single column (other cases might not work).
    猜你喜欢
    • 1970-01-01
    • 2015-03-10
    • 1970-01-01
    • 1970-01-01
    • 2016-05-26
    • 2021-01-01
    • 2012-01-06
    • 2023-03-12
    • 1970-01-01
    相关资源
    最近更新 更多