'Spring seems to be ignoring Hibernate5Module and lazy loading of hibernate object
Exception
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: java.util.ArrayList[0]->challenge.ChallengeAttempt["user"]->user.User$HibernateProxy$EvJuQSUg["hibernate_lazy_initializer"])
My entity has a ManyToOne relationship as follows:
@Entity
public class ChallengeAttempt{
//rest of the fields and setters/getters
//....
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "USER_ID")
private User user;
}
And this is my contorller class which fetches a list of data:
@RestController
public class MyController{
@GetMapping("attempts")
public ResponseEntity<List<ChallengeAttempt>> getStatistics(@RequestParam(name = "alias") String alias) {
return ResponseEntity.ok(challengeService.getStatsForUser(alias));
}
}
Then I added a configuration to solve the lazy loading exception (fail on empty bean):
@Configuration
public class JsonConfiguration {
@Bean
public Module hibernate5Module() {
Hibernate5Module module = new Hibernate5Module();
return module;
}
}
The problem is that when I send a get request to fetch latest attempts (controller getStatistics method) I still get the exception as if JsonConfiguration didn't exist. (I have put this class under the main SptringBootApplication class, so it is actually being scanned by the Spring.)
UPDATE: I realized that Spring does not automatically register the Hibernate5Module into objectMapper. Using ApplicationContext I made sure that the hibernate5Module is successfully loaded. Then, when I checked the registered modules in objectMapper bean, I noticed it is empty (Meaning that no module has been registered). By registering hibernate5Module bean in objectMapper as follows I could make the Spring to work properly:
objectMapper.registerModule(hibernate5Module);
However, I think it's just a hack and is not recommended at all. So, why doesn't Spring register hibernate5Module automatically? Is this a bug in Spring?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
