Could not write JSON: could not initialize proxy - no Session;

在spring boot中使用jackson作为rest controller出入参的序列化库,出现Could not write JSON: could not initialize proxy - no Session; nested exception is com.fasterxml.jackson.databind.JsonMappingException异常

原因分析:

DAO层使用的是spring data jpa,其依赖hibernate4,而出现异常的repository里有懒加载的对象

解决办法:

添加Hibernate4Module到默认的MappingJackson2HttpMessageConverter中,需要做的是:

1.重写配置类(继承WebMvcConfigurerAdapter)的configureMessageConverters方法

2.注册Hibernate4Module

示例:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter{

    //其他配置....

    public MappingJackson2HttpMessageConverter jacksonMessageConverter(){
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();

        ObjectMapper mapper = new ObjectMapper();
        //Registering Hibernate4Module to support lazy objects
        Hibernate4Module hm = new Hibernate4Module();
        //Force Jackson serialize lazy objects
        hm.configure(Hibernate4Module.Feature.FORCE_LAZY_LOADING,true);
        mapper.registerModule(hm);

        messageConverter.setObjectMapper(mapper);
        return messageConverter;

    }

    @Override
    public void configureMessageConverters(List> converters) {
        //Here we add our custom-configured HttpMessageConverter
        converters.add(jacksonMessageConverter());
        super.configureMessageConverters(converters);
    }

    //其他配置....
}

最后一点,不要忘了引入依赖:

根据自己的hibernate使用版本(hibernate4或hibernate5)和jackson版本${jackson.version}在pom中添加依赖

 



    com.fasterxml.jackson.datatype
    jackson-datatype-hibernate4
    ${jackson.version}

or



    com.fasterxml.jackson.datatype
    jackson-datatype-hibernate5
    ${jackson.version}

 

 

 

 

 

你可能感兴趣的:(java)