Hibernate + MySQL: How to set the encoding utf-8 for database and tables
You can also create databases with encoding.
Simply use phpMyAdmin
for the database/table creation.
There are some URL parameters you would specify in the URL of the hibernate settings to have the connection using UTF8:
<!-- Database Settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- for performance reasons changed to MyISAM from org.hibernate.dialect.MySQLInnoDBDialect -->
<property name="dialect">org.openmeetings.app.hibernate.utils.MySQL5MyISAMDialect</property>
<property name="connection.url">jdbc:mysql://localhost/openmeetings?autoReconnect=true&useUnicode=true&createDatabaseIfNotExist=true&characterEncoding=utf-8</property>
<property name="hibernate.connection.CharSet">utf8</property>
<property name="hibernate.connection.characterEncoding">utf8</property>
<property name="hibernate.connection.useUnicode">true</property>
You don't need to set the whole encoding in the database to utf8 Only if you are using
<!-- Database Scheme Auto Update -->
<property name="hbm2ddl.auto">update</property>
You WILL have to set the default encoding of MySQL to utf8. Cause the hbm2dll
will use the default encoding of the database.
You might still use hbm2ddl.auto
, and modify the table's of the database manually to have utf8 collation.
If you are not using hbm2ddl.auto
, you can simply create the tables with your favorite encoding.
No need to set the database to a special encoding.
Sebastian
Consider changing the connection url configuration like this:
<property name="hibernate.connection.url">
jdbc:mysql://localhost/yourdatabase?UseUnicode=true&characterEncoding=utf8
</property>
It solves the case.
How to change the encoding to UTF-8?
I used a local dialect class that extended the MySQLDialect
and changed the table-type string:
public class LocalMysqlDialect extends MySQLDialect {
@Override
public String getTableTypeString() {
return " DEFAULT CHARSET=utf8";
}
}
I was actually extending the MySQL5InnoDBDialect
type so I was really using:
public class LocalMysqlDialect extends MySQL5InnoDBDialect {
@Override
public String getTableTypeString() {
return " ENGINE=InnoDB DEFAULT CHARSET=utf8";
}
}