I'm trying to understand how Spring JPA works in creating (POST http action) resources under relationships (@OneToMany).
I have 2 simples classes, Product
and Comment
. One product
is related to many comments
.
Product class :
@Entity
@Table(name = "product")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "product_id")
private int productId;
@Column(name = "name")
private String name;
@Column(name = "description")
private String description;
@OneToMany(cascade = { CascadeType.PERSIST})
@JoinColumn(name = "product_id")
private List<Comment> comments;
... getters and setters are also implemented
}
Comment class :
@Entity
@Table(name = "comment")
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "comment_id")
private int commentId;
@Column(name = "content")
private String content;
@Column(name = "product_id")
private int productId;
... getters and setters
}
I implemented this @OneToMany relationship as unidirectional, on purpose, just to understand how it works.
I also made basic controller and repository classes for both resources.
What I am trying to understand is, when I send a Post request (using postman) to "/products"
with a new product and its new comments at the same time as below :
I dont understand why I'm getting an error 500 from hibernate that successfully created the new product but did not for the comment because the comment is missing the foreign key.
Of course I the get issue here. But since my relationship is unidirectional from the product, it should mean the product is leading the relation. So spring should synchronize the persisting operation (I added CascadeType.PERSIST
), based on the product. In my request body, the product's comments list
is filled with two new comments. This is supposed to set the comments list
of the product and tell to hibernate that this product has two new comments
.
So my question is, why doesnt hibernate create the product then get the new id of this product and then create the two new comments with a foreign key set to this new product id ?
Thank you for all your help.