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

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

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

    @NotBlank
    private String name;

    private String img;

    @NotBlank
    @Column(unique = true)
    private String email;

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

// getters and setters

}

and here’s my Item entity

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

    @JsonIgnore
    @JsonManagedReference
    @ManyToOne
    @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

@PostMapping("/item")
    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?

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

@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.

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


Source: stackoverflow