0

I faced strange behavior for Spring Page serialization. I have endpoint that return Page as a response body. However, there was n+1 select problem, that's why I implemented repository method with entity graph argument.

    @Override
public Page<T> findAll(Specification<T> spec, Pageable pageable,
                       EntityGraph.EntityGraphType entityGraphType, String entityGraphName) {

    TypedQuery<T> query = getQuery(spec, pageable.getSort());
    query.setHint(entityGraphType.getKey(), entityManager.getEntityGraph(entityGraphName));

    return readPage(query, getDomainClass(), pageable, spec);
}

This code works well for me as far as resolved n+1 problem (I can see it from in logs with "show-sql:true"). However, serialization problem occurred as far as response json was something like:

{
"content": [
    {
        "parentDateField": "2019-07-17",
        "anotherParentDateField": "2019-07-17",
        "id": 90,
        "childA": {
            "fieldA": null,
            "fieldB": null,
            "id": 11,
            "name": "Value",
            "childAchildA": {
                "id": 3
            }
        }
    }
]
}

So many missed data: page info that is always placed in json root with context (totalElements etc.), context contains only 1 object although there should be 20 elements on the page, even this 1 object contains only 1 child entity data although there are many children mentioned in entity graph with @ManyToOne relation.

To solve this problem I added Hibernate5Module:

@Configuration
public class SpringConfig {

@Autowired
public void configureObjectMapper(final ObjectMapper mapper) {
    mapper.registerModule(new SimpleModule().addSerializer(new SortSerializer(Sort.class)));
}

@Bean
public Hibernate5Module hibernate5Module() {
    return new Hibernate5Module();
}

@Bean
public Jdk8Module jdk8Module() {
    return new Jdk8Module();
}
}

I know that it could also be added in configureObjectMapper, but, please, it doesn't matter for now. Adding these beans resolved 3rd issue mentioned above as far as my object now contains all the fields and children info as expected. But there are still Page info and other 19 elements missed. I am pretty sure that it is serialization issue because when I use debugger to evaluate result I receive all the necessary information:

Debugger evaluation

I don't know how to fix it. Moreover, it's interesting how adding entity graph could cause such issues. Please, help!

4

0 回答 0