Hello,
I have this problem IllegalStateException: Cannot get unfetched attribute [sigla] from detached object com.company.traspammversionetest.entity.TipoSoggetto-54961005-2a2b-e141-db9c-672dec46ec7b [detached] on Listener of Entity.
example_middle_listnere.zip (9.4 MB) Hello,
I created a litte project with two entities on PostGresSql (Automobile and Modello -> Cars and Models in italian language).
I attached a listener (a Bean) on entity Automobile that contain
if (entity.getMarca().getSigla().equalsIgnoreCase(“bmw”)){
throw new CustomValidationException(“test”);
}
When I debug BeforeInsert into listener the property get by “entity.getMarca().getSigla()” is not accessible.
The error that occur is
“IllegalStateException: Cannot get unfetched attribute [sigla] from detached object com.company.examplemiddlelistnere.entity.Marca-2c3c34ec-ad66-aace-afb4-c9ffb2f1e921 [detached].”
Hi,
Entity Listener is a global thing and you can not control which data comes there.
In the BeforeInsertEntityListener there is no guarantee that entity.getMarca() returns an object in managed state with all fields loaded or lazy-loaded when requested.
You can write the code this way to be safe:
@Override
public void onBeforeInsert(Automobile entity, EntityManager em){
Marca marca = entity.getMarca();
if (!PersistenceHelper.isManaged(marca)) {
marca = em.reloadNN(marca);
}
if (marca.getSigla().equalsIgnoreCase("bmw")){
throw new CustomValidationException("test");
}
}
After reload() you can be sure that Marca has all fields loaded, and all links from Marca to other entities will be loaded lazily if requested.