Spring Boot JPA配置MySQL字符集为UTF-8失败求助
我来帮你搞定这个字符集的问题!你用Spring Boot 2.0.1和Hibernate改字符集没生效,大概率是这几个环节没做到位,咱们一步步来排查:
1. 先确认数据库和表的现有字符集
首先得搞清楚:你改的配置可能只影响新创建的表,旧表的字符集不会自动变更。先跑几个SQL命令确认现状(记得替换成你的数据库和表名):
-- 查看数据库默认字符集 SELECT default_character_set_name FROM information_schema.SCHEMATA WHERE schema_name = '你的数据库名'; -- 查看目标表的字符集 SELECT table_collation FROM information_schema.TABLES WHERE table_schema = '你的数据库名' AND table_name = '你的表名'; -- 查看表中字段的字符集 SELECT column_name, character_set_name FROM information_schema.COLUMNS WHERE table_schema = '你的数据库名' AND table_name = '你的表名';
如果查到旧表还是latin1,先备份数据,然后手动修改表和字段的字符集(推荐用utf8mb4,它是MySQL真正完整的UTF-8,支持emoji这类4字节字符):
ALTER TABLE 你的表名 CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
2. 修正Spring Boot的数据源配置
Spring Boot 2.x里,数据源URL的配置优先级比Hibernate的属性更高,你可以把URL参数调整成这样:
spring.datasource.url=jdbc:mysql://localhost:3306/你的数据库名?useUnicode=true&characterEncoding=utf8mb4&serverTimezone=UTC&useSSL=false
注意这里用characterEncoding=utf8mb4而不是utf8,同时确保useUnicode=true开启——这俩是配对用的。
你之前加的Hibernate配置可以保留,但核心是数据源URL的设置:
spring.jpa.properties.hibernate.connection.CharSet=UTF-8 spring.jpa.properties.hibernate.connection.characterEncoding=UTF-8 spring.jpa.properties.hibernate.connection.useUnicode=true
3. 让Hibernate自动建表时用对字符集
如果你的项目用Hibernate自动建表(比如spring.jpa.hibernate.ddl-auto=update/create),得确保它创建表时指定正确的字符集:
全局配置方式
在application.properties里指定方言和字符集:
# 针对MySQL 5.x用这个方言,MySQL 8.x换成org.hibernate.dialect.MySQL8Dialect spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect spring.jpa.properties.hibernate.connection.characterEncoding=utf8mb4 spring.jpa.properties.hibernate.connection.CharSet=utf8mb4 spring.jpa.properties.hibernate.connection.useUnicode=true
实体类单独配置方式
如果只想给某个表指定字符集,在实体类的@Table注解上补充Hibernate的表配置:
import javax.persistence.Entity; import javax.persistence.Table; import org.hibernate.annotations.Table; @Entity @Table(name = "你的表名") @org.hibernate.annotations.Table( appliesTo = "你的表名", charset = "utf8mb4", collation = "utf8mb4_unicode_ci" ) public class YourEntity { // 你的实体字段 }
4. 检查连接池是否冲突
Spring Boot 2.0默认用HikariCP连接池,一般不会有冲突,但如果你自定义了连接池配置,要确保没有覆盖字符集相关的参数——只要URL配置正确,连接池会自动继承这些参数。
5. 重启验证
改完所有配置后,一定要重启应用!然后插入一些带特殊字符(比如中文、emoji)的数据,查询看看是否乱码,再用第一步的SQL命令检查表的字符集是否已经更新。
内容的提问来源于stack exchange,提问作者Alexandre Maia

