[Java] Hibernate + MySQL + UTF-8 how-to

If you wonder how to configure your Hibernate to cooperate with MySQL using UTF-8 character encoding – you are in the right place. The problem you may suffer from: you are using other languages than English in your web application and special characters from these languages are not saving properly. For example, instead of Polish characters like “ęóąśłżźć” you get “????????”.
What you need:

  • Hibernate 3
  • MySQL 5
  • Already configured Hibernate + MySQL

Lets begin with creating new class that has to extend org.hibernate.dialect.MySQLDialect :

import org.hibernate.dialect.MySQLDialect;

public class CustomMySQLDialect extends MySQLDialect {

	@Override
	public String getTableTypeString() {
		return " DEFAULT CHARSET=utf8";
	}

}

It is done to create your tables automatically using correct character encoding – UTF-8.

The second part of solution:
1. Add hibernate.connection.characterEncoding property to hibernate.cfg.xml file with value UTF-8 .
2. Set dialect property to newly created com.codesmuggler.CustomMySQLDialect .

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

<hibernate-configuration>
	<session-factory>
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost/DB_NAME_HERE</property>
		<property name="hibernate.connection.username">DB_USERNAME_HERE</property>
		<property name="hibernate.connection.password">DB_PASSWORD_HERE</property>
		<property name="hibernate.connection.pool_size">10</property>
		<property name="show_sql">true</property>
		<property name="dialect">com.codesmuggler.CustomMySQLDialect</property>
		<property name="hibernate.hbm2ddl.auto">create-drop</property>
		<property name="hibernate.connection.characterEncoding">UTF-8</property>
	</session-factory>
</hibernate-configuration>

Another solution:
instead of adding hibernate.connection.characterEncoding in hibernate.cfg.xml configuration file add to value of the property hibernate.connection.url string: ?characterEncoding=UTF-8:

<property name="hibernate.connection.url">jdbc:mysql://localhost/DB_NAME_HERE?characterEncoding=UTF-8</property>

Now you can enjoy with properly coded UTF-8 chars.

This entry was posted in coding, enterprise edition, java, snippets and tagged , , , , . Bookmark the permalink.

Leave a Reply