Some background:
I have a Java 1.6 webapp running on Tomcat 7. The database is MySQL 5.5. Previously, I was using Mysql JDBC driver 5.1.23 to connect to the DB. Ever
Apparently, to get version 5.1.33 of MySQL JDBC driver to work with UTC time zone, one has to specify the serverTimezone
explicitly in the connection string.
jdbc:mysql://localhost/db?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
This is a bug in mysql-connector-java from version 5.1.33 to 5.1.37. I've reported it here: http://bugs.mysql.com/bug.php?id=79343
Edited: This has been corrected from mysql-connector-java 5.1.39
It was a typo in TimeUtil class in loadTimeZoneMappings method that raises a NPE locating /com/mysql/jdbc/TimeZoneMapping.properties file. If you look at the code, the file should be located within TimeUtil class loader, not TimeZone:
TimeUtil.class.getResourceAsStream(TIME_ZONE_MAPPINGS_RESOURCE);
The parameter useLegacyDatetimeCode allows to correct the difference between client and server timezones automatically when using dates. So it helps you precissely not having to specify timezones in each part. Althought using serverTimeZone parameter is a workaround, and meanwhile the patch is released, you can try better correcting the code by yourself as I did.
If it's a standalone application, you can try simply to add a corrected com/mysql/jdbc/TimeUtil class to your code and be careful with jar loading order. This can help: https://owenou.com/2010/07/20/patching-with-class-shadowing-and-maven.html
If it's a web application, the easier solution is to create your own mysql-connector-java-5.1.37-patched.jar, substituting the .class directly into the original jar.
Everything that we need to fix the problem with serverTimezone
:
String url = "jdbc:mysql://localhost:3306/db?serverTimezone=" + TimeZone.getDefault().getID()
I have added the following line to my /etc/mysql/my.cnf
file:
default_time_zone='+00:00'
Restarted the MySQL server:
systemctl restart mysql
And it works like a charm.
In my case, it was a test environment and I had to make an existing application to work without any configuration changes, and if possible without any MySQL config changes. I was able to fix the issue by following @vinnyjames suggestion and changing server timezone to UTC:
ln -sf /usr/share/zoneinfo/UTC /etc/localtime
service mysqld restart
Doing that was enough for me to solve the issue.
It worked for me just by adding serverTimeZone=UTC on application.properties.
spring.datasource.url=jdbc:mysql://localhost/db?serverTimezone=UTC