Al Grant
Al Grant

Reputation: 2354

Spring boot project with LocalDateTime

Can you use LocalDateTime with a Spring Boot project and if so how?

I tried to follow this post and added the dependancy and the line required in application.properties but I still get :

java.io.StreamCorruptedException: invalid stream header: 32303137

When persisting data or trying to view existing data with dates created using Java.Util.Date.

Upvotes: 0

Views: 2256

Answers (1)

Al Grant
Al Grant

Reputation: 2354

Ok, so I got it to go. It required multiple changes to make both Hibernate & Springboot & Thymeleaf all work with Java 8 - LocalDateTime.

Hibernate

Add dependencies:

compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.4.0")
compile group: 'org.hibernate', name: 'hibernate-java8'

Add the following to application.properties:

spring.jackson.serialization.write_dates_as_timestamps=false

The annotations on my entities look like:

@JsonFormat(pattern="yyyy-MM-dd")
@DateTimeFormat(iso = DateTimeFormat.ISO.TIME)
private LocalDateTime somedate;

Although that didn't seem to be strictly needed.

Thymeleaf

add dependency:

compile group: 'org.thymeleaf.extras', name: 'thymeleaf-extras-java8time', version: '3.0.0.RELEASE'

Make sure it matches your Thymeleaf version.

In any HTML in the project your dates fields should now use #temporals instead of #dates. ie:

<td th:text="${#temporals.format(object.somedate, 'yyyy-MM-dd HH:mm')}">12/12/2018</td>

Spring boot

In my Application.java class I added:

@Bean
public Java8TimeDialect java8TimeDialect() {
    return new Java8TimeDialect();
}

The following resources were invaluable:

http://blog.codeleak.pl/2015/11/how-to-java-8-date-time-with-thymeleaf.html#comment-form (Thymeleaf/Springboot)

https://www.thoughts-on-java.org/hibernate-5-date-and-time/ (Hibernate)

Upvotes: 1

Related Questions