首先,我正在使用旧的mongo驱动程序(1.5.6),但无法更新它。另外,在使用MongoTemplate
时,我们也遇到了严重的性能问题,因此我们决定避免使用它。相反,我们遍历DBCollection
public class CustomMongoTemplate {
private final DBCollection collection;
private DBToEntityTranslator dbToEntityTranslator = new DBToEntityTranslator();
public CustomMongoTemplate(MongoConfig mongoConfiguration) {
collection = mongoConfiguration.getCollection();
}
public List<MyEntity> find(Query query) {
return convert(doFind(query));
}
private DBCursor doFind(Query query) {
return collection.find(query.getQueryObject());
}
private List<MyEntity> convert(DBCursor cursor) {
List<MyEntity> entities = new ArrayList<>();
while (cursor.hasNext()) {
entities .add(dbToEntityTranslator.toEntity((cursor.next())));
}
return entities ;
}
}
这是我的配置类。
@Configuration
public class MongoConfig extends AbstractMongoConfiguration {
private DBCollection collection;
@PostConstruct
private void init() throws Exception {
DB db = mongo().getDB(dbName);
collection = db.getCollection("mycollection");
}
@Override
protected String getDatabaseName() {
return dbName;
}
@Override
public Mongo mongo() throws Exception {
CodecProvider pojoCodecProvider = PojoCodecProvider.builder().register("com.company.entities").build();
CodecRegistry pojoCodecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(), fromProviders(pojoCodecProvider));
MongoClientOptions mongoClientOptions = MongoClientOptions.builder().codecRegistry(pojoCodecRegistry).build();
return new MongoClient(Collections.singletonList(new ServerAddress(host, port)),
Collections.singletonList(MongoCredential.createMongoCRCredential(userName, dbName, password.toCharArray())),
mongoClientOptions);
}
如您所见,我正在尝试在CodecRegistry
中注册我的实体类,所以我可以使用看起来像这样的Criteria
criteria.add((Criteria.where("root.myEntity").exists(true).all(myEntity)));
myEntity
是我应注册的类com.company.entities.MyEntity
的对象。但是,当我尝试运行此代码时,我会得到
“找不到类com.company.entities.MyEntity的编解码器。”