JPA utf-8字符未保留

问题描述:

我有一个使用JPA的简单Web应用程序.

I have a simple web application where I use JPA.

我有一个名为 BlogEntry 的实体.

I have an entity called BlogEntry.

当我提交新的BlogEntry时,在调试应用程序时,我看到utf8字符就很好了.

When I submit a new BlogEntry, when I debug my application I see the utf8 characters just fine.

例如

em.persist(entity);

在这一行中,如果我调试例如:

In this line, if I debug for example:

entity.getTitle()

我可以在IDE中成功看到utf-8字符. (如ğğ或çç)

I can successfuly see utf-8 characters in the IDE. ( like ğğ, or çç )

此外,我的数据库具有UTF8排序规则,我可以使用"INSERT INTO ..."之类的sql插入utf-8字符

Also, my database has UTF8 collation and I can insert utf-8 characters just fine with sql using like "INSERT INTO..."

但是,在JPA中,字符保留为????

However, with JPA, the characters are persisted as ????

为什么会这样?

致谢.

这是我的persistence.xml:

Here is my persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
    <persistence-unit name="Persistence">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>com.tugay.blog.core.model.Blogentry</class>
        <properties>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/blogdatabase"/>
            <property name="javax.persistence.jdbc.user" value="root"/>
            <property name="javax.persistence.jdbc.password" value="aabbccdd"/>
        </properties>
    </persistence-unit>
</persistence>

在persistence.xml文件的属性中使用字符编码

use the character encoding in the property of persistence.xml file

<property name="javax.persistence.jdbc.url" 
   value="jdbc:mysql://localhost:3306/blogdatabase?useUnicode=yes&amp;characterEncoding=UTF-8"/>