Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring-Boot, Can't save unicode string in MySql using spring-data JPA

I have my application.properties set up like this :

spring.datasource.username = root
spring.datasource.password = root
spring.datasource.url = jdbc:mysql://localhost:3306/dbname?useUnicode=yes&characterEncoding=UTF-8
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

And In my pom.xmlI have property set up like this :

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <start-class>toyanathapi.Application</start-class>
        <java.version>1.8</java.version>
</properties>

My entity : @Entity public class DailyRashifalEntity {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String date;
private int rollno;
private String name;
//Constructors and getters/setters 
}

Problem 1: If I use the above setup I get the exception

java.sql.SQLException: Incorrect string value: '\xE0\xA4\xA7\xE0\xA4\xBE...

Problem 2 : If I change the datasource url into this :

spring.datasource.url = jdbc:mysql://localhost:3306/dbname

The unicodes in my database get saved like this

 29 | 2074-03-04 |        3 | ?????????????? ?????,?????? ??????, ??????????? ????? ? ???? ???? ???? ??????  

enter image description here

How can I save them in Mysql like they are in unicode instead of getting all the unicode data converted into ???????? .

like image 697
erluxman Avatar asked Jun 16 '17 11:06

erluxman


2 Answers

In your /etc/mysql/my.cnf file change the following.

[mysql]
default-character-set=utf8
[mysqld]
character-set-server=utf8
like image 154
amagain Avatar answered Sep 20 '22 22:09

amagain


Keep your hibernate configuration Like this

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

And Change your DB Collation Like this

ALTER TABLE tablename CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

More information : Link

like image 40
Harsha Jayamanna Avatar answered Sep 21 '22 22:09

Harsha Jayamanna