Hibernate one-to-one loose relationship

I have a Table say product and other say product_external
product (id – primary key, product_unique_id – unique kie)




Both tables are loosely coupled, product_external comes from other system so we don’t have any authority over that (still table is in our DB).

This is my relation in java hibernate

class Product{
       // id column and other fields
     private String productUniqueid;

     @OneToOne(fetch = FetchType.EAGER, optional = true)
     @JoinColumn(updatable = false, insertable = false, name="product_unique_id")
     private ProductExternal external;


class ProductExternal{
     private String productUniqueId;

     private String otherColumnData;

Since we don’t have any control over product_external we don’t have foreign key relation of product_unique_id.

When I try to get product with id 1, it is working properly because it will have product_unique_id in both tables.

But when I try to get product with id 2, it gives me error that no row with P988 available in product_external table.

I understand this error, it is because of one to one relation’s key is not null in product table and there is no row in product_external.

But is there a way to map this where it work even if no row is there on other table?

Source: java

Leave a Reply