kmongo
kmongo copied to clipboard
Create @BsonSubTypes Annotation for abstract / sealed class
Hi, I've created a User model with a list of accounts List<Account> Account is a sealed class with 2 subclasses InternalAccount and GoogleAccount. The 3 classes are marked with annotation @BsonDiscriminator. InternalAccount and GoogleAccount have specific values for BsonDiscriminator.
I start the application, save a user with different accounts and close the application. When I restart the application and do a find() on the user collection, the application crashes. The Mongo Java driver can't determine how to cast the list of accounts because after restarting the application it has never seen InternalAccount or GoogleAccount classes and so it has not registered them in the KMongoPojoCodecProvider (which uses automatic(true)).
If I create a KMongoClient and do the following just after: mongoClient.mongoClientOptions.codecRegistry.get(InternalAccount::class.java) mongoClient.mongoClientOptions.codecRegistry.get(GoogleAccount::class.java) Then the application works because now both classes are registered with the codec provider.
The best would probably to have a @BsonSubTypes annotation on Account sealed class with an array of classes as parameter and use reflection to register the classes with the codec provider when Account class is registered.
Let me know what you think about it, I could work on this and create a pull request. Best, JB
@jbmolle I agree with the proposal. A PR would be great :)