使用hibernate3从mysql检索utf-8字符串的问题

时间:2011-09-04 17:58:14

标签: java mysql database hibernate utf-8

当我尝试从mysql数据库加载一个对象(一行)时,字符串属性未正确加载,因此当我打印它们时,没有显示任何内容。

这是我的hibernate配置文件:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM 
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>    
    <property name="connection.driver_class">
       com.mysql.jdbc.Driver
    </property>
    <property name="connection.url">
      jdbc:mysql://localhost:3306/demo_hib_1
    </property>
    <property name="connection.username">root</property>
    <property name="connection.password"> </property>
    <property name="pool_size">5</property>
    <property name="show_sql">true</property>
    <property name="dialect">
      org.hibernate.dialect.MySQLDialect
    </property>
    <!-- Mapping files -->

     <mapping resource="com/navid/Person.hbm.xml"/>

  </session-factory>
</hibernate-configuration>

我尝试向连接网址添加编码:

jdbc:mysql://localhost:3306/demo_hib_1&characterEncoding=UTF-8

并获得了hibernate异常:

Exception in thread "main" org.hibernate.HibernateException: Could not parse configuration: /hibernate.cfg.xml
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2246)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:2158)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:2137)
    at com.navid.Main.main(Main.java:31)
Caused by: org.dom4j.DocumentException: Error on line 10 of document  : The reference to entity "characterEncoding" must end with the ';' delimiter. Nested exception: The reference to entity "characterEncoding" must end with the ';' delimiter.
    at org.dom4j.io.SAXReader.read(SAXReader.java:482)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2238)
    ... 3 more

2 个答案:

答案 0 :(得分:9)

hibernate配置文件是一个XML文件,所以原始&amp;不允许使用符号

我想到的两个选项(但未经测试!),第一个是使用XML &amp;转义序列:

<property name="connection.url">
  jdbc:mysql://localhost:3306/demo_hib_1?useUnicode=true&amp;characterEncoding=UTF-8
</property>

或使用名称+值语法,这不需要&amp;逸出:

<property name="connection.url" value="jdbc:mysql://localhost:3306/demo_hib_1?useUnicode=true&characterEncoding=UTF-8" />

请注意,我也添加了第二个选项,我认为你需要两个选项

答案 1 :(得分:0)

您是否尝试添加

<property name="connection.characterEncoding">UTF-8</property>

到会话工厂配置。

来自Hibernate文档:

  

可以通过预先添加&#34; hibernate.connection&#34;来提供任意连接属性。到连接属性名称。例如,您可以使用hibernate.connection.charSet指定charSet连接属性。