Hibernate: LazyInitializationException: failed to

2020-08-10 09:47发布

问题:

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?

回答1:

It seems that model is a detached entity.

Try to merge and perform operations on a merge instance:

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

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


回答2:

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.