Hibernate: LazyInitializationException: Failed to lazily initialize the role collection. Failed to initialize proxy - no session

I have the following 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 object Model:

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 class of service:

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

I call the 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 try to call this method, I get an exception in the string entities.add(entity);, the same exception occurs when I call getEntities()on Model. I checked the transaction manager, and it is configured correctly, and the transaction exists at this step. I also checked many stackoverflow answers related to this exception, but nothing useful.

What could be the reason for this?

+9
2

, - .

:

@Override
public void process(Model model) {
     ...
    Model mergedModel = session.merge(model);

    mergedModel.addEntity(createEntity());
    ...
}
+7

@Maciej Kowalski @Transactional, model, deatached, get entities @Transactional LazyInitializationException.

, model :

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

, .

+2

Source: https://habr.com/ru/post/1672811/


All Articles