Cannot get unfetched attribute

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.

On a View I added all properties.

Could you help me ?

I attached only module directory.

Thanks in advance.modules.zip (13.7 MB)

Hi,
The project attached is pretty big, and you have not specified where the problem occurs.

If you could extract your problem to a small demo project with 2-3 entities and screens, community members would have more chance to help you.

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].”

Can you help me?

Thanks in advance.

Best regards.

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.

3 Likes