Hibernate與MySQL開發中亂碼解決方案
Hibernate與MySQL開發中亂碼解決方案
Hibernate與MySQL開發中亂碼解決方案
文章分类:Java编程 关键字: hibernate與mysql開發中亂碼解決方案
本文參考自:
http://blog.tremend.ro/2007/08/14/how-to-set-the-default-charset-to-utf-8-for-create-table-when-using-hibernate-with-java-persistence-annotations/,感謝提供者spostelnicu.
問題:hibernate與mysql開發中,新增和修改時出現中文亂碼
解決:
步驟一:將hibernate.cfg.xml中的connection.url值加入characterEncoding=utf8,具體如下:?
文件:hibernate.cfg.xml內容
Xml代码
- <!DOCTYPE?hibernate-configuration?PUBLIC ??
- ????”-//Hibernate/Hibernate?Configuration?DTD?3.0//EN” ??
- ????”http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”>??
- ??
- ??
- <hibernate-configuration>??
- ??<session-factory>??
- ????<property?name=“hibernate.connection.url”>jdbc:mysql://localhost:3306/hibernate_first?characterEncoding=utf8</property>??
- ????… ??
- ? ??
- ??<session-factory>??
- <hibernate-configuration>??
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_first?characterEncoding=utf8</property> ... <session-factory> <hibernate-configuration>
步驟二:在建表時,一定要將MySQL中的資料表格的欄位字符集設置成utf8的 ,否則會拋出類似如下錯誤:
錯誤訊息:com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column ‘name’ at row 1;
如果是在外部建表,建表語句寫法如下:
Sql代码
- ?????????create?table?`my_table`?( ??