回答问题

我在我的 Java 项目中使用mongodb-driver-sync库,版本:4.2.3将值插入到 MongoDB 集合中。当我插入它们时,字段名称不是@BsonProperty注释中的值,而是 Java 变量名称的小写字母。如何让它使用我的 annonation 值?

我的 POJO 是:

public class Product {
    private ObjectId id;
    @BsonProperty(value = "product_sk")
    private String ProductSK;
    @BsonProperty(value = "product_id")
    private String ProductID;
    @BsonProperty(value = "upc")
    public String UPC;

    public ObjectId getId() {
        return id;
    }

    public Product setId(ObjectId id) {
        this.id = id;
        return this;
    }

    public String getProductSK() {
        return ProductSK;
    }

    public Product setProductSK(String productSK) {
        ProductSK = productSK;
        return this;
    }

    public String getProductID() {
        return ProductID;
    }

    public Product setProductID(String productID) {
        ProductID = productID;
        return this;
    }

    public Product setUPC(String uPC) {
        UPC = uPC;
        return this;
    }
}

我的插入代码是:

public void insertProduct(List<Product> products) {
    ConnectionString connectionString = new ConnectionString(MONGO_URI);
    CodecRegistry pojoCodecRegistry = fromProviders(PojoCodecProvider.builder().automatic(true).build());
    CodecRegistry codecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), pojoCodecRegistry);
    MongoClientSettings clientSettings = MongoClientSettings.builder()
                                                            .applyConnectionString(connectionString)
                                                            .codecRegistry(codecRegistry)
                                                            .build();
    try (MongoClient mongoClient = MongoClients.create(clientSettings)) {
        MongoDatabase db = mongoClient.getDatabase(DATABASE);
        MongoCollection<Product> productCollection = db.getCollection("products", Product.class);
        productCollection.insertMany(products);
    }
}

输入的 BSON 是:

{ "_id" : ObjectId("60afb7be0af8954d7ce91b8f"), "productID" : "test1", "productSK" : 123, "uPC" : "test2" }

它应该是:

{ "_id" : ObjectId("60afb7be0af8954d7ce91b8f"), "product_id" : "test1", "product_sk" : 123, "upc" : "test2" }

我的依赖是:

implementation 'com.google.code.gson:gson:2.8.6'
implementation group: 'org.mongodb', name: 'mongodb-driver-sync', version: '4.2.3'
implementation group: 'org.mongodb', name: 'mongodb-crypt', version: '1.2.0'

Answers

也许这是一个约定俗成的问题。您的属性都以大写字母开头。由于 getter/setter 约定建议这种属性应该以小写字母开头,我会尝试这样的事情:

private ObjectId id;
@BsonProperty(value = "product_sk")
private String productSK; // instead of ProductSK
@BsonProperty(value = "product_id")
private String productID; // instead of ProductID
@BsonProperty(value = "upc")
public String upc; // or uPC
Logo

MongoDB社区为您提供最前沿的新闻资讯和知识内容

更多推荐