hibernate mysql写入中文乱码 解决

hibernate mysql写入中文乱码 解决

启动hibernate项目,自动创建表,插入数据之后发现写入表里的数据里的中文是乱码。按如下方法解决了:

  1. 修改数据库的字符集为UTF-8,这个可以通过mysql的客户端软件里右键要修改的数据库的属性更改。

  2. 修改Client默认字符集为UTF8。windows下在mysql安装目录(我的计算机操作系统是Windows 7 64,默认的安装路径在:C:\Program Files (x86)\MySQL\MySQL Server 5.0)下找到my.ini,将里面的default-character-set=latin1 改为default-character-set=UTF8,然后重起mysql服务即可将数据库默认字符集改为utf8。

  3. 在项目的hibernate的配置文件hibernate.cfg.xml里修改name为“hibernate.connection.url"的property的值为:jdbc:mysql://localhost:3306/tdm?useUnicode=true&characterEncoding=UTF-8,其中tdm为数据库的名称。

  4. 然后启动项目,执行代码,插入的中文就不会是乱码了。

    &amp”是什么意思?
    "&"就是'&'
    只是在HTML中的&用&来表示

    比如你要得到'&nbsp'的字符串,而不是空格,那就用&nbsp

    XML有5个转义符: < >& " '

直接用&连接的话,报错如下

正确配置如下:

hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">
            jdbc:mysql://localhost:3306/hib2019?useUnicode=true&amp;characterEncoding=UTF-8
        </property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password"></property>
        
        <property name="hbm2ddl.auto">update</property>
        <property name="show_sql">true</property>
        
        <mapping resource="com/jxq/model/User.hbm.xml" />
    </session-factory>

</hibernate-configuration>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章