I've seen some post about this, but it seems that I keep running into the same problem.
Here is a similar post:
JsonMappingException: could not initialize proxy - no Session
The Problem
So the suggestion is to add the following:
private MappingJackson2HttpMessageConverter jacksonMessageConverter() {
MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper mapper = new ObjectMapper();
//Registering Hibernate4Module to support lazy objects
mapper.registerModule(new Hibernate5Module());
messageConverter.setObjectMapper(mapper);
return messageConverter;
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(jacksonMessageConverter());
super.configureMessageConverters(converters);
}
But I don't have a super.configureMessageConverters()
method inside super
. They say that the easy solution is to add EAGER
, but it's not preferred. another solution would be to use @JsonIgnore
, but I want to retrieve the corresponding entities. It is said that adding the code that you see above this text is 1 of the proper and clean ways to handle this. Is this still true? If so, then how should I write the super.configureMessageConverters(converters);
, cause that seems to be the problem.
Extra info
This problem occurred when I was adding an many to many relationship:
Type
// region: relationships
@ManyToMany(mappedBy = "types")
private Set<License> licenses;
// endregion: relationships
License
@ManyToMany
@JoinTable(name = "license_restrictions",
joinColumns = @JoinColumn(name = "license_id"),
inverseJoinColumns = @JoinColumn(name = "type_id"))
private Set<Type> types;
// endregion: relationships
EDITED V1
I've added the following as suggested in the comments:
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(jackson2HttpMessageConverter());
}
@Bean
public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(this.jacksonBuilder().build());
return converter;
}
private Jackson2ObjectMapperBuilder jacksonBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
Hibernate5Module hibernateModule = new Hibernate5Module();
hibernateModule.configure(Hibernate5Module.Feature.FORCE_LAZY_LOADING, false);
builder.modules(hibernateModule);
// Spring MVC default Objectmapper configuration
builder.featuresToDisable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
builder.featuresToDisable(MapperFeature.DEFAULT_VIEW_INCLUSION);
return builder;
}
This also does not return the result.
Types is null
while it should be a collection of 2 types.
Here you can see that I do have types that are bound to license 1.