TillTheDayIDie
TillTheDayIDie

Reputation: 67

Jackson doesn't serialize hibernate lazy fetched field

During the debugging i can see that required in my case field is fetched. enter image description here

But after response is fetched i got this. enter image description here

This is how defiend my field and getter for it.

@JsonBackReference
@OneToMany(mappedBy = PhysicianNote.PHYSICIAN, fetch = FetchType.LAZY)
@ApiModelProperty(hidden = true)
private Set<PhysicianNote> notes;

@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonProperty("notes")
public List<PhysicianNote> getNotes() {
    return Hibernate.isInitialized(notes)
            ? new ArrayList<>(notes)
            : new ArrayList<>();
}

And this is how defined my hibernate 5 module.

    @Bean
    @Primary
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        JavaTimeModule module = new JavaTimeModule();
        module.addSerializer(Instant.class, new InstantSerializerWithMilliSecondPrecision());
        Hibernate5Module h5Module = new Hibernate5Module();
        h5Module.configure(Hibernate5Module.Feature.FORCE_LAZY_LOADING, false);
        objectMapper.registerModules(module, h5Module);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        return objectMapper;
    }

What i do wrong?

Upvotes: 1

Views: 374

Answers (1)

PaulD
PaulD

Reputation: 499

You mixed up @JsonBackReference and @JsonManagedReference, a field marked with @JsonBackReference will not be serialized, it should be on PhysicianNote#physician and @JsonManagedReference should be on notes.

Upvotes: 1

Related Questions