One to Many cascade All - save children and dependents

207 Views Asked by At

I have 3 entities as below:

@Entity
@Table(name = "person", schema = "test")
public class Person implements Persistable 
{
     @Id
     @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "***")
     @SequenceGenerator(name = "***", sequenceName = "***" , schema = "test")
     @Column(name = "person_id")
     private int personId;

     @OneToOne(mappedBy = "personById", cascade = CascadeType.ALL, orphanRemoval = true)
     private Address address;
}

@Entity
@Table(***)
class Address
{
    @Id
    private int personId;
    Person personById;
    String countryCode;
    List<AddressUse> addressById;
    
    @OneToOne
    @MapsId
    @JoinColumn(name = "person_id", nullable = false)
    public Person getPersonById() {
        return personById;
    }
    
    @OneToMany(mappedBy = "addressById" , cascade = CascadeType.ALL)
    public Collection<AddressUse> getAddressById() {
        return addressById;
    }
}

@Entity
@Table(***)
class AddressUse
{
    @Id
    private int personId;
    @Id  
    String use;
    Date modifyTimestamp;
    String updateBy;
    Address addressById;
    
    @ManyToOne
    @JoinColumn(name = "person_id", nullable = false , insertable = false, updatable = false)
    public Address getAddressById() {
        return addressById;
    }
}

When I try to save Person with auto generated Id, the Person and Address inserts happen properly but the AddressUse insert fails saying Address does not have the personId field. If the key is not autogenerated, and I pass it manually, everything works well but with auto generated Id, the cascade fails.

I have set Address in AddressUse and vice versa, I have set Person in Address and Vice versa.

Error in the response is:

Key (person_id)=(0) is not present in table "Address" Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute batch] insert into db.test.address_use

0

There are 0 best solutions below