gpt4 book ai didi

java - Mongodb Java SDK 不使用@BsonProperty 作为字段名称

转载 作者:行者123 更新时间:2023-12-04 13:27:08 24 4
gpt4 key购买 nike

我正在使用 mongodb-driver-sync库,版本:4.2.3在我的 Java 项目中将值插入到 MongoDB 集合中。当我插入它们时,字段名称不是 @BsonProperty 中的值注释,但 Java 变量名的小驼峰大小写。如何让它使用我的注释值?
我的 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'

最佳答案

也许这是约定俗成的问题。您的属性都以大写字母开头。由于 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

关于java - Mongodb Java SDK 不使用@BsonProperty 作为字段名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67639351/

24 4 0
文章推荐: reactjs - 在 React 错误中实现 Google 登录 -
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com