I have a JPA problem with @OneToMany and specifically with the functionality of CascadeType.ALL. I have two entities, a father and a child.
I show you an example of what I have: BOOK
@Entity
@Table(name = "books")
public class Book implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
@JoinColumn(name="id_page")
private List<Page> pages;
...
...
}
PAGE
@Entity
@Table(name = "pages")
public class Page implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Column(name = "id_book")
private int idBook;
...
...
}
So, I just have a book and several pages. When I save the book, I also save the pages contained within it thanks to the CascadeType.ALL. Which works, actually Hibernate tries to save the Book object, realizes with OneToMany that there is also the Page entity to save and starts the query thanks to Cascade ALL.
I simply do:
bookRepository.save(book);
The json representing the book I want to save is something like this:
{
"id": 0,
"page": [
{
"id": 0,
"idBook": 0
}
]
}
But, if I put 0 to the book id, it is created. If I put 0 on the idBook into the page, it gives me an error like this: Key (id_book) = (0) is not present in table "book".
But, the thing I really don't understand is: why if I put an id_book in the json that exists on the DB, then finished saving the book entity, it understands what the id is and inserts it correctly on the DB?
So, if I give this JSON.
{
"id": 0,
"page": [
{
"id": 0,
"idBook": 1
}
]
}
And let's consider that on the DB there is only one book with id=1. After saving it generates me a line that has id=2 for the book, and a page linked to the book with id=2?
This thing drives me crazy. If give an idBook = 0 to tell him he has to retrieve / generate it, he tells me that it doesn't exist. If, on the other hand, I give him an idBook that really exists (but it's not correct), does he not even consider it and correctly use the idBook of the Book he just created?
I would simply like not to have to use bogus idBook, tell him he has to take the page idBook after creating the book, exactly like he actually does.