Search code examples
javahibernatejpapersistence

Which side of bidirectional mapping should be persisted


I was looking for an answer on SO and several articles, but I think clear explanation is unfortunately missed, so I decided to ask.

Say we have two entities (box contains several items):

@Entity
@Table(name = "box")
class Box
{
    @Id
    private Long id;

    @OneToMany(mappedBy = "box")
    private List<Item> items = new LinkedList<>();
    
    public void addItem(Item item)
    {
        items.add(item);
        item.setBox(this);
    }
    // setters, getters, delete synchronize method
}
@Entity
@Table(name = "item")
class Item
{
    @Id
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "box_id")
    private Box box;

    // setters getters
}

Which side of the relationship should I persist?

  1. Does it depend on the owning side of the relationship?
  2. Does it depend on the cascade type and owning side has nothing in common?
    1. Place CascadeType.PERSIST in the Box entity, then em.persist(box)
    2. Place CascadeType.PERSIST in the Item entity, then em.persist(item)
    3. Both, and persist is up to me - can be em.persist(box) or em.persist(item)

Solution

  • You can persist the relationship from both sides.

    If you persist the box entity, you will only have to call the persist method of the entity manager once and pass the box entity as a parameter, with the item entity list, the box items parameter will have to have a cascade type.

    If you persist the item entity, you will have to call the persist method of the entity manager N times, being N the number of items, passing the Item entity with the box parameter, the box parameter will have to have a cascade type. In the first insertion Box will not have ID, but once you insert the first Item, Box will have ID so in the following N-1 Items you will have to establish that Box with Id since if not, it will create N boxes.

    Based on all this I think that in most logics it is better to persist the parent entity, cob cascade type persist in the property that represents the relation with the daughter class.