Hibernate对mysql操作时的编码问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32847235/article/details/79891670

我的项目中使用的是hibernate框架操作数据库,显示数据库的数据一切正常,但是在执行新增、修改、搜索的时候,中文字符都出现乱码,新增的是乱码的记录,模糊查询的中文搜索查不出来数据。直到我修改完编码格式才恢复正常。
1、用eclipse启动项目时报错,启动超过45秒,无法启动成功

 找到eclipse的工作空间workspace,打开下面的.metadata文件,再找到下面的.plugins文件,找到org.eclipse.wst.server.core文件,打开servers.xml文件
   文件中有个属性   start-timeout="45" 代表启动如果超过45秒,就会报错。可以修改到更大的数值,如150或者200秒
2、要修改eclipse中的编码格式
       file--properies----Resource中有一个编码格式:other修改为utf8
       右键单击项目---properties---Resource/Java Build Path/Java Compiler
      Window----preferences-----General和XML都要选择编码格式,General下面的workspace
3、修改数据库的编码格式 
     新建数据库的时候编码格式选择utf8,排序规则选择utf8_general_ci
4、修改mysql的安装文件my.ini中的编码格式,默认为latin1

     打开mysql的安装目录,找到my.ini或者my_default.ini

 新版本的mysql可能在mysql安装目录下没有my.ini文件,安装到了另外一个目录下,找到c:ProgramData---mysql--mysql Server 5.7,下面就有。
    在[client]下添加: default-character-set=utf8
    在[mysqld]下添加:default-character-set=utf8
或者修改default-character-set=utf8
5、修改项目中连接数据库的配置文件的编码格式
    在jdbc.properties中配置jdbc.url=jdbc:mysql://localhost:3306/nsfw?useUnicode=true&characterEncoding=UTF-8
要加上后面的编码格式
6、修改hibernate配置文件中的编码格式hibernate.cfg.xml
  在connection.url后面也要加上编码格式
  <property name="connection.url">
         jdbc:mysql://localhost:3306/tansinglepage?useUnicode=true&amp;characterEncoding=UTF-8
     </property>

或者: <!-- 设置编码格式 -->
  <property name="hibernate.connection.useUnicode">true</property> 
  <property name="hibernate.connection.characterEncoding">UTF-8</property>

<!-- 配置方言 -->
  <property name="hibernate.dialect">com.shzy.dialect.CustomerDialect</property>

重启项目  别忘了url后面加的?useUnicode=true&amp;characterEncoding=utf8

 

   
    


        

   

猜你喜欢

转载自blog.csdn.net/qq_32847235/article/details/79891670