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

2019-08-30 04:48发布

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条回答
劳资没心,怎么记你
2楼-- · 2019-08-30 05:23

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

查看更多
登录 后发表回答