简体   繁体   English

如何在OneToOne单向关系中插入父母和孩子

[英]How to insert parent and child in a OneToOne unidirectional relationship

I'm starting a Web application, and I have the following structure: 我正在启动一个Web应用程序,并且具有以下结构:

+--------------------------+
| Company                  |
|--------------------------|
| id            PK, NN, AI |
| attibute1                |
| attribute2               |
+--------------------------+

+--------------------------+
| CompanyProfile           |
|--------------------------|
| id            PK, NN, AI |
| id_company    FK, NN     |
| attribute3               |
| attribute4               |
| attribute5               |
+--------------------------+

 public class Company {
    @Id
    @GeneratedValue
    @Column(unique = true, nullable = false)
    private Long id;

    private String attribute1;

    private String attribute2;

    @OneToOne(cascade = { CascadeType.ALL })
    @JoinColumn(name = "id_company", unique = true)
    private CompanyProfile companyProfile;

    // ...
}

public class CompanyProfile {
    @Id
    @GeneratedValue
    @Column(unique = true, nullable = false)
    private Long id;

    private String attribute3;

    private String attribute4;

    private String attribute5;

    // ...
}

I'm sending a POST request to one controller with the following JSON: 我正在使用以下JSON向一个控制器发送POST请求:

{
    "attribute1": "value 1",
    "attribute2": "value 2",
    "companyProfile": {
        "attribute3": "value 3",
        "attribute4": "value 4",
        "attribute5": "value 5"
    }
}

So now I want to execute the command .save() and have the application to insert the company in its respectively table and after that, insert the companyProfile in its respective table, all at once. 因此,现在我想执行命令.save()并让应用程序将公司插入其各自的表中,然后,将companyProfile一次插入其各自的表中。 But that's not happening and I'm getting this: Error Code: 1364. Field 'id_company' doesn't have a default value . 但这没有发生,我得到了: Error Code: 1364. Field 'id_company' doesn't have a default value

What may I have been doing wrong? 我可能做错了什么?

For your persistence, I think you will have to persist in the order below, 为了您的坚持,我认为您必须按照以下顺序坚持,

Persist Company object, then 坚持公司对象,然后

Set the Company object into CompanyProfile and 将公司对象设置为CompanyProfile和

Finally persist CompanyProfile 最后坚持CompanyProfile

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM