Cannot serialize LocalDate in Mongodb

前端 未结 3 487
闹比i
闹比i 2021-01-13 07:38

I am using the java 8 java.time.LocalDate to parse around dates.

But trying to insert a LocalDate object to mongodb. I get errors in the java driver:



        
3条回答
  •  没有蜡笔的小新
    2021-01-13 07:42

    Unfortunately, the MongoDB driver uses the java.util.Date type, see the docs here

    So you have to convert your LocalDate to a Date instance first, for example:

    MongoClient mongoClient = new MongoClient("localhost", 27017);
    DB db = mongoClient.getDB("test");
    DBCollection coll = db.getCollection("testcol");
    
    LocalDate ld = LocalDate.now();
    Instant instant = ld.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
    Date date = Date.from(instant);
    
    BasicDBObject doc = new BasicDBObject("localdate", date);
    coll.insert(doc);
    

    I would suggest using something like Morphia or Jongo to wrap the MongoDB driver though, as you can register global mappers to implicitly do these conversions on the fly, so that you can use LocalDate, etc, in your domain model

提交回复
热议问题