Spring项目升级mysql-connector-java至8.0.11遇日期及时区异常问题
Hey there, I’ve helped tons of developers work through these exact problems when moving to MySQL’s 8.x JDBC driver—let’s break down each issue and fix them step by step.
1. Resolving the "InvalidConnectionAttributeException" Time Zone Error
This error happens because the 8.x driver is way stricter about time zone configurations than 6.x. The PET (Peru Time) identifier is ambiguous to the driver, so we need to specify a precise, IANA-standard time zone value. Here are your go-to fixes:
Option 1: Update your JDBC URL with the serverTimezone parameter
Modify your database connection URL to use the official IANA time zone ID for Peru Time: America/Lima. This is the value the driver reliably recognizes:
jdbc:mysql://your-db-host:3306/your-db-name?serverTimezone=America/Lima
If you’re using Spring Boot, add this to your application.properties:
spring.datasource.url=jdbc:mysql://your-db-host:3306/your-db-name?serverTimezone=America/Lima
Option 2: Configure the MySQL server’s default time zone
If you have access to the server config, set the default time zone directly to avoid needing the JDBC parameter:
- On Linux, edit
my.cnf(usually in/etc/mysql/) and add this under the[mysqld]section:default-time-zone = America/Lima - On Windows, edit
my.iniand add the same line under[mysqld]. - Restart the MySQL service for changes to take effect.
2. Fixing Unexpected Date Value Changes
The date shifts are almost always tied to the driver’s updated datetime handling logic. In 6.0.6, the driver used legacy datetime parsing by default, but 8.0.11 disables this by default. Here’s how to fix it:
Option 1: Adapt to Java 8+ Time APIs (Recommended)
The 8.x driver is built to work seamlessly with Java’s modern java.time APIs (like LocalDate, LocalDateTime). If your code was using older types like java.util.Date or java.sql.Date, migrating to these new types will resolve date discrepancies long-term:
- Update your entity class fields to use
LocalDate(for DATE columns) orLocalDateTime(for DATETIME/TIMESTAMP columns). - Hibernate 5.2+ supports these types out of the box, so no extra config is needed if you’re using it.
Option 2: Re-enable Legacy Datetime Handling (Quick Fix)
If you need to keep your existing code without rewriting date logic, add the useLegacyDatetimeCode=true parameter to your JDBC URL alongside the timezone setting:
jdbc:mysql://your-db-host:3306/your-db-name?serverTimezone=America/Lima&useLegacyDatetimeCode=true
This forces the driver to use the same datetime parsing logic as the 6.x version, making your date values match what you saw before the upgrade.
Critical Check: Ensure Time Zone Consistency
Double-check that the MySQL server’s time zone, the JDBC driver’s configured time zone, and your application server’s time zone all match. Mismatches here are a hidden, common cause of date shifts.
内容的提问来源于stack exchange,提问作者Manuel Jordan




