Avoid Jackson serialization on non fetched lazy objects

前端 未结 14 1887
终归单人心
终归单人心 2020-11-22 13:02

I have a simple controller that return a User object, this user have a attribute coordinates that have the hibernate property FetchType.LAZY.

When I try to get this

14条回答
  •  名媛妹妹
    2020-11-22 13:39

    I tried this, and worked:

    // custom configuration for lazy loading

    public static class HibernateLazyInitializerSerializer extends JsonSerializer {
    
        @Override
        public void serialize(JavassistLazyInitializer initializer, JsonGenerator jsonGenerator,
                SerializerProvider serializerProvider)
                throws IOException, JsonProcessingException {
            jsonGenerator.writeNull();
        }
    }
    

    and configure mapper:

        mapper = new JacksonMapper();
        SimpleModule simpleModule = new SimpleModule(
                "SimpleModule", new Version(1,0,0,null)
        );
        simpleModule.addSerializer(
                JavassistLazyInitializer.class,
                new HibernateLazyInitializerSerializer()
        );
        mapper.registerModule(simpleModule);
    

提交回复
热议问题