MongoDB Java驱动程序3.x:如何保存java.sql.Timestamp?

时间:2015-04-07 02:55:54

标签: java mongodb

我已按照教程Getting Started with the 3.0 Java Driver

但是当我使用java.sql.Timestamp值保存doc时,有关于编解码器的错误。我知道从驱动程序3.x开始,有一些关于编解码器的东西,但我不知道如何使用它们来解决这个问题。

我习惯于2.x驱动程序,但是3.x驱动程序的新功能。

1 个答案:

答案 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();
    }
}

来自:https://stackoverflow.com/a/33436425/2119009