3

I am developing a Rest API which will receive a JSON. I need to save the JSON correctly in a Postgres DB.

Right now I have:

@Entity
public class Customer {
    @Id
    @GeneratedValue(strategy = AUTO)
    private Long id;
    private String name;
    @OneToMany(mappedBy = "customer", cascade = ALL)
    private List<Address> address;
}

And

@Entity
public class Address {
    @Id
    @GeneratedValue(strategy = AUTO)
    private Long id;
    private String city;
    private String number;
    private String country;
    @ManyToOne
    @JoinColumn(name = "customer_id", nullable = false)
    private Customer customer;
}

My controller has only this:

@RequestMapping(method = POST)
public ResponseEntity create(@RequestBody Customer customer) {
    Customer customerSaved = repository.save(customer);
    return new ResponseEntity(customerSaved, CREATED);
}

When I send a JSON like:

{
   "name":"A name",
   "address":[
      {
         "country":"Brazil",
         "city":"Porto Alegre",
         "number":"000"
      }
   ]
}

I was expecting that the table Customer would have the name and table Address would have the three properties plus the customer_id. But the customer_id right now is null.

Any thoughts?

Suresh A
  • 1,178
  • 2
  • 10
  • 21
Lucas Beier
  • 621
  • 1
  • 7
  • 19
  • 1
    Yes, you need to set the address.customer field, and not leave it null. – JB Nizet Apr 06 '17 at 06:33
  • If you're using Jackson for the JSON conversion, you could use the `JsonManagedReference` and `JsonBackReference` annotations to automatically set the reference automatically, instead of manually. – coladict Apr 19 '17 at 19:22

1 Answers1

4

Change the setter method of List address like below:

public void setAddress(Set<Address> address) {

        for (Address child : address) {
            // initializing the TestObj instance in Children class (Owner side)
            // so that it is not a null and PK can be created
            child.setCustomer(this);
        }
        this.address = address;
    }

Hibernate - One to many relation - foreign key always "null"

Community
  • 1
  • 1
Elias
  • 664
  • 2
  • 11
  • 23