I\'ve got the question about using JPA with OneToMany relationship (bidirectional) along with CascadeType.ALL. Basing on vlad post (https://vladmihalcea.com/a-beginners-guid
You're mixing two very different concepts.
A CascadeType
deals with what actions cascade to relations. When specifying CascadeType.ALL
, you are telling the persistence provider that whenever you persist, merge, or remove that entity, those actions are to be replicated to the relations.
But in order for cascade operations to work, you must first make sure that the relationship is managed correctly. If you look at Vlad's post, you'll notice two very important methods on Post
.
public void addDetails(PostDetails details) {
this.details = details;
details.setPost( this );
}
public void removeDetails() {
this.details.setPost( null );
this.details = null;
}
These methods make sure that the relationship between a PostDetails
and a Post
is properly maintained based on your requirements. So assuming the following mapping:
public class Post {
@OneToOne(cascade = CascadeType.ALL, mappedBy = "post", orphanRemoval = true)
private PostDetails details;
}
You could perform the persistence operation of both of them as follows:
PostDetails details = new PostDetails();
details.setUser( currentUser );
Post post = new Post();
post.addDetails( details );
session.persist( post );
You notice I used the addDetails
rather than the typical setDetails
because I wanted to make sure that the relationship between Post
and PostDetails
was initialized.
Hope that helps.