title: How to save data-from-parent-to-child-tables-based-on-entities-in-spring-jpa
body: <p>I have a table master table user ,topics table and comments table
  where in for a single topic there can be multiple comments</p>
  
  <p>user table will be already populated.
  I will get a post request to save the topic with structure like below</p>
  
  <pre><code>{  
     "topicId":"T001",
     "title":"stackoverflow",
     "commentBeans":[  
        {  
  "comment":"developer platform"
        },
  
        {  
  "comment":"developer communtiy"
        }
     ]
  }
  </code></pre>
  
  <p>Frameworks used:
  spring boot
  JPA
  DB : postgressql</p>
  
  <p>I am able to save the data the traditional way (i.e get the request and save topic bean first. get the primarykey from saved entity and loop the list of commentbean where user num will be set dynamically by another get service and save them)</p>
  
  <p>I wanted to know if there is anyway to save the data with single save query.</p>
  
  <pre><code>@Entity
  @Table(name ="user")
  public class User implements Serializable {
  
      @Id
      @Column(name = "user_num")
      @GeneratedValue(strategy = GenerationType.AUTO)
      private Long userNum;
  
      @Column(name = "user_id")
      private String userId;
  
      @Column(name = "username")
      private String userName;
  
  }
  
  @Entity
  @Table(name = "topics")
  public class TopicBean implements Serializable {
  
      @Id
      @Column(name = "topic_num")
      @GeneratedValue(strategy = GenerationType.AUTO)
      private Long topicNum;
  
      @Column(name = "topicId")
      private String topicId;
      @Column(name = "title")
      private String title;
  
      @OneToMany(mappedBy="topicBean")
      private List&lt;CommentBean&gt; commentBeans;
  }
  
  @Entity
  @Table(name = "comments")
  public class CommentBean implements Serializable {
  
      @EmbeddedId
      private CommentBeanKey key;
  
  
      @Column(name = "comment")
      private string comment;
  
      @ManyToOne
      @JoinColumn(name="topic_num")
      private TopicBean topicBean;
  
      @ManyToOne
      @JoinColumn(name="user_num")
      private TopicBean topicBean;
  
  }
  
  @Embeddable
  public class CommentBeanKey implements Serializable{
  
      private static final long serialVersionUID = 5889249943605061539L;
  
      @Column(name ="topic_num")
      private Long topicNum;
  
      @Column(name ="user_num")
      private Long userNum;
  
  
  }
  </code></pre>
  
  <p>I saw the below link and am little worried if am doing the wrong way. any help is appreciated.</p>
  
  <p><a href="https://thoughts-on-java.org/hibernate-tips-how-to-map-an-entity-to-multiple-tables/" rel="nofollow noreferrer">https://thoughts-on-java.org/hibernate-tips-how-to-map-an-entity-to-multiple-tables/</a></p>