title: Get Id of the associated object after save
body: <p>There is simple model of associated entities:</p>
  
  <p>MainModel class</p>
  
  <pre><code>@Entity 
  @Table(name = "main_model")
  public class MainModel 
  {
      @Id 
      @GeneratedValue(strategy = GenerationType.IDENTITY) 
      private long id;
  
      @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
      @JoinColumn(name = "id_main_model", referencedColumnName = "id")
      private List&lt;AssociatedModel&gt; am_collection;
  
      public MainModel() { }
  
      public long getId()
      {
          return this.id;
      }
  
      public void addAssociated(AssociatedModel am)
      {
          am_collection.add(am);
      }
  }
  </code></pre>
  
  <p>AssociatedModel class</p>
  
  <pre><code>@Entity 
  @Table(name = "associated_model")
  public class AssociatedModel
  {
      @Id 
      @GeneratedValue(strategy = GenerationType.IDENTITY) 
      private long id;
  
      public AssociatedModel() { }
  
      public long getId()
      {
          return this.id;
      }
  }
  </code></pre>
  
  <p>Simplest jpa repository for MainModel</p>
  
  <pre><code>public interface MainModelDAO extends JpaRepository&lt;MainModel, Long&gt;  
  {
  }
  </code></pre>
  
  <p>and finally, controller's method for creating and saving AssociatedModel instance</p>
  
  <pre><code>@RequestMapping("/url")
  public String createAssociated(@RequestParam("id_mainmodel") long id_mainmodel, @RequestBody AssociatedModel newAm) 
  {
      MainModel mm = MainModelDAOobject.findOne(id_mainmodel);// MainModelDAOobject - @Autowired
      mm.addAssociated(newAm);
      MainModelDAOobject.saveAndFlush(mm);
      return String.valueOf(newAm.getId());// get Id of associated saved object
  } 
  </code></pre>
  
  <p>Associated obect saves into database correctly, but <strong>id</strong> value of this object, allowed by its <code>getId()</code> method, always <strong>zero</strong>. How can I get Id of the saved associated object correctly?</p>