2016-02-22 26 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