Hibernate OneToOne by alternative key

Viewed 222

I have two tables in a one-to-one relationship through a non-primary key. And I am trying to map entities like this:

@Entity
public class FirstEntity implements Serializable {

    @Id
    private Long id;

    private String code;

    @OneToOne(mappedBy = "firstEntity")
    private SecondEntity secondEntity;

}

@Entity
public class SecondEntity {

    @Id
    private Long id;

    @OneToOne
    @JoinColumn(name = "first_entity_code", referencedColumnName = "code")
    private FirstEntity firstEntity;

    private String value;
}

But when I am trying to select the first entity, hibernate generates the following SQL:

select
        firstentit0_.id as id1_0_1_,
        firstentit0_.code as code2_0_1_,
        secondenti1_.id as id1_1_0_,
        secondenti1_.first_entity_code as first_en3_1_0_,
        secondenti1_.value as value2_1_0_ 
    from
        FirstEntity firstentit0_ 
    left outer join
        SecondEntity secondenti1_ 
            on firstentit0_.id=secondenti1_.first_entity_code 
    where
        firstentit0_.code=?

When I change mappings from @OneToOne to @ManyToOne and @OneToMany, like this:

@ManyToOne
@JoinColumn(name = "first_entity_code", referencedColumnName = "code")
private FirstEntity firstEntity;

@OneToMany(mappedBy = "firstEntity")
private List<SecondEntity> secondEntity;

everything works as expected. I don't understand what is wrong with the first example. Is there any way I can map bidirectional one-to-one association by non-primary key?

0 Answers
Related