How to create unidirectional relationship from non owning entity of relation in one to one relationship

I have two entity in the model like Order and BankDetail. Order is composite with BankDetail with one to one association.

`Database tables

table_order(id, …)
table_bank_detail(id,order_id, …)
`

Unidirectional model :

@Entity
Class Order {
    @Id
    @Column(name = "id")
    private Long id;


    @OneToOne
    @JoinColumn(name = "id", referencedColumnName = "order_id")
    private OrderBankDetail bankDetail;
}

Class BankDetail {

    @Id
    @Column(name = "id")
    private Long id;

}

It seems not working and I can’t find order bank detail.It seems it used order.id to find entry in table table_bank_detail with table_bank_detail.id field

And the same approach works in one to many relationship.

If it’s a true one-to-one association, the PK should be shared so you don’t need both I’d and order_is in bank_detail.

Check out this article for more details about using @MapsId to share the PK as you should.

I have legacy database which is used by other application also.
Is there any way to achieve that without sharing primary key in both tables as that would require db schema change.

Is there any way to achieve that without sharing primary key in both tables as that would require db schema change.

Of course, there is. But you have to use a bidirectional association.

@Entity
Class Order {
    @Id
    private Long id;


    @OneToOne(mappedBy = "order")
    private OrderBankDetail bankDetail;
}

Class BankDetail {

    @Id
    private Long id;
  
    @OneToOne
    private Order order;
}