JPA ManyToOne/OneToMany无法在子项上插入值

3

我是一名开发人员,正在开发一个接收JSON的Rest API。我需要正确地将JSON保存在Postgres数据库中。

目前我的代码如下:

@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为空。有什么想法吗?

1
是的,您需要设置address.customer字段,而不是将其保留为空。 - JB Nizet
如果您正在使用Jackson进行JSON转换,您可以使用JsonManagedReferenceJsonBackReference注释来自动设置引用,而不是手动设置。 - coladict
1个回答

4

将 List address 的 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 - 一对多关系 - 外键始终为“null”


1
谢谢。这个人花了两个多小时寻找正确的答案。 - Ashwin Golani

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接