I'm having problems with automatically persisting my child entity when persisting the parent. I have followed guides etc but can't seem to find where I'm making a mistake.
I have the following entities:
@Entity
@Table(name = "mp_item")
public class Item {
@BatchFetch(value = BatchFetchType.JOIN)
@OneToOne(fetch = FetchType.LAZY, mappedBy = "item", cascade = CascadeType.ALL)
private ItemGroupSuggestion itemGroupSuggestion;
}
Child:
@Entity
@Table(name = "mp_itemgroup_suggestion")
public class ItemGroupSuggestion {
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "item_id")
private Item item;
When creating a suggestion I am setting the reference to the parent, and in the parent the reference to the child, like this:
ItemGroupSuggestion suggestion = new ItemGroupSuggestion(item, itemgroups, nearestItem);
// sets this.item = item inside constructor of ItemGroupSuggestion
item.setItemGroupSuggestion(suggestion);
After setting the references, I do a batch-save:
itemService.saveAll(items);
Why are the children not getting persisted?
CodePudding user response:
Your setter in item should be as follows:
public void setItemGroupSuggestion(ItemGroupSuggestion itemGroupSuggestion) {
itemGroupSuggestion.setItem(this);
this.itemGroupSuggestion = itemGroupSuggestion;
}
CodePudding user response:
Seems like I finally got it to work, for some reason when I provided the referencedColumnName it started working. I thought that would be the default, but apparently not.
@JoinColumn(name = "item_id", referencedColumnName = "id")
private Item item;
If anyone knows why this was needed to get things working, please let me know.