Is there any difference between saving an entity on the owner side or on the other side if PERSIST cascade type is used on the relation?
@Entity
public class Slot {
@OneToOne(mappedBy = "slot", cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
private Cartridge cartridge;
}
@Entity
public class Cartridge {
@OneToOne(cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
private Slot slot;
}
Question:
slot.setCartridge(cartridge);
slot.save();
vs.
cartridge.setSlot(slot)
cartridge.save();
slot.save() or cartridge.save() don’t seem to be the same…
both entites are already saved. I just wanted to set the relation between them.
Cartridge owns the relationship, that means the cartridge.slot value must be set for the foreign key to be updated in most providers. The JPA spec also states that you should maintain both sides of a bidirectional relationship to keep them in synch with what is in the database -so if your setCartridge is not setting the other side of the relationship somehow as well, when you next read the cartrige, it may not have a slot set. JPA did away with relationship maintanace from the old EJB spec, making entities behave more like regular java objects as much as possible.
You should call something like:
And then save on either slot or cartridge – it doesn’t mater since the merge will cascade to the referenced object in either direction.