今天在學習Hibernate插入數據時,一直報錯:
Exception in thread "main"
org.hibernate.exception.GenericJDBCException: could not execute statement
Caused by: java.sql.SQLException: Incorrect string value: '\xE8\x8F\x9C\xE9\xB8\x9F...' for column 'school_name' at row 1
at com.mysql.jdbc.SQLError.createSQLExceptionSQLError.java:1073)
導致原因就是數據庫和數據表的編碼方式導致的。
解決方案:
嘗試將數據庫以及數據表的編碼方式改爲UTF-8
在Hibernate中建議在配置文件hibernate.cfg.xml中添加:
<!-- 設置編碼方式爲utf-8 -->
<property name="hibernate.connection.characterEncoding">utf-8</property>
<!-- 是否根據需要自動建表 -->
<property name="hbm2ddl.auto">update</property>
這樣的話以後我們再自動建表時就會自動將排序規則設置爲utf-8.
重新執行以下就好了。