Search code examples
spring-bootspring-data-rest

Configuring Jackson to enable self-referencing objects using jackson-datatype-hibernate


How do I configure the Jackson ObjectMapper in Spring Data when using Spring Boot?

When I try returning a self-referencing entity I keep getting a "com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS" error when I try to retrieve the children of an object in a self-referencing table.

I thought the issue was a serialization issue that could be solved by using the jackson-datatype-hibernate package to help me serialize self-referencing objects. https://github.com/FasterXML/jackson-datatype-hibernate

I haven't been able to see any definitive guidance so far on how to configure the existing ObjectMapper instance that Spring Data Rest uses.

According to the project's GitHub page all I need to do is subclass the ObjectMapper

public class HibernateAwareObjectMapper extends ObjectMapper {

    public HibernateAwareObjectMapper() {
        registerModule(new Hibernate4Module());
    }
}

However, if I subclass the ObjectMapper won't I loose the default behavior of the Jackson ObjectMapper? I don't necessarily want to lose that behavior, just extend it. Also, wouldn't I need to put an @Component annotation on the class in order to have Spring pick it up?


Solution

  • If you are using Spring Data REST I think you need Spring Boot 1.2 to get automatic updates to the object mapper (see here for details). With older versions you can inject your own I think (but you do need to configure all the features you need, if it's more than just that one Module).