转换事务中的实体时的LazyInitializationException

时间:2015-07-26 16:52:45

标签: java spring hibernate jackson spring-data

在将域对象从数据库转换为客户端的资源对象期间,我有一个延迟加载字段的问题。

  • 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

为什么会这样?

1 个答案:

答案 0 :(得分:2)

您从一个事务加载客户,该事务不会初始化延迟加载的字段。然后提交该事务并关闭关联的Hibernate会话,使客户实体分离。然后,您启动另一个尝试初始化分离客户的惰性字段的事务。

这不起作用:您需要从与加载客户的事务相同的事务中加载惰性字段。所以

  • 使您的控制器方法具有事务性,或
  • 初始化getById()或
  • 中的惰性字段
  • 在存储库中使用连接提取,以确保查询加载客户和所需的关联,或
  • make getById()返回FullCustomer
  • 使用OpenEntityManagerInView拦截器/过滤器(并使您的转换器成为非事务性的)
相关问题