【发布时间】:2015-07-26 16:52:45
【问题描述】:
在将域对象从数据库转换为客户端的资源对象期间,我遇到了延迟加载字段的问题。
-
Customer: 实体从数据库中加载,带有惰性字段 -
FullCustomer:将发送给客户端的实体。
服务层:
@Transactional(readOnly=true)
public Customer getById(Long id){
return customerRepository.getById(id);
}
控制器:
@Autowired
private ResourceAssembler<Customer, FullCustomer> converter;
@RequestMapping(...)
public final FullCustomer getCustomerById(long cid) {
Customer customer = customerService.getById(cid);
return converter.convert(customer);
}
转换器 (ResourceAssembler<Customer, FullCustomer>)
@Override
@Transactional(readOnly = true)
public FullCustomer convert(Customer input) {
System.err.println("Is open: " + TransactionSynchronizationManager.isActualTransactionActive()); //prints true
FullCustomer fullCustomer = new FullCustomer();
BeanUtils.copyProperties(input, fullCustomer); //Fails
return fullCustomer;
}
所以我的控制器使用转换器将数据库实体转换为客户端的实体。转换触发加载其他延迟加载的实体。
我的问题:虽然转换函数打开了一个新事务(Is open 打印true),但我得到了这个异常:
org.springframework.http.converter.HttpMessageNotWritableException:
Could not write content: failed to lazily initialize a collection of role: [..], could not initialize proxy - no Session (..);
nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: ...
在使用 BeanUtils 之前访问延迟加载的字段时,我得到以下信息:
org.hibernate.LazyInitializationException:
failed to lazily initialize a collection of role: [..], could not initialize proxy - no Session
为什么会这样?
【问题讨论】:
标签: java spring hibernate jackson spring-data