2

I use Spring Boot and Data Rest to create a simple microservice in Java8 and get a wrong serialized value in a Date attribute in my JSON response.

My entity:

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

My repository interface:

@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 saves the attribute in a simple date (invoice_date date NOT NULL - '2016-02-22') but the JSON response returns:

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

How can I avoid this?

user2722077
  • 462
  • 1
  • 8
  • 21
  • You just need a [`@Temporal(DATE)` annotation](https://docs.oracle.com/javaee/5/api/javax/persistence/Temporal.html) on the field. Without it JPA will treat that field as a `timestamp` (apparently with time zone). – pozs Feb 22 '16 at 20:07
  • This works also fine, when I remove the @DateTimeFormat annotation! Thanks! – user2722077 Feb 22 '16 at 21:00

1 Answers1

3

java.util.Date is actually a timestamp:

The class Date represents a specific instant in time, with millisecond precision.

Use java.sql.Date instead if the SQL type is date. Or if you use java 8, you can try using java.time.LocalDate. For that to work you will need to register Springs JSR310 JPA converters.

Community
  • 1
  • 1
Cyril
  • 2,376
  • 16
  • 21
  • Well, `java.sql.Date` extends `java.util.Date`, so (in theory) it also can represent a specific instant in time. The only difference is in their default bindings. – pozs Feb 22 '16 at 20:10
  • Sure, but why would you use `java.util.Date` if `java.sql.Date` is designed to represent the SQL type date? – Cyril Feb 22 '16 at 20:16
  • Unfortunately, this does not work. I get now this exception: Caused by: org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.util.Date] to type [@org.springframework.data.repository.query.Param @org.springframework.format.annotation.DateTimeFormat java.sql.Date] – user2722077 Feb 22 '16 at 20:21
  • The query parameter in your repository should also be java.sql.Date and you don't need the `@DateTimeFormat` annotation. – Cyril Feb 22 '16 at 20:27
  • sorry, actually not sure about the annotation. – Cyril Feb 22 '16 at 20:37
  • It works, when I remove the annotation and use java.sql.Date. Thanks! – user2722077 Feb 22 '16 at 20:40