RK1
RK1

Reputation: 439

Hibernate doesn't encode UTF-8 when persisting objects to MySQL database

I'm creating a Spring MVC web application. Objects persisted by Hibernate to MySQL database are encoded wrongly. The data is coming from a .jsp page form, and is passed to a controller method using POST method.

I already tried applying solutions proposed here and here, but they don't seem to work.

This is the header I'm using on my JSP pages:

<%@page language="Java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

This is the database configuration file I'm using in my application:

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/database?useUnicode=yes&amp;characterEncoding=UTF-8
jdbc.username=root
jdbc.password=password

hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.hbm2ddl.auto=update
hibernate.show_sql=false
hibernate.format_sql=true

I also added a UTF-8 filter in my web.xml file:

<filter>
    <filter-name>SetCharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>SetCharacterEncodingFilter</filter-name>
    <url-pattern>*</url-pattern>
</filter-mapping>

I also tried to change collation of my database by running a command in MySQL Workbench (tried utf8, utf8_unicode_ci, utf8_polish_ci). I tried to change collation of only one table (the one containing UTF-8 string), too.

None of this works. UTF-8 characters are stored as "?". I know the error is occuring while persisting the object, because I print the object in my console before persisting, and UTF-8 is displayed correctly. So I assume the problem lies in the Hibernate configuration and/or MySQL database configuration.

I will provide additional configuration files, should that be necessary.

Here's the CREATE statement for the table involved:

CREATE TABLE `table` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `string` varchar(255) CHARACTER SET utf8 COLLATE utf8_polish_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

Upvotes: 0

Views: 2329

Answers (1)

hd1
hd1

Reputation: 34657

Do you have the collation set properly on mysql? It can be checked using the following statements:

show variables like 'character%';
show variables like 'collation%';

To allow unicode to be used on mysql server:

[mysqld]
character-set-server = utf8
character-set-filesystem = utf8

Hope that helps.

Upvotes: 2

Related Questions