轉載:https://www.jianshu.com/p/bd0311a33c16
現象:
搭建spring boot+mybatis+mysql時出現插入mysql的中文出現亂碼???。

mysql插入中文亂碼
現象分析:
- 首先懷疑mysql字符編碼格式不是utf-8導致
- 在服務器端編碼格式錯誤,導致存到mysql也是亂碼
- mybatis配置不正確,導致亂碼
問題排查:
- mysql編碼格式
查看建表時是否執行編碼格式:
show create table t_user;
輸出如下:

create語句
可以看到DEFAULT CHARSET=utf8,建表時已經指定了編碼格式。檢查mysql配置,也沒有問題(mysql配置在這不贅述了,網上很多例子)。
於是,手動插入一條數據,中文能正確插入,因此排除mysql的問題。
- 服務端編碼格式
用debug模式調試,在controller層和service層中文顯示都是正常的
服務器調試.png
3.mybatis的配置問題
現在排除了其他兩種可能,於是重新查看mybatis和datasource的配置
配置如下:
spring:
datasource:
name: test type: com.alibaba.druid.pool.DruidDataSource filters: stat driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/mytest?nullNamePatternMatchesAll=true&serverTimezone=GMT%2b8 username: root password: 123456 initial-size: 1 min-idle: 1 max-active: 20 max-wait: 60000 time-between-eviction-runs-millis: 60000 min-evictable-idle-time-millis: 300000 validation-query: SELECT 'x' test-while-idle: true test-on-borrow: false test-on-return: false pool-prepared-statements: false max-pool-prepared-statement-per-connection-size: 20
發現在url配置項中沒有指定編碼格式,於是將url配置項改成
url: jdbc:mysql://127.0.0.1:3306/mytest?ullNamePatternMatchesAll=true&serverTimezone=GMT%2b8?useUnicode=true&characterEncoding=utf8
重啟項目,重新插入數據,插入正確。

編碼格式正確
總結
在使用spring boot集成mybatis,mysql的url一定要加上useUnicode=true&characterEncoding=utf8兩個配置項,否則插入中文數據亂碼。至此,mysql插入中文亂碼的問題得以解決,分析中的1、3兩點是經常出現問題的原因,因此遇到這類問題先從這兩個原因下手。如果有大神還有別的見解,可以留言交流