0
votes

When I read about cascade and inverse it is said that both are doing totally separate things. Cascade: In cascade, after one operation (save, update and delete) is done, it decide whether it need to call other operations (save, update and delete) on another entities which has relationship with each other. Inverse: This is used to decide which side is the relationship owner to manage the relationship (insert or update of the foreign key column).

Lets say i save parent that has some children. So when i set one-to-many with inverse="true" cascade="all" on one hand I want that child is owner of the relationship, so saving parent should change children collection, however when I add cascade="all" hibernate would change this behaviour and persist children.

So how they are different if cascade changes behaviour of inverse?

1
What is your question?JB Nizet
so how they are different if cascade changes behaviour of inverse?user1308908

1 Answers

1
votes

Let's take an example:

  • one Order has many Lines: OneToMany association
  • Many Lines share one parent Order: ManyToOne association

The owner side is Line. The inverse side is Order.

That means that if you persist an Order, persist a Line, add the line to the collection Order.lines, but don't set Line.order, Hibernate will consider that no association exists between those two entities. Why? Because you only set the inverse side of the association (Order.lines), and not the owner side (Line.order).

Cascade has nothing to do with this. Let's say Order.lines is annotated with cascade=PERSIST. That means that if you create an Order, create a Line, add the Line to Order.lines, and persist the Order, Hibernate will also automatically call persist() on the Line. The Line will thus be persisted without having to explicitely call persist() with this line. But the association between the two entities still won't be saved in the database, because you still haven't set the owner side of the association: Line.order.