【发布时间】:2017-08-13 01:01:45
【问题描述】:
我有下一个错误:nested exception is org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.example.Model.entities, could not initialize proxy - no Session
我的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);
}
}
我有一个服务类:
@Service
@Transactional
class ServiceImpl implements Service {
@Override
public void process(Model model) {
...
model.addEntity(createEntity());
...
}
}
我正在从另一个服务方法调用服务:
@Override
@JmsListener(destination = "listener")
public void handle(final Message message) throws Exception {
Model model = modelService.getById(message.getModelId());
serviceImpl.process(model);
modelService.update(model);
}
但是当我尝试调用此方法时,我在 entities.add(entity); 上遇到异常,当我在 model 上调用 getEntities() 时也会发生同样的异常。
我检查了事务管理器,它配置正确,并且在这一步存在事务。我还检查了与此异常相关的 stackoverflow 上的大量答案,但没有任何用处。
可能是什么原因造成的?
【问题讨论】:
-
当你说“事务存在于这一步”时,你的意思是你已经检查了一个事务是否真的打开了,比如使用stackoverflow.com/a/42584751/3517383?
-
@gabrielgiussi 是的
-
实体是新对象吗?如果是这种情况,则必须先将实体对象保存在数据库中,然后才能将其添加到实体列表中。
-
我猜你错了,实际上调用 model.getEntities() 给了我关于延迟初始化的同样错误
标签: java spring hibernate jpa spring-transactions