【发布时间】:2018-10-26 05:10:19
【问题描述】:
更新 2: 我想我已经取得了一些进展。我的 IDE 对我的代码更满意,但我只有最后一行不高兴:
CodecRegistry pojoCodecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(),
fromProviders(PojoCodecProvider.builder().automatic(true).build()));
MongoClientURI connectionString = new MongoClientURI("my-mongo-string");
MongoClient mongoClient = new MongoClient(connectionString);
MongoDatabase database = mongoClient.getDatabase("New");
database = database.withCodecRegistry(pojoCodecRegistry);
MongoCollection<? extends Person> collection = database.getCollection("people", this.getClass());
collection = collection.withCodecRegistry(pojoCodecRegistry);
collection.insertOne(this);
我已将“集合”的名称替换为“人员”,以暂时防止与 Java 的“集合”发生冲突。除了最后一行,一切似乎都很好,这给了我这个错误:insertOne (capture<? extends Utils.Person>) in MongoCollection cannot be applied to (Utils.Person)。 'this' 指的是我的 person 类。我在这里做错了什么?
更新: 原始问题如下。我相信我现在已经确定仿制药是我最好的选择。但是,我在“生成”这两行时遇到了一些问题(假设我已正确初始化数据库):
MongoCollection<MyClass> collection = database.getCollection("SomeString", MyClass.class);
最好的方法是什么? Java 似乎不喜欢在泛型上使用 .class。
原问题:
所以我想利用 MongoDB 驱动程序存储 PJOS 的能力。 Example Here。但是我计划将多个类存储到数据库中,并且我不想每次都重新键入所有连接代码,也不想复制和粘贴然后对每个类的代码进行细微修改。我有创建一个“集合”类的想法,然后扩展它,但它并没有按照我的意图工作。这是我的代码:
public class Collection {
private MongoCollection<Collection> collection;
public Collection(){}
public Collection(String databaseName){
databaseName = databaseName.toLowerCase().replaceAll(" ", "");
CodecRegistry pojoCodecRegistry = fromRegistries(com.mongodb.MongoClient.getDefaultCodecRegistry(),
fromProviders(PojoCodecProvider.builder().automatic(true).build()));
MongoClientURI connectionString = new MongoClientURI("my-mongo-connection-string");
com.mongodb.MongoClient mongoClient = new com.mongodb.MongoClient(connectionString);
MongoDatabase database = mongoClient.getDatabase(databaseName);
database = database.withCodecRegistry(pojoCodecRegistry);
collection = database.getCollection(this.getClass().getName(), Collection.class);
}
public Collection findOne(Document document){
return collection.find(document).first();
}
public void save(){
collection.insertOne(this);
}
}
如您所见,我希望能够将数据库名称传递给从此类继承的任何类(或任何正确的做法。),并让我的代码连接到数据库并查找或正确保存相应子类的 POJO。例如,如果我有一个带有电话号码的 Person 类,我可以扩展我的 Collections 类并依靠一切工作。现在,当我在子类上调用 save 函数时,它会尝试保存父 Collection,我收到错误 Can't find a codec for class Utils.MongoDb.Collection.(我的 Collection 类在我自己的 Utils.MongoDb 命名空间中)。我只是错过了什么吗?有没有更好的方法来解决这个问题?我认为让它工作的唯一方法是将我的 Collection 构造函数中的代码复制并粘贴到每个类中,并使用正确的类变量对其进行修改。我希望这一切都清楚。提前致谢!
【问题讨论】:
标签: java mongodb generics inheritance design-patterns