JAVA 處理 Spring data mongodb 時區問題


Spring data mongodb 查詢出結果的時候會自動 + 8小時,所以我們看起來結果是對的

但是我們查詢的時候,並不會自動 + 8小時,需要自己處理

 

解決方法 1   @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") 

但是此注解,僅針對json 數據轉換的時候處理,如果是form 提交 urlencoded 的時候就沒辦法了

    @Transient
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    @JsonSerialize(using = LocalDateTimeSerializer.class)
    @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createDate;

雖然我們可以在 里面注冊自定義的格式化,在進入Controller的時候 自動處理,但是 可能我們存在 mysql 跟 Mongodb 不同的 數據庫,這種方式顯然有些武斷.

    @InitBinder
    public void initBinder(WebDataBinder binder)

解決方法 2 查詢Mongodb 的時候,手動處理

 if (orderInfo.getCreateEndDate() != null && orderInfo.getCreateDate() != null)
            query.addCriteria(where("objectId").gte(new ObjectId(LocalDateTimeUtil.LocalDateTimeToUdate(orderInfo.getCreateDate().plusHours(8)))).lte(new ObjectId(LocalDateTimeUtil.LocalDateTimeToUdate(orderInfo.getCreateEndDate().plusHours(8)))));
        else {
            Optional.ofNullable(orderInfo.getCreateDate()).ifPresent(createDate -> query.addCriteria(where("objectId").gte(new ObjectId(LocalDateTimeUtil.LocalDateTimeToUdate(createDate.plusHours(8))))));
            Optional.ofNullable(orderInfo.getCreateEndDate()).ifPresent(endDate -> query.addCriteria(where("objectId").lte(new ObjectId(LocalDateTimeUtil.LocalDateTimeToUdate(endDate.plusHours(8))))));
        }

 

logback 打開debug 顯示 Spring data mongodb 的查詢語句,方便調試

    <Logger name="org.mongodb.driver" level="debug" />
    <logger name="org.springframework.data.mongodb.core.MongoTemplate" level="debug" />
{ "$gte" : { "$date" : "2017-11-01T00:00:00.000Z"}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM