Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set useUnicode=true and characterEncoding=utf8 properties on Spring-managed MySQL JDBC connection

Tags:

I'm currently building a Spring MVC webapp and the database is the vital backend part. For whatever reason, however, Spring is refusing to process the data as UTF-8. Since the views, resources and browsers are set to Unicode, and so are the tables in the database (and also reading quite a few similar questions asked), I have established that the problem lies in the database connection.

The JDBC Driver should be provided two items in connectionProperties: useUnicode (set to yes and characterEncoding (set to utf8). It turns out, however, it's impossible.

JDBC is a bean, and as such is configured via an XML file, like so:

<property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/<database>" /> <property name="username" value="<not telling>" /> <property name="password" value="<not telling>" /> 

This setup converts all non-alphanumeric characters pulled from the database (such as arrows or Greek letters) into question marks. Which is, obviously, unacceptable.

I tried multiple solutions: specified the JDBC URL as jdbc:mysql://localhost:3306/<database>?useUnicode=yes&amp;characterEncoding=utf8, played with my.ini file (and MySQL Workbench) to force everything in the database to default to utf8 charset, and something that caused the largest headache: adding <property name="connectionProperties" value="useUnicode=yes;characterEncoding=utf8" />. Turns out, it's literally impossible to set two connectionProperties within a single bean, because... there is no separating character mentioned anywhere (the bean will attempt to read it as trying to set yes;characterEncoding=utf8 as the value of useUnicode). So my question is: how does I utf8?

like image 223
Haxton Fale Avatar asked Sep 27 '13 13:09

Haxton Fale


2 Answers

The problem may be caused by specifying utf8 and not UTF-8. From Using Character Sets and Unicode:

When specifying character encodings on the client side, use Java-style names. The following table lists MySQL character set names and the corresponding Java-style names...

and utf8 maps to UTF-8. Try the following JDBC URL:

jdbc:mysql://localhost:3306/?useUnicode=yes&characterEncoding=UTF-8

like image 188
hmjd Avatar answered Oct 04 '22 10:10

hmjd


Note that if you are using Spring Boot, you can do this using properties within application.properties instead of having to add extra parameters to your connection strings:

Put this into application.properties:

spring.datasource.connectionProperties=useUnicode=true;characterEncoding=utf-8; 
like image 37
Conor O'Neill Avatar answered Oct 04 '22 09:10

Conor O'Neill