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

@Table(name = "user")
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"}, allowGetters = true)
public class User implements Serializable {

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

    private String name;

    private String img;

    @Column(unique = true)
    private String email;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    private List<Item> items;

// getters and setters


and here’s my Item entity

@Table(name = "item")
public class Item implements Serializable {
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @JoinColumn(name = "user_id")
    private User user;
   // setters and getters

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

    public Item createNote(@Valid @RequestBody Item item) {
        return itemRepository.save(item);

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?


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

@ManyToOne(cascade = CascadeType.PERSIST)
private User user;

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.


  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

Source: stackoverflow