Saving emojis in your application using grails or java and mysql database
Posted By : Shakil Pathan | 30-Sep-2015
Hi,
In this blog I am going to explain you about saving emojis in your application using grails/java and mysql database.
In one of my project, I have to store emoticons in the database using java/grails application. By default mysql allow user to save utf-8 character encoding which is store in database as 3 byte encoding but emojis require 4 byte encoding to store in the database, so we have to change our database configuration for successfully storing the emojis in the database.
First of all we have to do some configuration in our mysql conf file that is "/etc/my.cnf"
[client]
default-character-set = utf8mb4
[mysql]
default-character-set = utf8mb4
[mysqld]
character-set-client-handshake = FALSE
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci
After saving the file we have to restart our mysql server for the changes.
After that we have to change our database character set and collate for using utf8mb4
ALTER DATABASE databaseName CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
We also need to change table also for successfully saving the data in that table
ALTER TABLE tableName CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Thats it with the mysql configuration to save the data correctly into the database.
Then to saving and showing the data correctly in the database we have to run the following commands
SET NAMES utf8mb4;
then updating the table with the emojis
update tableName set content='??';
So it saves the data correctly in the database.
Now, how we can save the emojis using our grails/java application, so here is the groovy code
def connection = sessionFactory.currentSession.connection()
connection.createStatement().execute("SET NAMES utf8mb4");
which creates the connection for utf8mb4 encoding and saves the emojis successfully in the database.
Hope it helps!
THANKS
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Shakil Pathan
Shakil is an experienced Groovy and Grails developer . He has also worked extensively on developing STB applications using NetGem .