我有下一个错误: 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
我的Model实体:
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);,当我打电话时,也会发生同样的异常getEntities()上model。我已经检查了事务管理器,并且配置正确,并且此步骤中存在事务。另外,我已经检查了关于与此异常相关的stackoverflow的大量答案,但没什么用。
entities.add(entity);
getEntities()
model
可能是什么原因造成的?
看来模型是一个独立的实体。
尝试合并并在合并实例上执行操作:
@Override public void process(Model model) { ... Model mergedModel = session.merge(model); mergedModel.addEntity(createEntity()); ... }