[英]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
我有下一个错误:
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: 我的
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 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);
但是当我试图调用这个方法时,我会在线上
entities.add(entity);
上获得异常entities.add(entity);
also the same exception occurs when I'm calling getEntities()
on model
. 当我在
model
上调用getEntities()
时也会发生同样的异常。 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.
此外,我已经检查了连接到此异常的stackoverflow上的大量答案,但没有任何用处。
What could be the cause of it? 可能是什么原因造成的?
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());
...
}
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
. 因此@Maciej Kowalski在第一次
@Transactional
读取我的model
后提到它已经处于deatached状态并且调用来自另一个@Transactional
方法的entities
因LazyInitializationException
失败。
I've changed my service a bit to get model
from database in the same transaction: 我已经改变了我的服务,以便在同一个事务中从数据库中获取
model
:
@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. 现在一切都按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.