I have a OneToMany relationship between a Donor entity and Phone entity. Each Donor entity has a many phones. I have mapped this relationship using java.util.Map with shared primary key. Here is what the mapping looks like.
In Donor entity
Code:
@OneToMany(mappedBy="donor", fetch=FetchType.EAGER,cascade=CascadeType.ALL)
@MapKey(name="phoneType")
private Map<PhoneType, Phone> phonesMap = new HashMap<PhoneType,Phone>();
In Phone entity
Code:
@Id
@Column(name="Phone_Type")
@Enumerated
private PhoneType phoneType;
@Id
@ManyToOne
@JoinColumn(name="Donor_Id")
private Donor donor;
This relation works fine if I try to persist a new Donor entity. But if I try to modify the existing donor entity using detachment and merging I get following exception.
Code:
javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.arpanjyoti.model.Donor
Here is the code that I am using for modifying the Donor entity.
First read the Donor entity
Code:
tran.begin();
Donor managedDonor = em.find(Donor.class, donorId);
tran.commit();
Now modify the Donor entity and try to merge
Code:
tran.begin();
Donor managedDonor = em.merge(donor);
tran.commit();
The merge operation gives the above mentioned exception. The strange part is that I don't even modify the Donor to Phone relationships prior to merge. Not only that, if I don't modify Donor object and just try to merge as it was before, I still get the above said exception.
Any suggestions why merge fails with exception.
regards,
Nirvan