Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: LazyInitializationException: failed to lazily initialize a collection of role. Could not initialize proxy - no Session

I have next error: nested exception is org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.example.Model.entities, could not initialize proxy - no Session

My Model entity:

class Model {
...
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "model", orphanRemoval = true)
    @Cascade(CascadeType.ALL)
    @Fetch(value = FetchMode.SUBSELECT)
    public Set<Entity> getEntities() {
        return entities;
    }

    public void addEntity(Entity entity) {
        entity.setModel(this);
        entities.add(entity);
    }

}

And I have a service class:

@Service
@Transactional
class ServiceImpl implements Service {
    @Override
    public void process(Model model) {
        ...
        model.addEntity(createEntity());
        ...
    }
}

I'm calling service from another service method:

@Override
@JmsListener(destination = "listener")
public void handle(final Message message) throws Exception {
    Model model = modelService.getById(message.getModelId());
    serviceImpl.process(model);
    modelService.update(model);
}

But when I'm trying to call this method I'm getting exception on line entities.add(entity); also the same exception occurs when I'm calling getEntities() on model . I've checked transaction manager and it's configured correctly and transaction exists on this step. Also I've checked tons of answers on stackoverflow connected to this exception but nothing useful.

What could be the cause of it?

like image 657
Orest Avatar asked Mar 21 '17 11:03

Orest


1 Answers

So as @Maciej Kowalski mentioned after first @Transactional read of my model it's already in deatached state and call to get entities from another @Transactional method failed with LazyInitializationException.

I've changed my service a bit to get model from database in the same transaction:

@Service
@Transactional
class ServiceImpl implements Service {
    @Override
    public void process(long modelId) {
        ...
        Model model = modelDao.get(modelId);
        model.addEntity(createEntity());
        ...
    }
}

Now everything works as expected.

like image 149
Orest Avatar answered Sep 19 '22 09:09

Orest