java - JPA ManyToOne/OneToMany 没有在 child 身上插入值(value)

标签 java json postgresql hibernate jpa

我正在开发一个将接收 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;
}

我的 Controller 只有这个:

@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 表会有 name,而 Address 表有这三个属性加上 customer_id。但是现在的 customer_id 是空的。

有什么想法吗?

最佳答案

修改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"

关于java - JPA ManyToOne/OneToMany 没有在 child 身上插入值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43246259/

相关文章:

c# - 牛顿软件.Json.JsonReaderException : Additional text encountered after finished reading JSON content:

python - 获取JSON数据的特定值

c# - JSON 字符串解析错误。 System.Exception {Newtonsoft.Json.JsonReaderException}

javascript - Bookshelf.js 预加载第三个表

python - Django、Postgres - 列无法自动转换为整数类型

Java 数独生成器无法正常工作

java - 您如何链接到 javadoc 中的_包描述_(不是类)?

java - 为作为 Windows 服务运行的 Java 应用程序创建安装程序

postgresql - 插入后同步两个表

java - 跨多个请求周期保留组件状态