尝试使用MongoDB集合填充Java Pojo类并获得null

p8h8hvxi  于 2023-01-16  发布在  Java
关注(0)|答案(1)|浏览(116)

我尝试使用Mongo DB集合填充Java POJO类,但在尝试从Pojo类获取数据时得到null
这里,CSVRowPOJO类名

类构造函数

MongoDatabase database;

MongoDbUtils() {
    String uri = "mongodb://localhost:27017/?maxPoolSize=20&w=majority";

    //This registry is required for your Mongo document to POJO conversion
    ConnectionString connectionString = new ConnectionString(uri);
    CodecRegistry pojoCodecRegistry = fromProviders(PojoCodecProvider.builder().automatic(true).build());
    CodecRegistry codecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), pojoCodecRegistry);
    MongoClientSettings clientSettings = MongoClientSettings.builder()
            .applyConnectionString(connectionString)
            .codecRegistry(codecRegistry)
            .build();
    MongoClient mongoClient = MongoClients.create(clientSettings);
    database = mongoClient.getDatabase("StudyPriceDataTest");
}

从POJO检索数据的函数

public MongoCollection<CsvRow> RetriveAllDocumentsInCSVRows(String collectionName) {
    System.out.println(collectionName);
    MongoCollection<CsvRow> collection = database.getCollection(collectionName, CsvRow.class);
    List<CsvRow> csvRows = collection.find(new Document(), CsvRow.class).into(new ArrayList<CsvRow>());
    for(CsvRow doc:csvRows) {
        System.out.println("vinsds="+doc.getVin()); **<-- here I am getting null**
    }
    return collection;
}

我尝试了上面提到的代码,希望从POJO获得数据

pjngdqdw

pjngdqdw1#

我们可以用

public List<CsvRow> RetriveAllDocumentsInCSVRows(String collectionName) {
    List<CsvRow> userList = new ArrayList<CsvRow>();
    List<CsvRow> collection = database.getCollection(collectionName, CsvRow.class).find().into(userList);
    // return all documents in the collection
    for (CsvRow u : userList) {
        System.out.println(u.getVin());
    }

    return collection;
}

相关问题