I am trying to better familiarize myself with JPA so I created a very simple project. I have a User Class and an Address class. It appears that I have to persist both even tho
What you're talking about it's called Cascading. That means doing the same action to nested objects, such as an Address
in your User
. By default, there is no cascading at all if you don't specify any CascadeType
.
You can define various cascade types at once
@OneToMany(fetch=FetchType.LAZY, mappedBy="user", cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
private List addresses;
or just tell JPA to cascade every operation:
@OneToMany(fetch=FetchType.LAZY, mappedBy="user", cascade = CascadeType.ALL)
private List addresses;
Both ways will result in, for example, a persisted Address
while persisting an User
or the deletion of the associated Address
when an User
is removed.
But!... if you remove CascadeType.REMOVE
from the first example, removing an User
won't remove its associated Address
(The removal operation won't be applied to nested objects).