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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With