How to persist One-to-One Hibernate with shared primary Key

Solution for How to persist One-to-One Hibernate with shared primary Key
is Given Below:

I have following one-to-one relationship:

@Entity
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    ...

    @OneToOne(mappedBy = "product", cascade = CascadeType.ALL)
    @PrimaryKeyJoinColumn
    private Book book;

}

and

@Entity
public class Book {

    @Id
    private Long id;

    ...

    @OneToOne
    @MapsId
    @JoinColumn(name = "product_id")
    private Product product;
}

Now I have a function that returns a product already having a book and want to persist it with an entityManager in a transaction. So I call product.getBook().setProduct(product) and want to persist both with entityManager.save(product).

But it says org.hibernate.exception.ConstraintViolationException id of book is violating Not-Null-Constraint

The method beeing called for saving the entities is annotated with @Transactional if that helps.

Why does hibernate not generate the ids?

Every bidirectional association must have one owning side only (the child side), the other one being referred to as the inverse (or the mappedBy) side. You should remove @PrimaryKeyJoinColumn annotation from the Product.book:

@Entity
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    // ...

    @OneToOne(mappedBy = "product", cascade = CascadeType.ALL)
    private Book book;
}

as this annotation uses only on the owning (not mappedBy) side.

And whenever a bidirectional association is formed, the application developer must make sure both sides are in-sync at all times. So, you should do something like this:

Product product = new Product();
Book book = new Book();
// ...
product.setBook(book);
book.setProduct(product);
entityManager.save(product);