JPA ManyToOne / OneToMany没有在child上插入值

时间:2017-04-06 05:17:22

标签: java json postgresql hibernate jpa

我正在开发一个将接收JSON的Rest API。我需要在Postgres DB中正确保存JSON。

现在我有:

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

我的控制器只有这个:

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

当我发送JSON时:

(debugsig:26923): Gtk-CRITICAL **: gtk_text_buffer_get_bounds: 
assertion 'GTK_IS_TEXT_BUFFER (buffer)' failed

我当时希望表Customer有名称,表Address会有三个属性加上customer_id。但是customer_id现在是空的。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

更改列表地址的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"