First of all, hope you are having a great day!!!
I have a class model with a POJO having nested document list which are an abstract type, like so:
public class ConfigDocument {
private List<BaseActionConfig> actions;
}
public abstract class BaseActionConfig {
@BsonProperty("interface") private int iface;
}
public class SwitchActionConfig extends BaseActionConfig {
private int switchIndex;
private boolean switchState;
}
My configuration form MongoClient is:
public class MongoDBManager {
private static MongoClient client = null;
private static CodecRegistry codecRegistry()
{
ClassModel<ConfigDocument> configDocumentPojo =
ClassModel.builder(ConfigDocument.class).enableDiscriminator(true).build();
ClassModel<BaseActionConfig> baseActionConfigPojo = ClassModel.builder(BaseActionConfig.class)
.enableDiscriminator(true)
.discriminatorKey("interface")
.build();
ClassModel<SwitchActionConfig> switchActionConfigPojo = ClassModel.builder(SwitchActionConfig.class)
.enableDiscriminator(true)
.discriminatorKey("interface")
.discriminator("1")
.build();
PojoCodecProvider manualProvider = PojoCodecProvider.builder()
.register(configDocumentPojo,
baseActionConfigPojo,
switchActionConfigPojo)
.build();
PojoCodecProvider autoProvider = PojoCodecProvider.builder().automatic(true).build();
CodecRegistry pojoCodecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),
fromProviders(manualProvider, autoProvider));
return pojoCodecRegistry;
}
private static MongoClient getClient()
{
if (client == null) {
CodecRegistry pojoCodecRegistry = MongoDBManager.codecRegistry();
MongoClientSettings setting = MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(CONN_STRING))
.codecRegistry(pojoCodecRegistry)
.build();
client = MongoClients.create(setting);
}
return client;
}
}
When reading from database i have all kind of exceptions. The most recurrent one is an InstantiateException
. After a lot of research and configuring ClassModels for using the BsonDiscriminator
i reached the conclusion that the discriminator is not working because i am using an integer value.
How? I have manually replaced the type field in a document inside the database to string and the discrimination started to work. Also, because at some time i have reached this other exception:
org.bson.codecs.configuration.CodecConfigurationException:
Failed to decode 'ConfigDocument'. Decoding 'actions' errored with: Failed to decode 'BaseActionConfig'.
Decoding errored with: readString can only be called when CurrentBSONType is STRING, not when CurrentBSONType is INT32.
The thing is that i cannot update the field of ALL Documents in the database and i see useless to add a new field on each document only for having this java application to work. So, before watching me writing a custom Codec for those classes, i wanted to know if it is possible to configure a discriminator to use an integer value instead of an string one.