JPA - @OneToOne relation on non-primary-key field not working

♀尐吖头ヾ 提交于 2020-01-17 08:19:30

问题


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;

    ...
}

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?

Query log:

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

回答1:


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

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).

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



来源:https://stackoverflow.com/questions/29670105/jpa-onetoone-relation-on-non-primary-key-field-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!