2017-04-06 55 views
1

我正在開發一個Rest API,它將收到一個JSON。我需要將JSON正確保存在Postgres數據庫中。JPA ManyToOne/OneToMany不插入值的孩子

現在我有:

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

而且

@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; 
} 

我控制器只有這個:

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

當我送一個JSON,如:

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

我期待的表Customer將有名稱和表Address將具有三個屬性加上customer_id。但是現在的customer_id是null。

有什麼想法?

+1

是的,你需要設置address.customer領域,而不是讓它空。 –

+0

如果您使用Jackson進行JSON轉換,您可以使用'JsonManagedReference'和'JsonBackReference'註釋自動設置參考,而不是手動。 – coladict

回答

1

更改列表地址像下面的setter方法:

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"