作者:ywf158 | 来源:互联网 | 2023-01-30 15:25
我的旅程开始于我尝试配置MongoDB的Java驱动程序以使用UUID v4而不是默认设置的Legacy UUID v3.
我在这里找到了这个解决方案https://groups.google.com/forum/#!msg/mongodb-user/ZJKQpMpCMU4/dW5ATHTcAvgJ.
但正如他所说:
请注意,使用旧版API时,将忽略编解码器注册表,因此不会使用重写的UUIDCodec
它不适用于我的MongoRepositoy
.
这是我的实际配置:
@Bean
public MongoDbFactory mongoDbFactory() throws Exception {
ServerAddress server = new ServerAddress(host,port);
MongoClientOptions.Builder mcoBuilder = MongoClientOptions.builder();
CodecRegistry codecRegistry = fromRegistries(fromCodecs(new UuidCodec(UuidRepresentation.STANDARD)),
MongoClient.getDefaultCodecRegistry());
mcoBuilder.codecRegistry(codecRegistry).build();
MongoClientOptions optiOns= mcoBuilder.build();
MongoClient mOngoClient= new MongoClient(server,options);
return new SimpleMongoDbFactory(mongoClient, mongoDataBase);
}
@Bean
public MongoTemplate mongoTemplate() throws Exception {
MongoTemplate mOngoTemplate= new MongoTemplate(mongoDbFactory());
return mongoTemplate;
}
如果我做:
mongoClient.getDatabase(mongoDataBase).getCollection("test")
.insertOne(new Document("_id",UUID.randomUUID()));
我明白了:
{ "_id" : BinData(4,"f0u8ig4TS6KaJGK93xmvNw==") }
除此以外:
mongoTemplate.getCollection("test")
.insert(new BasicDBObject("_id", UUID.randomUUID()));
结果:
{ "_id" : BinData(3,"mUX4PTPBJo6bIjPufHf0vg==") }
我知道MongoRepository
使用MongoTemplate
,虽然我已经设置了使用的实例,MongoClient
而不是旧的Mongo
,仍然无法正常工作.有什么解决方案吗?