未获取的惰性对象的Jackson序列化Hibernate 5 Spring 5

时间:2018-08-21 23:32:36

标签: java hibernate spring-boot jackson

当Jackson尝试序列化惰性对象时,我得到一个错误:

Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: failed to lazily initialize a collection of role:

我尝试使用这种方法this approach,但没有成功。我的杰克逊模块配置

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

  public MappingJackson2HttpMessageConverter jacksonMessageConverter(){
    MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new Hibernate5Module());
    messageConverter.setObjectMapper(mapper);
    return messageConverter;
  }

  @Override
  public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(jacksonMessageConverter());
    super.configureMessageConverters(converters);
  }
}

但是我遇到了同样的错误。您能解释一下我在做什么错吗?

我的springboot版本1.5.15.RELEASE,我的jackson-datatype-hibernate5版本:2.6.0

1 个答案:

答案 0 :(得分:0)

默认情况下,延迟加载功能设置为false。

要启用:

Hibernate5Module module = new Hibernate5Module();
module.enable(Hibernate5Module.Feature.FORCE_LAZY_LOADING);