Let's say I have those two entities, Person & Insurance. One Person can have multiple insurances, and the insurance uniqueness is maintained by a composite key combination of (insurance type, policy number, and person id). The below code represent the the scenario...
parent class
@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);
}
}
child class
@Entity
@Setter
@Getter
@RequiredArgsConstructor
public class Insurance implements Serializable {
@EmbeddedId
private insurancePK id;
//other data
@ManyToOne
@MapsId("personId")
private Person person;
}
composite PK class
@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;
}
now, my data mapper looks something like that...
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);
}
Problem is my person_id inside the composite key is always getting a null value, not sure why (shouldn't the @MapsId takes care of that value)? I need to fetch that value dynamically, most of the JPA composite key solutions only are setting all the value manually, but that's not my scenario.
return object from 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
}
]
}
}
any suggestions on what am I missing? Thank you in advance!