sonoerin
sonoerin

Reputation: 5175

spring data jpa @OneToMany child id not updating

Using Spring data & boot 1.3.0.BUILD-SNAPSHOT with MySQL I have a parent & child relationship:

parent:

@Entity
public class CustomerSearchResults {

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   public Long customerSearchResultsId;

   @OneToMany(mappedBy = "customerSearchResults", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
   @Fetch(value = FetchMode.SUBSELECT)
   private List<CustomerResult> customerAAAAList;

   @OneToMany(mappedBy = "customerSearchResults", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
   @Fetch(value = FetchMode.SUBSELECT)
   private List<CustomerResult> customerBBBBList;

   @OneToMany(mappedBy = "customerSearchResults", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
   @Fetch(value = FetchMode.SUBSELECT)
   private List<CustomerResult> customerCCCCList;
    ....
 }

child:

@Entity
public class CustomerResult {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL, optional = false)
    @JoinColumn(name = "customerSearchResultsId", nullable = false)
    private CustomerSearchResults customerSearchResults;
       ....
}

The parent can have multiple lists of the same child type. I do not have any foreign keys defined in this or any other of my successful @ManyToOne examples.

I create the results like this:

CustomerSearchResults customerSearchResults = new CustomerSearchResults();
customerSearchResults.setCustomerAAAAList(anArrayList);
customerSearchResults.setCustomerBBBBList(anArrayList);
customerSearchResults.setCustomerCCCCCList(anArrayList);
customerResultsRepository.save(customerSearchResults);

No errors are thrown and I get the CustomerSearchResults inserted into that table, and the correct CustomerResult records are inserted into that table. The only problem is the CustomerResults.customerSearchResultsId is null, despite it being declared as not null

Here is how I create the tables via liquibase:

 <createTable tableName="CustomerSearchResults">
     <column name="customerSearchResultsId" type="bigint" autoIncrement="true">
           <constraints primaryKey="true"/>
     </column>
    ...
  </createTable>

 <createTable tableName="CustomerResult">
     <column name="id" type="bigint" autoIncrement="true">
          <constraints primaryKey="true"/>
      </column>
      ...
      <column name="customerSearchResultsId" type="bigint"/>
  </createTable>

Why would the ref id customerSearchResultsId in the child field not be populated like this?

Upvotes: 1

Views: 1596

Answers (1)

CornePlas
CornePlas

Reputation: 41

nullable = false is only used for schema generation, it doesn't do anything while inserting data. You need to set the property on both ends of the relationship, so each entry in your 'anArrayList' must set the customerSearchResults you just created.

Upvotes: 3

Related Questions