|
Originally posted on stackoverflow.
Entity from @MapsId over an entiy directly returned by EntityManager.find() may not be managed !
The case where it happened is in an extended transaction context and the @MapsId entity was retrieved from Hibernate cache. However it is not managed.
Sample code
@Repository
@Transactional
public class SuiviDao {
public Suivi getSuivi(SuiviPK pk) {
final Suivi suivi = em.find(Suivi.class, pk);
assert em.contains(suivi);
assert em.contains(suivi.getCommune());
return suivi;
}
}
Relevant part of the related classes:
@Entity
public class Suivi {
@EmbeddedId
private SuiviPK pk = new SuiviPK();
@MapsId("commune")
@ManyToOne
private Commune commune;
@MapsId("echeance")
@NotNull
@ManyToOne(cascade = { CascadeType.REFRESH })
private Echeance echeance;
}
@Embeddable
public class SuiviPK implements Serializable {
@Column(name = "ECHEANCE")
private Long echeance;
@Column(name = "COMMUNE")
private Long commune;
}
Workaround: load the entity from DB
if (!em.contains(suivi.getCommune())) {
final Commune commune = em.find(Commune.class, suivi.getCommune().getId());
suivi.setCommune(commune);
}
|