JPA (hibernate) OneToMany relationship and null
I have a relation OneToMany between a class Resident and ResidentInfo ResidentInfo is not supposed to exists without Resident, but ResidentInfo is not required
Here are my classes:
public class Resident {
...
@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE, Casc开发者_运维技巧adeType.REFRESH}, mappedBy = "resident")
@Cascade({org.hibernate.annotations.CascadeType.ALL})
public List<ResidentInfo> infos;
}
public class ResidentInfo {
...
@ManyToOne(optional = false)
public Resident resident;
public String label;
public String value;
}
I'm new to JPA and maybe I'm doing things wrong.
The issue is that when I try to insert datas all at once (create resident and its infos at the same time) I've got a null exception.
This is because ResidentInfo.resident.id is null (but I can't specify a value because Resident is created in the same time !)
Also even if the resident is created first, I have this error but I don't know why :
detached entity passed to persist: models.ResidentInfo
So how to resolve theses issues ?
To solve your problem you should provide at first a setter method in the class ResidentInfo to set the Resident object the info instance belongs to. It could look like this
public void setResident(Resident resident) {
this.resident = resident;
}
Furthermore adding a ResidentInfo object to a Resident object should only be done in the Resident class. You should provide a method to add a new ResidentInfo object to the contained list. Part of adding the ResidentInfo object would be to set the Resident object that is associated with it. The code could look something like this
public void addResidentInfo(ResidentInfo residentInfo) {
residentInfo.setResident(this);
infos.add(residentInfo);
}
With these lines every object in the list contains a reference to the Resident instance that is associated with it. So when you persist all objects, the necessary references (as well as any required ID) are set.
On a side note you should check your Cascade information in the JPA annotation. You provided two different annotations with very different meaning.
精彩评论