Matelutex
Matelutex

Reputation: 2220

How to choose right cascade type for hibernate entity?

I have bidirectional mapping OneToMany and ManyToOne. In my entity OneToMany:

@OneToMany(
   mappedBy = "announcementTemplate",
   cascade = CascadeType.MERGE
)
private List<Warehouse> warehouses = new ArrayList<>();

I want only to add additional field warehouses, nothing more - I don't want to delete any Warehouse when THIS entity is removed. The question is what's the best approach in this case?

Should I use:

  1. CascadeType.ALL
  2. CascadeType.MERGE
  3. without any CascadeType

As I said, I want only to add new field warehouses to be able to display them on the frontend (without additional fetching of warehouses from database)

Upvotes: 1

Views: 1811

Answers (1)

SternK
SternK

Reputation: 13041

The cascade property of the @OneToMany annotation allows hibernate to identify which entity state should be propagated from a parent entity to a child.

Example:

Assuming that you have the following mapping:

@Entity
class Parent
{
   @OneToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST})
   private List<Child> children = new ArrayList<>();
}

and then you do:

Parent parent = new Parent();
parent.children.add(new Child());
entityManager.persist(parent);

Due to the usage of CascadeType.PERSIST in cascade you can expect that a new child will be persisted together with parent.

Then if you do something like this:

Parent parent = entityManager.find(Parent.class, 1L );
parent.name = "NewParentName";
parent.children.get(0).name = "NewFirstChildName";
entityManager.merge(parent);

So, due to the usage of CascadeType.MERGE in cascade you can expect that a child's name will be updated together with a parent's name.

Additionally (as it's stated in the documentation), the CascadeType.ALL will propagate any Hibernate-specific operation, which is defined by the org.hibernate.annotations.CascadeType enum:

  • SAVE_UPDATE - cascades the entity saveOrUpdate operation.
  • REPLICATE - cascades the entity replicate operation.
  • LOCK - cascades the entity lock operation.

So, if you are going to use else, for example, session.saveOrUpdate(parent), then CascadeType.ALL will be a right chose here.

Anyway, you should review at first the operations list that you apply to the parent and want to propagate to the child, and then based on that make your choice.

Upvotes: 1

Related Questions