首页 > 解决方案 > 使用 MongoDB Java 驱动程序时未插入 LocalDate

问题描述

我的图书馆是:

implementation group: 'org.mongodb', name: 'mongodb-driver-sync', version: '4.3.2'
implementation group: 'org.mongodb', name: 'bson', version: '4.3.2'

我有 Java 对象,例如:

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Objects;

import org.bson.codecs.pojo.annotations.BsonProperty;
import org.bson.types.ObjectId;

public class TestFile {

    protected ObjectId id;
    @BsonProperty(value = "report_date")
    public LocalDate reportDate;
    @BsonProperty(value = "asset_title")
    public String assetTitle;
    @BsonProperty(value = "asset_type")
    public String assetType;
    @BsonProperty(value = "revenue")
    public Double revenue;
    @BsonProperty(value = "modified_datetime")
    private LocalDateTime modifiedDateTime;

    public ObjectId getId() {
        return id;
    }
    public TestFile setId(ObjectId id) {
        this.id = id;
        return this;
    }
    public LocalDate getReportDate() {
        return reportDate;
    }
    public TestFile setReportDate(LocalDate reportDate) {
        this.reportDate = reportDate;
        return this;
    }
    public String getAssetTitle() {
        return assetTitle;
    }
    public TestFile setAssetTitle(String assetTitle) {
        this.assetTitle = assetTitle;
        return this;
    }
    public String getAssetType() {
        return assetType;
    }
    public TestFile setAssetType(String assetType) {
        this.assetType = assetType;
        return this;
    }
    public Double getRevenue() {
        return revenue;
    }
    public TestFile setRevenue(Double revenue) {
        this.revenue = revenue;
        return this;
    }
    public LocalDateTime getModifiedDateTime() {
        return modifiedDateTime;
    }
    public TestFile setModifiedDateTime(LocalDateTime modifiedDateTime) {
        this.modifiedDateTime = modifiedDateTime;
        return this;
    }
}

我的插入代码是:

MongoDatabase db = MongoDBConnector.getInstance().getDatabase(dbName);
MongoCollection collection = db.getCollection(collectionName, documentClass);
collection.insertMany(documents);

当我将此对象插入 MongoDB 时,没有插入LocalDates 和s。LocalDateTime以前,这些是java.util.Dates。那时,它们正在被插入。换到新旧后,他们就没有了。我怎样才能插入它们?

标签: javamongodb

解决方案


推荐阅读