Skip to content
Advertisement

Spring boot rest api post method with oneToMany relationship

I’m new to spring and I’m building my first web app. I have an item and user entities. User could have a lot of items. So User has a list of items

JavaScript

and here’s my Item entity

JavaScript

I also created rest controller to create Item and I defined POST endpoint like this

JavaScript

here how I send request using postman enter image description here

So how I need to save this item object with that relationship? Any ideas?

Advertisement

Answer

You get this error because the User that is references is not existing in the Database the moment you save your item. What you have to do depends on how you want your application to behave.

If the user must exist before you save your item you should load the user by his name or email, reference him in the item and then save the item.

If you want to create the user while creating the item you could Cascade the user in the Item like you do with the items in the user-class. So if you want to persist the User when persisting your item try CascadeType.PERSIST

JavaScript

But even if you want to create the user while you create the item you should check beforehand if the user already exists and load him eventually.

So,

  1. cascade
  2. load user by username or email
  3. reference in item if present or leave like is if none found
  4. save item
Advertisement