我正在尝试创建一个 Java 程序,例如从 MongoDB 读取和写入复杂对象...
public class GameCharacter {
public String name;
public Weapon weapon;
public Armor armor;
public GameCharacter(String name, Weapon weapon, Armor armor) {
this.name = name;
this.weapon = weapon;
this.armor = armor;
}
}
我已经通过设置这个编解码器成功地编写了它,并且我可以在数据库中检查所有数据是否以正确的结构正确写入:
CodecRegistry defaultCodecRegistry = MongoClient.getDefaultCodecRegistry();
PojoCodecProvider pojoCodecProvider = PojoCodecProvider.builder().automatic(true).build();
CodecRegistry pojoCodecRegistry = fromRegistries(defaultCodecRegistry, fromProviders(pojoCodecProvider));
MongoDatabase characterDatabase = mongoDatabaseConnectionPool.getDatabase(CHARACTER_DATABASE_NAME);
characterDatabase = characterDatabase.withCodecRegistry(pojoCodecRegistry);
MongoCollection<GameCharacter> characterCollection = characterDatabase.getCollection(CHARACTER_COLLECTION_NAME, GameCharacter.class);
Character testCharacter = new Character ("Sylvia Zerin", testWeapon, testArmor);
characterCollection.insertOne(testCharacter);
...但是,当尝试再次从该数据库读取 GameCharacter 时,如下所示:
FindIterable<GameCharacter> characters = characterCollection.find();
...然后出现以下错误消息:
org.bson.codecs.configuration.CodecConfigurationException: An exception occurred when decoding using the AutomaticPojoCodec.
Decoding into a 'GameCharacter' failed with the following exception:
Cannot find a public constructor for 'GameCharacter'.
A custom Codec or PojoCodec may need to be explicitly configured and registered to handle this type.
这让我感到困惑,因为我为 GameCharacter 类提供了一个公共(public)构造函数。我不清楚为什么程序找不到它。
遵循this question中的答案,我还尝试了以下方法来设置编解码器:
ClassModel<GameCharacter> gameCharacterClassModel = ClassModel.builder(GameCharacter.class).enableDiscriminator(true).build();
CodecRegistry defaultCodecRegistry = MongoClient.getDefaultCodecRegistry();
CodecRegistry pojoCodecRegistry = fromRegistries(defaultCodecRegistry, fromProviders(PojoCodecProvider.builder().register(gameCharacterClassModel).automatic(true).build()));
return pojoCodecRegistry;
...但是,这仅将错误消息稍微更改为:
org.bson.codecs.configuration.CodecConfigurationException: Cannot find a public constructor for 'GameCharacter'.
我需要做什么才能再次从 MongoDB 检索 GameCharacterObject?
最佳答案
我明白了。
该错误消息有些误导。实际上,问题在于它需要一个空构造函数不带参数,所以我上面的类中的构造函数自然无法工作。定义的确切要求here具体如下:
By default all POJOs must include a public or protected, empty, no arguments, constructor.
因此,可以通过将 GameCharacter 类更改为如下所示来解决该问题:
public class GameCharacter {
public String name;
public Weapon weapon;
public Armor armor;
public GameCharacter() {
}
public GameCharacter(String name, Weapon weapon, Armor armor) {
this.name = name;
this.weapon = weapon;
this.armor = armor;
}
}
关于java - MongoDB Java CodecConfigurationException 找不到公共(public)构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60756994/