I recently migrated the Spring Boot version of a project, upgrading from version 1.X to 2.X. However, this caused problems in recovering persisted objects using the org.bson.Document
(using PojoCodecProvider
), because they did not have the _class
field.
I had already asked at StackOverflow in order to identify a solution, but I did not get an answer. In addition, a very qualified user suggested that I open an issue to report my problem. In this sense, I created a simple repository that simulates this problem: here. The Application class has all the configuration and execution flow, as well as explanatory comments, which I summarized below:
@Autowired
private LogRepository logRepository;
@Bean
public MongoClientOptions mongoClientOption() {
// I am using the PojoCodec to automatic parse my domain classes:
final CodecRegistry pojoCodec = fromProviders(PojoCodecProvider.builder().automatic(true).build());
final CodecRegistry fullCodec = fromRegistries(getDefaultCodecRegistry(), pojoCodec);
return MongoClientOptions.builder().codecRegistry(fullCodec).build();
}
@Override
public void run(String... args) throws Exception {
final String key = "response";
// Simulate my dynamic of entity insertion (with several domain classes into "outbound" field):
final Map<String, Object> map = new HashMap<>();
map.put(key, new MyClass1("attr1", new MyClass2(1L)));
final Log log = new Log();
log.setOutbound(new Document(map));
logRepository.save(log);
// Find saved entity to try specific class conversion (MyClass1):
final Log logSaved = logRepository.findById(log.getId()).orElseThrow(RuntimeException::new);
try {
// Error occurs here, but in Spring Boot 1.X this conversion/cast works...
// Note: In Spring Boot 1, the "_class" field is present inside my "outbound" field.
final MyClass1 test = logSaved.getOutbound().get(key, MyClass1.class);
System.out.println(test);
} catch (Exception e) {
e.printStackTrace();
}
}
Analyzing the difference between the data saved in the Spring Boot version 1 and 2, I identified that the most current version stopped recording the _class
field, looking to the instances stored in myDocument
(Log#outbound
).
Could you help me understand this difference in outcome, please?
Comment From: snicoll
@falvojr that is rather a question for Spring Data MongoDB that got upgraded as part of the Spring Boot upgrade. Let's continue on the StackOverflow question you've created, as mentioned in the guidelines for contributing, we prefer to use GitHub issues only for bugs and enhancements.