数据库通过hibernate自动的写入entity类。但是插入到mysql数据库时,出现中文乱码问题。我把所有涉及到的文件都修改成utf8编码,但是还是无效。
昨晚自己认为是mysql的问题,搞了好久,还是没解决。今天早上,灵机一动,想:也许是hibernate的问题。就上网搜‘hibernate mysql编码问题’,果然解决了,好开心啊。
同时也再想,我们遇到的问题,其实有很多解决办法,只是我们找错了解决方向。
下面我贴出答案,同时感谢网友,脚本之家
hibernate.cfg.xml加上属性.
<property name="connection.useUnicode">true</property>
<property name="connection.characterEncoding">UTF-8</property>
mysql 的驱动用3.0.15以上版本的,
加个Filter, 使用UTF-8字符集就可以了,
若使用Spring则写在spring中的sessionFactory里即可。
例如:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="connection.username">root</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/hibernate_table
</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="myeclipse.connection.profile">
mySql hibernatetable
</property>
<property name="connection.password">12345678</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.useUnicode">true</property>
<property name="connection.characterEncoding">UTF-8</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<mapping resource="cn/com/hibernate/Demo/Guestbook.hbm.xml" />
<mapping resource="cn/com/hibernate/Demo/GMapping.hbm.xml" />