【问题标题】:JPA ManyToOne/OneToMany not inserting the value on childJPA ManyToOne/OneToMany 没有在孩子上插入值
【发布时间】:2017-08-31 22:58:49
【问题描述】:

我正在开发一个将接收 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 是 null。

有什么想法吗?

【问题讨论】:

  • 是的,需要设置address.customer字段,不能留空。
  • 如果您使用 Jackson 进行 JSON 转换,您可以使用 JsonManagedReferenceJsonBackReference 注释自动设置引用,而不是手动设置。

标签: java json postgresql hibernate jpa


【解决方案1】:

改变List地址的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"

【讨论】:

  • Thnnxx Man 花了两个多小时寻找正确的答案
猜你喜欢
  • 1970-01-01
  • 2016-11-14
  • 1970-01-01
  • 1970-01-01
  • 2014-08-19
  • 1970-01-01
  • 1970-01-01
  • 2011-01-01
  • 2019-02-24
相关资源
最近更新 更多