JPA OneToMany persist with CascadeType.ALL doesn't persist child

前端 未结 1 361
生来不讨喜
生来不讨喜 2021-01-17 01:48

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

相关标签:
1条回答
  • 2021-01-17 02:30

    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.

    0 讨论(0)
提交回复
热议问题