JPA - 非主键字段的@OneToOne关系不起作用 [英] JPA - @OneToOne relation on non-primary-key field not working

查看:1577
本文介绍了JPA - 非主键字段的@OneToOne关系不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用Hibernate作为ORM实现的Spring Data JPA后端。

I have a Spring Data JPA backend using Hibernate as the ORM implementation.

这是模型:

This is the model:

 __________     _________________________
 |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;

    ...
}

人员表格与MailConfig表中的字段不是Person的主键。当我使用 personDAO.findOne(id)加载实体时,我可以看到查询中的连接是针对person.id而不是person.uid( on personent0_.id = mailconfig2_.uid )。任何想法为什么这不起作用?

Person table is joined with MailConfig table through a field that is not Person's primary key. When I load an entity using personDAO.findOne(id) I can see the join in the query is performed against person.id instead of person.uid (on personent0_.id=mailconfig2_.uid). Any idea why this isn't working?

查询日志:

    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=?


推荐答案

根据文档,检查这是否是外来的key

As per the documentation, check if this is a foreign key


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

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应位于关系的所有者一方

Also the JoinColumn should be on the owner side of the relationship

这篇关于JPA - 非主键字段的@OneToOne关系不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆