0

I'm learning Hibernate and faced a question: what is the difference between mappedBy and CascadeType.ALL?

We use mappedBy on the owning side in order to eliminate excessive persistence. For instance, with mappedBy we can replace

a.addB(b);
b.setA(a);

with

a.addB(b);

in a case of ONE-TO-MANY relationship between A and B, and MANY-TO-ONE between B and A (bidirectional).

Why do we need CascadeType in this case?

Pasha
  • 1,768
  • 6
  • 22
  • 43
  • 2
    No, that's not, at all, what mappedBy is for. mappedBy is necessary to tell what the owner side of the bidirectional association is. And the owner side of a OneToMany/ManyToOne **must** be the Many side. And you **must** set the owner side, so `a.addB(b)` will **not** work (unless the method calls `b.setA(this)`. – JB Nizet Aug 26 '18 at 22:27

1 Answers1

2

The CascadeType option tells hibernate which operations to also execute on B when executed on A.
If you for example persisted A without setting CascadeType.Persist, B would not be persisted.
The mappedBy option on the other hand creates a bidirectional relationship, with A being represented by a foreign key in the table of B.
If you actually need CascadeType.ALL depends on your use-case, it allows you to think of the relationship between A and B as a composition, with A owning B.

cype
  • 96
  • 4