我有3个实体如下:
@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;
}
}
当我尝试使用自动生成的 Id 保存 Person 时,Person 和 Address 插入正确发生,但 AddressUse 插入失败,说 Address 没有 personId 字段。如果密钥不是自动生成的,我手动传递它,一切正常,但使用自动生成的 ID,级联失败。
我在 AddressUse 中设置了 Address ,反之亦然,我在 Address 中设置了 Person ,反之亦然。
响应中的错误是:
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