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)

`id`,`product_unique_id`,`other_columns`
________________________________________
1|'P1'|'abc'
2|'P988'|'xys'

product_external

`product_unique_id`,`other_columns`
___________________________________
'P1'|'werwer'

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
Product.java

class Product{
       // id column and other fields
     @Column(name="product_unique_id")
     private String productUniqueid;

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

ProductExternal.java

class ProductExternal{
     @Id
     @Column(name="product_unique_id")
     private String productUniqueId;

     @Column(name="other_column_data")
     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

This site uses Akismet to reduce spam. Learn how your comment data is processed.