21

I have a simple web application where I use JPA.

I have an entity called BlogEntry.

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

For example

em.persist(entity);

In this line, if I debug for example:

entity.getTitle()

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

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

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

Why might this be?

Regards.

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>
Koray Tugay
  • 22,894
  • 45
  • 188
  • 319

4 Answers4

44

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"/>
muthukumar
  • 2,233
  • 3
  • 23
  • 30
  • remember to escape any special characters, as below: `spring.datasource.url=jdbc\:mysql\://localhost\:3306/blogdatabase\?useUnicode=true\&characterEncoding=utf\-8\&characterSetResults=utf\-8` – vijay Oct 07 '17 at 10:17
18

This helped in Spring Boot:

spring.datasource.url=jdbc:mysql://localhost:3306/securitydb?useUnicode=yes&characterEncoding=UTF-8
ACV
  • 9,964
  • 5
  • 76
  • 81
13

This solved it nicely:

<property name="hibernate.connection.useUnicode" value="true" />
<property name="hibernate.connection.characterEncoding" value="UTF-8" />

Edit: with hibernate 4.3.1 this works:

<property name="connection.useUnicode">true</property>
<property name="connection.characterEncoding">utf-8</property>
Koray Tugay
  • 22,894
  • 45
  • 188
  • 319
0

Another common mistake can be the wrong encoding of the database. If you just cerated the database without the correct encoding this error can also be a result. use

create database mydb character set utf8 collate utf8_general_ci;

instead of

create database mydb;
Julz
  • 103
  • 1
  • 7