首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> MySQL 資料庫 >> MySQL 綜合教學

Hibernate + MySQL 中文亂碼終極解決方案

     編輯:MySQL 綜合教學

Hibernate + MySQL 中文問題 90% 來自 **三層編碼不一致**。

三層統一配置

層級配置位置標準值
資料庫/表/欄位DDL / my.cnfCHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
JDBC 連線hibernate.cfg.xml / Spring DataSourceuseUnicode=true&characterEncoding=UTF-8
Web 請求/回應web.xml Filter / Spring CharacterEncodingFilterUTF-8

Hibernate 具體配置



jdbc:mysql://localhost:3306/db?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Taipei
root
pwd
com.mysql.cj.jdbc.Driver
utf8mb4
utf8mb4
true

Web 編碼 Filter (Spring Boot 內建)



# application.yml
server:
  servlet:
    encoding:
      charset: UTF-8
      force: true
      force-request: true
      force-response: true

舊版 Spring MVC 手動註冊




  encodingFilter
  org.springframework.web.filter.CharacterEncodingFilter
  
    encoding
    UTF-8
  
  
    forceEncoding
    true
  


  encodingFilter
  /*

驗證清單

  1. MySQL CLI:SHOW VARIABLES LIKE 'character_set%'; 全為 utf8mb4
  2. 資料表:SHOW CREATE TABLE t\G 顯示 CHARSET=utf8mb4
  3. 3. 插入中文:session.save(new Entity("測試")); 無報錯 4. 查詢中文:list.get(0).getName() 顯示正常 5. 瀏覽器 Network:Response Header Content-Type: text/html; charset=UTF-8

核心:**資料庫 utf8mb4 + JDBC useUnicode=true&characterEncoding=UTF-8 + Web Filter UTF-8**,三層缺一不可。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved