Skip to content
Advertisement

Spring JPA ManyToMany with additional table persists with null id

I have these entities:

JavaScript

My HeroService is like this:

JavaScript

I am using postman to create a new Hero and this is a sample POST request:

JavaScript

Although a hero is created and two entities on HeroSkill table are also created, the HeroSkill hero_id column is null, so my new heroes are not associated with their skills as they should be.

It works if I modify my service like this:

JavaScript

But I think that I shouldn’t have to pass the Hero manually to each HeroSkill. Isn’t that the point of adding CascateType.ALL (which includes CascadeType.PERSIST)?

What is the correct approach to that?

Thanks in advance.

Advertisement

Answer

There is no reference of Hero(Parent) in HeroSkill(child) that’s why JPA can’t resolve hero_id and set as null. Use this heroSkill.setHero(hero) to set parent in child.

To save child with parent in bidirectional relation you have to make sync both side.

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