OneToOne relationship - where should be Id

34 views Asked by At

There is many question about oneToOne or OneToMany but I can not get answer why my app does not save id. I have two entities:

@Entity
Person {
    private String id;
    private String Name;
    ...
}

and:

@Entity
Address{
    private String id;
    private String city;
    ...
}

now I would like to make realtionship OneToOne. So in table with Address I added column ID_PERSON and then in Person Entity:

@Entity
Person {
   ...
   @OneToOne(mappedBy = "person", fetch = FetchType.LAZY, cascade = CascadeType.All)
   private Address address;
}

and in Address:

@Entity
Address{
    ...
    @OneToOne
    @JoinColumn(name = "ID_PERSON")
    private Person person;
}

And the I would like to make simply repository.save(person). After that, I recive new record in PERSON_TABLE and new record in ADDRESS_TABLE but value in column ID_PERSON is empty. Is it coused by fact that Person is getting "id" after save and while saving address that id not exists yet? What should I change to get result like:

public void save() {
    Person person = new Person();
    Address address = new Address();
    addres.setCity("XYZ");
    person.setName("ANY_NAME");
    person.setAddress(address)
    repository.save(person); 
}

and record in Databases: PERSON_TABLE: ID: UUID111, NAME: ANY_NAME, ...

ADDRESS_TABLE: ID: UUID555, CITY: XYZ, ID_PERSON: UUID111 ?

1

There are 1 answers

0
Anton Kozub On

Add address.setPerson(person);. Because address saves a person's id, not the other way around.