Search code examples
mysqlmybatisibatis

Unable to print Japanese characters fetched from MySQL using MyBatis


The collation of the column is set to "utf8mb4_general_ci". The data stored under that column is "ベッドルーム". But when I fetch this using MyBatis, and printed it out, the result is "????????\u2030?????????"

my config is this:

<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://domain:port/mydb" />
<property name="username" value="user"/>
<property name="password" value="pass"/>

Then I added character encoding to the url.

<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://domain:port/mydb?useUnicode=yes&amp;characterEncoding=utf8" />
<property name="username" value="user"/>
<property name="password" value="pass"/>

The result became this "??????".

I also tried adding the property driver.encoding

<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://domain:port/mydb" />
<property name="driver.encoding" value="UTF-8" />
<property name="username" value="user"/>
<property name="password" value="pass"/>

Still not able to print out the characters. I don't know where the problem is.


Solution

  • I found out that the problem was due to default encoding of Java. I just changed it upon startup of the program with the following code:

    try 
    {
        Field charset = Charset.class.getDeclaredField("defaultCharset");
        charset.setAccessible(true);
        charset.set(null,null);
    
        System.setProperty("file.encoding","UTF-8");
    } 
    
    catch (Exception e) 
    {
        e.printStackTrace();
    }