背景
簡化版錯誤日誌:
[WARN]SqlExceptionHelper : SQL Error: 1366, SQLState: HY000
[ERROR]SqlExceptionHelper : Incorrect string value: '\xE5\xB0\xBC\xE7\x8E\x9B' for column 'string' at row 1
[INFO]AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements
[ERROR][dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not execute statement; nested exception is org.hibernate.exception.GenericJDBCException: could not execute statement] with root cause
java.sql.SQLException: Incorrect string value: '\xE5\xB0\xBC\xE7\x8E\x9B' for column 'string' at row 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) ~[mysql-connector-java-8.0.28.jar!/:8.0.28]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.28.jar!/:8.0.28]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953) ~[mysql-connector-java-8.0.28.jar!/:8.0.28]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1098) ~[mysql-connector-java-8.0.28.jar!/:8.0.28]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1046) ~[mysql-connector-java-8.0.28.jar!/:8.0.28]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1371) ~[mysql-connector-java-8.0.28.jar!/:8.0.28]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1031) ~[mysql-connector-java-8.0.28.jar!/:8.0.28]
BUG探究
很顯然是字符集的問題。通過SHOW CREATE TABLE 表名;
發現由Spring Data JPA根據@Entity
類自動創建的表的默認字符集爲latin1
,將其修改爲utf-8
應該可以解決問題。
先做最簡單的嘗試,我用可視化數據庫操作工具HeidiSQL
直接把相應的表的默認字符集latin1_swedish_ci
修改爲utf8_general_ci
,然後點擊保存,結果居然失敗了(在0.1s內又跳回了latin1)。於是我勾選旁邊的轉換數據
再次修改字符集並點保存,還是不管用。
迫不得已只能通過命令行操作,用下面這個命令:
alter table 表格名稱 convert to character set utf8;
通過HeidiSQL
刷新查看字符集發現還是沒有變化。於是我重啓了一下HeidiSQL
然後再查看字符集終於是utf8_general_ci
因此推測剛纔沒用命令行其實已經修改成功了,只是需要重新連接一下數據庫。
改好了字符集,我啓動原來報錯的那個spring boot web服務程序
,再次POST
中文數據。
這一次插入數據很順利,沒報任何錯誤。且直接查看數據表數據或者GET
數據其中的中文也沒有任何亂碼。
既然好使就暫且手動改着,反正目前也沒有幾張表。。。。。。。。。。。。。。如何根治該問題而不需要手動,網上看了下需要添加一些代碼。。。。。。。。。。有空再探究吧!