【发布时间】:2021-04-15 17:43:43
【问题描述】:
假设我有这两个实体,个人和保险。一个人可以拥有多份保险,保险唯一性由(保险类型、保单编号和人员 ID)的复合键组合维护。下面的代码代表场景...
父类
@Entity
@Setter
@Getter
@RequiredArgsConstructor
public class Person implements Serializable {
@Id
@GeneratedValue(strategy = "GenerationType.IDENTITY")
@Column(name "person_id")
private Long personId;
@Column(name = "fst_nm")
private String fstName;
@Column(name = "lst_nm")
private String lstNm;
// ..Other columns & relationships
@OneToMany(mappedBy = "person")
private List<Insurance> insurances;
public void addInsurance(Insurance toAdd) {
getInsurances().add(toAdd);
toAdd.setPerson(this);
}
}
子类
@Entity
@Setter
@Getter
@RequiredArgsConstructor
public class Insurance implements Serializable {
@EmbeddedId
private insurancePK id;
//other data
@ManyToOne
@MapsId("personId")
private Person person;
}
复合PK类
@Setter
@Getter
@Embeddable
public class InsurancePK implements Serializable {
@Column(name = "person_id", insertable = false, updatable = false)
private Long personId;
@Column(name = "insurance_type")
private String insuranceType;
@Column(name = "pol_num")
private String polNum;
}
现在,我的数据映射器看起来像这样......
Person newPerson = new Person();
newPerson.setInsurances(new ArrayList<>());
// fill out Person Model data
// incoming insurance data
while (incomingData.hasNext()) {
Insurance insuranceData = new Insurance();
InsurancePK pk = new InsurancePK();
// set other insurance data
pk.setInsuranceType("Dental");
pk.setPolNum("123Abc00");
insuranceData.setId(pk);
person.addInsurance(insuranceData);
}
问题是我在复合键中的 person_id 总是得到一个空值,不知道为什么(@MapsId 不应该处理那个值)? 我需要动态获取该值,大多数 JPA 复合键解决方案只是手动设置所有值,但这不是我的方案。
从 saveAndflush() 返回对象
{
person: {
person_id: 55,
fst_nm: blah,
lst_nm: blah,
insurances: [
{
insurance_pk: {
person_id: null,
insurance_type: "Dental",
pol_num: "123Abc00"
}
//other insurance data
}
]
}
}
关于我缺少什么的任何建议?提前谢谢!
【问题讨论】:
-
不是真的,因为这意味着我仍然需要手动设置 MeetingId(在我的情况下为 InsuranceId)......而且我没有映射器内的所有值,因为 personId 是尚未决定,将为空。
标签: java spring-boot hibernate jpa spring-data-jpa