Skip to content
Advertisement

One to One relationship mapping JPA SpringBoot implementation error: ids for this class must be manually assigned before calling save()

I am trying to understand the JPA Spring Boot implementation for One-to-One mapping classes and was hoping if anyone could provide me a clear picture.

  1. One to One mapping Scenario: Table foo and Table childfoo Foo has the columns foo_id,foo_name, foo_place childfoo has the columnd foo_id(foreignkey of foo table), childfoo_name

Here is the JPA entity implementation I’ve made so far:

JavaScript

ChildFoo class

JavaScript

I’ve created a repository for the Foo and I am using FooRepository.save(foo) in the controller to save the data.

Controller code to add the foo and childfoo:

JavaScript

But I am getting the error:

ids for this class must be manually assigned before calling save().

Advertisement

Answer

From your comments it appears you are trying to use a shared primary key strategy where ChildFoo will also use fooId as its own primary key.

If that’s the case, then I think you need to update some of your JPA annotations:

JavaScript

And you may need save the instance of Foo (thereby generating the shared Id) before associating and saving the ChildFoo, but I don’t think that’s necessary once everything is properly annotated.

Speaking of annotations, I only removed the lazy fetch type from your original annotations to clarify updates. You should be able to include them without any issues.

Additional useful links: Shared primary key with JPA and Spring Boot OneToOne shared primary key – JPA2.0 updates

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement