我知道有很多“无法初始化代理 - 没有会话”的问题,但我没有找到我的问题的任何答案。
所以问题是,当我委托fetchLazy方法时,它会抛出上面提到的异常。这是我的服务类的简化版本:
服务
public abstract class Service<S extends Service<S,E>, E extends Entity> {
@PersistenceContext private EntityManager entityManager;
// person = personService.fetchLazy(person, Person::getCompany); OK
public E fetchLazy(E entity, Function<E,?> proxyMapper) {
E attachedEntity = entityManager.find(entity.getClass(), entity.getId());
Object proxy = proxyMapper.apply(attachedEntity);
if (!Hibernate.isInitialized(proxy)) { Hibernate.initialize(proxy); }
return attachedEntity;
}
// person = personService.fetch(person).lazy(Person::getCompany); EXCEPTION
public FetchBuilder fetch(E entity) { return new FetchBuilder((S) this, entity); }
public class FetchBuilder {
private final S service; private final E entity;
LazyFetchBuilder(E e, S s) { this.entity = e; this.service = s; }
public E lazy(E entity, Function<E,?> proxyMapper) {
return service.fetchLazy(entity, proxyMapper); // DELEGATE
}
}
}
个人服务
@Stateless
public class PersonService extends Service<PersonService,Person> { ... }
人豆
@Named @ViewScoped
public class PersonBean implements Serializable {
@EJB private PersonService personService;
@PostConstruct public void init() {
person = personService.getById(id);
person = personService.fetchLazy(person, Person::getCompany); // OK
person = personService.fetch(person).lazy(Person::getCompany); // EXCEPTION
}
}
Helenr
相关分类