I got a problem is CAN NOT save unicode string to MySQL database when using Hibernate 4.

I tried multiple solutions: specified the JDBC URL as jdbc:mysql://localhost:3306/[database_name]?useUnicode=yes&characterEncoding=utf8, played with my.ini file to force everything in the database to default to utf8 charset. But its not worked!

The JDBC Driver should be provided two items in connectionProperties: useUnicode (set to yes and characterEncoding (set to utf8).

In the file applicationContext.xml i followed the suggestion at http://stackoverflow.com/a/19052883/1896897

        <property name="connectionProperties">
            <props>
                <prop key="useUnicode">yes</prop>
                <prop key="characterEncoding">utf8</prop>
            </props>
        </property>

And it works for me !

This is full of my applicationContext.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
            </list>
        </property>
    </bean>
    
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="connectionProperties">
            <props>
                <prop key="useUnicode">yes</prop>
                <prop key="characterEncoding">utf8</prop>
            </props>
        </property>
    </bean>

</beans>

Hope this help !

Link Reference

About The Author