Alessandro C
Alessandro C

Reputation: 3560

Spring Data Rest: Entity serialization with LAZY object cause JsonMappingException

I'm getting the following Exception with a Spring Data Rest project:

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) ) 
(through reference chain: org.springframework.data.rest.webmvc.json.["content"]->test.spring.data.rest.xml.entities.Author_$$_jvstb93_1["handler"])

Certainly, I have some entities that have the fetch configuration = FetchType.LAZY.

I followed many instructions and links, but I still have this exception.

What I have already tried to do (with NO effetcs):

No one of the actions above has solved the problem!

How to (definitely) solve this problem?

Thanks.

Upvotes: 2

Views: 984

Answers (1)

Alessandro C
Alessandro C

Reputation: 3560

I have found the solution to this annoying problem.

For every repository of the Spring Data Rest application it has to be defined a custom @Projection; in the projection there will be the necessaries fields.

Pay attention that if there are cycylc references between two entities, the corrispective methods of the projections have to be annotated with @JsonBackReference annotation (for @ManyToOne annotated fields) and with @JsonManagedReference annotation (for @OneToMany annotated fields), otherwise there will be a JSON loop in the JSON serialization.

In every @Repository annotation (or @RepositoryRestResource annotation) it has to be marked the excerptProjection property, with the custom projection.

With this management, there is no need of any other configuration, and the exception for Lazy objects finally is vanished.

Upvotes: 4

Related Questions