[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 {

        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 .


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:


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

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

Leave a Reply

Your email address will not be published. Required fields are marked *



You may use these HTML tags and attributes: