title: Springboot : How to save nested associations using Spring Data JPA
body: <p>I have two models namely <strong>Company and User</strong>. <strong>A Company has many Users</strong>.
  When I save the company I need that the user be saved automatically.
  Is there a way that JPA provides to achieve such thing?</p>
  
  <p>Below are my models :</p>
  
  <p><strong>//Company Model</strong></p>
  
  <pre><code>@Entity
  public class Company {
  
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      private Long id;
  
      @NotNull
      @Size(min = 4, max = 100)
      private String name;
  
      @Size(max = 500)
      private String description;
  
      @OneToMany(mappedBy = "company",cascade = CascadeType.ALL)
      private List&lt;User&gt; users = new ArrayList&lt;&gt;();
  
      public Company(){};
  
      public Long getId() {
          return id;
      }
  
      public void setId(Long id) {
          this.id = id;
      }
  
      public String getName() {
          return name;
      }
  
      public void setName(String name) {
          this.name = name;
      }
  
      public String getDescription() {
          return description;
      }
  
      public void setDescription(String description) {
          this.description = description;
      }
  
      public List&lt;User&gt; getUsers() {
          return users;
      }
  
      public void setUsers(List&lt;User&gt; users) {
          this.users = users;
      }
  }
  </code></pre>
  
  <p><strong>//User Model</strong></p>
  
  <pre><code>@Entity
  public class User {
  
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      private Long id;
  
      @Column(length = 50, unique = true)
      @NotNull
      @Size(min = 4, max = 50)
      private String username;
  
      @Column(length = 50)
      @NotNull
      @Size(min = 8, max = 50)
      private String password;
  
      @Column(length = 50)
      @NotNull
      @Size(min = 4, max = 50)
      private String firstName;
  
      @Column(length = 50)
      @NotNull
      @Size(min = 4, max = 50)
      private String lastName;
  
      @Column(length = 50, unique = true)
      @NotNull
      @Size(min = 4, max = 50)
      private String email;
  
      private Boolean enabled;
  
      @Temporal(TemporalType.TIMESTAMP)
      @NotNull
      private Date lastPasswordReset;
  
      @Column(nullable = false, updatable = false)
      @Temporal(TemporalType.TIMESTAMP)
      @CreatedDate
      private Date createdAt;
  
      @Column(nullable = false)
      @Temporal(TemporalType.TIMESTAMP)
      @LastModifiedDate
      private Date updatedAt;
  
      @ManyToMany(fetch = FetchType.EAGER)
      @JoinTable(
              name = "user_authority",
              joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
              inverseJoinColumns = {@JoinColumn(name = "authority_id", referencedColumnName = "id")})
      private List&lt;Authority&gt; authorities;
  
      @ManyToOne(optional = false, fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
  private Company company;
  
  .... Followed by getters and setters
  }
  </code></pre>
  
  <p>So the client sends a request payload consisting of a nested JSON object something like :</p>
  
  <pre><code>"company":{  
     "name":"Evil Corp",
     "description":"test",
     "users":[  
        {  
           "userName":"xyz",
           "password":"abc"         //folllowed by other attributes
        }
     ]
  }
  </code></pre>
  
  <p>//Company Controller</p>
  
  <pre><code>@RestController
  @RequestMapping("/api/v1/company")
  public class CompanyController {
  
      @Autowired
      ICompanyService companyService;
  
      @RequestMapping(value = "/create", method = RequestMethod.POST)
      public ResponseEntity&lt;Company&gt; create(@RequestBody Company company){
          System.out.println("Request Recieved");
          company = companyService.save(company);
          return ResponseEntity.ok(company);
      }
  }
  </code></pre>
  
  <p>//Service</p>
  
  <pre><code>@Service
  public class CompanyService implements ICompanyService {
  
      @Autowired
      CompanyRepository companyRepository;
  
      @Override
      public Company save(Company company) {
          return companyRepository.save(company);
      }
  }
  </code></pre>
  
  <p>When I'm trying to save, I'm getting the following exception :</p>
  
  <pre><code>Hibernate: insert into user (company_id, created_at, email, enabled, first_name, last_name, last_password_reset, password, updated_at, username, id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  2018-03-11 15:15:57.814  WARN 7733 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 1048, SQLState: 23000
  2018-03-11 15:15:57.816 ERROR 7733 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper   : Column 'company_id' cannot be null
  2018-03-11 15:15:57.853  INFO 7733 --- [nio-8080-exec-2] o.h.e.j.b.internal.AbstractBatchImpl     : HHH000010: On release of batch it still contained JDBC statements
  2018-03-11 15:15:57.881 ERROR 7733 --- [nio-8080-exec-2] o.h.i.ExceptionMapperStandardImpl        : HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement]
  </code></pre>
  
  <p>So how can I save the nested associations?
  Do I manually need to set the company_id field in user once company is saved? I have achieved this kind of thing previously while working on <strong>Rails</strong>. Do such thing exists on Spring Boot as well?</p>