MySQL Date Changes to Yesterday's date After JPA Save

I think its because of Timezone problem. Locale Date do not consider the timezone as you already know. But In the database, I guess the date is associated with Timezone. The JPA/Hibernate layer will convert the LocaleDate to TimeStamp( default it will take JVM timezone during the conversion ). The timezone that your running the application is different from the database timezone, due to this there is mismatch.

To confirm on this, set the timezone of the running machine to UTC.


Thanks for your help. As noted and answered above, it was a Timezone issue.

Solution:

  1. Set in MySQL SET GLOBAL time_zone = '+02:00';";
  2. Remove ?serverTimezone=UTC from spring.datasource.url=jdbc:mysql://localhost:3306/schema_name

Found these MySQL commands useful: SELECT @@GLOBAL.time_zone, @@session.time_zone, @@system_time_zone; and SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP) as GMT_TIME_DIFF;

Additional information Should MySQL have its timezone set to UTC? and in the MySQL Documentaion.

Workaround

As answered above, changing the Spring Boot default mysql-connector-java in pom.xml:

<dependency>
 <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</>
</dependency>

And the driver to spring.datasource.driverClassName=com.mysql.jdbc.Driver in properties file also returned the proper date.


If your timezone is for example

Europe/Warsaw

you can set:

spring.datasource.url=jdbc:mysql://localhost:3306/database?serverTimezone=Europe/Warsaw

instead of this:

spring.datasource.url=jdbc:mysql://localhost:3306/database?serverTimezone=UTC

but you can also add one more entry in application.properties:

spring.jpa.properties.hibernate.jdbc.time_zone=Europe/Warsaw