I am learning Hibernate and just read the chapter “7.2.3 Adding columns to join tables” of the “Java Persistance with Hibernate” book. My goal is to save Item, Category and CategorizedItem in one transaction.
There is a constructor there (page 305):
public CategorizedItem(String username, Category category, Item item) {
// Set fields
this.username = username;
this.category = category;
this.item = item;
// Set identifier values
this.id.categoryId = category.getId();
this.id.itemId = item.getId();
// Guarantee referential integrity
category.getCategorizedItems().add(this);
item.getCategorizedItems().add(this);
}
It accepts category and item objects. If I create a Category and an Item and want to connect them with this technique, they obviously have to be persisted BEFORE, as category.getId() and item.getId() return null.
Is there “a trick in the Hibernate bag” that can cascade the saving of a join table? The join table have additional columns. I want to save all three objects in the onSuccess handler in my web page controller. All three entities or none of them must be inserted.
You said
Is there a trick in the Hibernate bag that can cascade the saving of a join table ?
Yes, use MutableInt
Here goes Category
And Item
Now because you need categoryId and itemId before saving CategorizedItem, do as follows
Notice the cascading just works when you have either a saved Category or a saved Item. Otherwise, you need to follow the approach shown above