Spring Boot – Localization (i18n) with Spring Boot Using Database Data

internationalizationjavaspring-mvc

I am writing a Spring boot app with Thymeleaf, which should support two languages (or more). I have set up the locale resolver and messages.properties so now my app can translate static messages on locale change.

The problem is, because there is some data in my MySQL database that have text in it (for example, description of a product). I would need this data translated as well.

So, my question is, what is the best approach for this?
Duplicate all the entries, have two tables, have two separate app for each language?

Best Answer

I managed to solve the problem on my own:

First, i created entities:

Product (id, name, price, description)

Language (id, lang)

Product_t (id, prod_id, lang_id, name, description)

then I created function on database:

FUNCTION `getLangOrder`(language INTEGER, locale varchar(5)) RETURNS int(11)
BEGIN
    case language 
        when (select id from language where lang=locale) then return 1; 
        when 2 then return 2;
        when 1 then return 3;
        else return 4;
    end case;
RETURN 5;
END

This function orders my translations by given specified locale first (if null it defaults) and if that is missing in order I defined (English(2), Slovenian(1), German(3))

Then in my repository instead of using JPA's default findAll() function I defined my own query:

select p.id
, ifnull((select t.description 
                  from product_t t where t.prod_id = p.id 
                  order by getLangOrder(lang_id, @lang) limit 1)
          , p.description 
  ) as description 
, ifnull((select t.name 
                 from product_t t where t.prod_id = p.proj_id 
                 order by getLangOrder(lang_id, @lang) limit 1)
          , p.name
  ) as name
, p.price 
from product p

where @lang is my passed argument (locale read from cookie)

Which then created list with entities Product, where name and description where translated.

Related Topic