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
Try the cascade
element for the annotation.
@OneToMany(fetch=FetchType.LAZY, mappedBy="user", cascade=CascadeType.PERSIST)
private List<Address> addresses;
The documentation says that by default no operation is cascaded. It also states that the cascade operation is optional, so it really depends on the implementation that you are using.
Also, while setting the relationship, make sure you set both sides of the relationship. Set addresses to the user and user to the addresses.
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<Address> addresses;
or just tell JPA to cascade every operation:
@OneToMany(fetch=FetchType.LAZY, mappedBy="user", cascade = CascadeType.ALL)
private List<Address> 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).
You are using a oneToMany annotation. From my understanding you have to persist the parent class (the USer) when you want to add a child class (Address) to it.
By persisting the User class, you do let know JPA know which row to update.