2015-10-29 55 views
0

基於https://jira.mongodb.org/browse/JAVA-1741我試圖實現和使用TimestampCodec,並期望讀取MongoCollection時使用decode(),但出於某種原因decode()不是 執行,因此數據庫的IsoDate值被轉換爲java.util .Date代替預期的java.sql.Timestamp。如何讓MongoCollectoin返回java.sql.Timestamp?

什麼是正確的方式來使我的TimestampCodec.decode()檢索MongoCollection時使用?

我有以下,但它與失敗java.lang.AssertionError:expected:< class [Ljava.sql.Timestamp; >卻被:<類java.util.Date >

@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()), 
      MongoClient.getDefaultCodecRegistry(), 
      CodecRegistries.fromProviders(documentCodecProvider)); 
    Builder optionsBuilder = new MongoClientOptions.Builder(); 
    optionsBuilder.codecRegistry(MongoCodecs.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(); 
    } 
} 

回答

3

除了一些小錯誤,解決辦法是改變編解碼登記的順序,以MongoClient.getDefaultCodecRegistry()是最後一個。

正確的代碼是:

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