Search code examples
javarestjava-8java-timelocaldate

Which datatype to use at JPA entity to store and retrieve date using java 8


I am using java 8 version in my application, I have confused to use java date classes like java.util.Date and java.time.LocalDate at entity and dto level. Before java 8, we used to use either java.sql.Date or java.util.Date but in java 8 introduced LocalDate so can I use LocalDate for both entity and dto class.

My date format should be either dd-MM-yyyy or dd/MM/yyyy, dto is used as Rest API request body and enity as we know this is the model to maps with database.

Can I use LocalDate for both entity and dto, in the database table column datatype is Date.


Solution

  • Definitely you can and should use LocalDate class. Also you should use annotation

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
    

    over a your variable declaration or over a getter method for it. Here is a very good question with excellent answer that deals with the same topic but just for ZonedDateTime class: Spring Data JPA - ZonedDateTime format for json serialization