我已按照教程Getting Started with the 3.0 Java Driver。
但是当我使用java.sql.Timestamp值保存doc时,有关于编解码器的错误。我知道从驱动程序3.x开始,有一些关于编解码器的东西,但我不知道如何使用它们来解决这个问题。
我习惯于2.x驱动程序,但是3.x驱动程序的新功能。
答案 0 :(得分:0)
尝试以这种方式更改代码注册表的顺序:
@Test
public void testTimestamp() {
Map<BsonType, Class<?>> replacements = new HashMap<BsonType, Class<?>>();
replacements.put(BsonType.DATE_TIME, Timestamp.class);
BsonTypeClassMap bsonTypeClassMap = new BsonTypeClassMap(replacements);
DocumentCodecProvider documentCodecProvider =
new DocumentCodecProvider(bsonTypeClassMap);
CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
CodecRegistries.fromCodecs(
new TimestampCodec()),
CodecRegistries.fromProviders(documentCodecProvider),
MongoClient.getDefaultCodecRegistry());
Builder optionsBuilder = new MongoClientOptions.Builder();
optionsBuilder.codecRegistry(codecRegistry);
MongoClientOptions options = optionsBuilder.build();
MongoClient mongo = new MongoClient(new ServerAddress(), options);
MongoDatabase db = mongo.getDatabase("mydb");
MongoCollection<Document> collection = db.getCollection("test");
try {
collection.insertOne(new Document("date", new Timestamp(new Date().getTime())));
assertEquals(Timestamp.class, collection.find().first().get("date").getClass());
} finally {
collection.drop();
mongo.close();
}
}