Used to know, JSR310
the time API is really artifact, greatly facilitates the process of time operation in Java.
The JSR 310 specification Leader Stephen Colebourne is the Joda-time author, whose main idea is to learn from Joda-time, instead of directly porting Joda-time to the Java platform, the API is similar but has been improved, For specific improvements please refer to one of its 2009 articles and Infoq's interview with him:
Http://blog.joda.org/2009/11/why-jsr-310-isn-joda-time_4941.html
http://www.infoq.com/cn/news/2010/05/jsr-310
Http://blog.joda.org/2010/12/what-about-jsr-310_153.html
Specification: https://jcp.org/en/jsr/detail?id=310
Things are very good, ordinary time directly with the line, after all, this can also be free with the old date, such as API conversion, although the writing will be slightly verbose, such as:
LocalDateTime nowLocalDateTime = LocalDateTime.now();Date nowDate = Date.from(start.atZone(ZoneId.systemDefault()).toInstant());
But for more convenient operation time can endure.
But after all, it's a new thing, and I've had two problems with the project before.
And
Spring Data JPA
Combine
I would like to Spring Data JPA
JPA
use an entity class in (hereinafter, but in JPA
fact, a specification) @Entity
as a type of LocalDateTime
attribute, such as:
@Entitypublicclass Product { ... @Column private LocalDateTime gmtCreate; ...}
The problem came, at that time specifically to forget what the exception, probably what can not be deserialized and the like, in short, it is impossible to use.
In fact, it is very simple, familiar with JPA should have been thought of, to use javax.persistence.AttributeConverter
, online there are many of their own implementation of this converter article, and spring Data JPA follow-up has also been targeted JSR310
to achieve the same org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters
.
And if you're a spring boot project, it's super easy to use, just add an annotation to the startup class and Jsr310JpaConverters
register as a bean to implement the LocalDateTime
attribute type as an entity class. The annotations are as follows:
@EntityScan(basePackageClasses = {Jsr310JpaConverters.class})
And
Jackson
Combine
Back-end problem solved, can be used when the front end, but there is a problem, the specific throw what exception I also forgot ([cover face]), probably still can not be deserialized and so on.
Help search engine learned that the original Jackson is not compatible JSR310
with the time API, so the need to introduce the corresponding Jackson
module (the key class is called com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
), if used is to Gradle
introduce the following dependencies:
compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310")
OK, perfect Deal ~
How to properly use the Java 8 time-related API in spring Data JPA and Jackson (that is, JSR 310 is the artifact under the Java.time package)