2016-02-22 54 views
1

我使用Spring Boot和Data Rest在Java8中創建一個簡單的微服務,並在我的JSON響應的Date屬性中獲取錯誤的序列化值。Spring Data(Rest):日期序列化映射返回一個錯誤的值

我的實體:

@Entity 
public class ArchivedInvoice implements Serializable { 
    ... 
    @Column 
    private java.util.Date invoiceDate; 
    ... 
} 

我的倉庫接口:

@RepositoryRestResource(collectionResourceRel = "archivedinvoices", path = "archivedinvoices") 
public interface ArchivedInvoiceRepository extends PagingAndSortingRepository < ArchivedInvoice, Long > { 
    ... 
     @RestResource(rel = "findByDate", path = "findByDate") 
     public Page<ArchivedInvoice> findByInvoiceDate(@Param("invoiceDate") @Nullable @DateTimeFormat(iso = ISO.DATE) Date invoiceDate, Pageable pageable); 
    ... 
} 

的Postgres保存在一個簡單的日期屬性(invoice_date日期NOT NULL - '2016年2月22日'),但JSON響應回覆:

"invoiceDate" : "2016-02-21T23:00:00.000+0000" 

我該如何避免這種情況?

+0

您只需在該字段中輸入['@Temporal(DATE)'annotation](https://docs.oracle.com/javaee/5/api/javax/persistence/Temporal.html)。如果沒有它,JPA會將該字段視爲「時間戳」(顯然與時區)。 – pozs

+0

當我刪除@DateTimeFormat註釋時,這也很好用!謝謝! – user2722077

回答

1

java.util.Date實際上是一個時間戳:

類Date表示特定的瞬間,以毫秒 精度。

如果SQL類型是日期,則使用java.sql.Date。 或者如果您使用java 8,則可以嘗試使用java.time.LocalDate。爲了這個工作,你需要register Springs JSR310 JPA converters

+0

好吧,'java.sql.Date'擴展了'java.util.Date',所以(理論上)它也可以代表一個特定的時刻。唯一的區別在於它們的默認綁定。 – pozs

+0

當然,但是如果'java.sql.Date'設計用來表示SQL類型date,那麼爲什麼要使用'java.util.Date'呢? – Cyril

+0

不幸的是,這是行不通的。我現在得到這個異常: 引起:org.springframework.core.convert.ConverterNotFoundException:找不到能夠從類型[java.util.Date]轉換爲類型[@ org.springframework.data.repository.query.Param @ org.springframework.format.annotation.DateTimeFormat java.sql.Date] – user2722077