Marian Klühspies
Marian Klühspies

Reputation: 17637

Localization of entity fields in Spring Hibernate

I have two entities with fields that I´d like to localize. However, I´m not sure how to implement that correctly, because I would need to have a reference to the entities as well as a reference to the field that is translated, in order to have a shared "i18n" table.

@Entity
public class EntityA {

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private List<Translation> name;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private List<Translation> description;

}

Second entity

@Entity
public class EntityB {

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private List<Translation> name;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private List<Translation> shortDescription;

}

Translation Entity

@Entity
@Table(name = "i18n")
public class Translation {

    private String languageCode;
    private String translation;

    //private String referenceToEntity
    //private String referenceToField


}

Is there a given way to enable internationalization on entity fields in Spring or at least some kind of workaround to make it working without too much overhead?

EDIT

I´ve written a short post about how I solved it using XmlAnyAttribute https://overflowed.dev/blog/dynamical-xml-attributes-with-jaxb/

Upvotes: 1

Views: 1986

Answers (2)

Ali Al-kubaisi
Ali Al-kubaisi

Reputation: 100

this tutorial helped me a lot. i hope it will help you too. i used the second way and it's work perfectly.Localized Data – How to Map It With Hibernate

Upvotes: 1

Gabriel Robaina
Gabriel Robaina

Reputation: 741

I did some research and found this @Convert JPA annotation. You would need to encapsulate the name and description properties into an object (that implements AttributeConverter), and use a convertion class to specify how it will be translated when persisted, and how will it be translated when retreived.

To execute translations on persistence and retrieval, you can consume Google translate's API.

Here:

@Entity
public class EntityA {

    @Convert(converter = DescriptionConverter.class)
    private Description description

    // getters and setters

},

The encapsulated object, something like:

public class Description {

    private String name;

    private String language;

    private String description;

    // Getters and Setters.

}

And the translation applies here:

@Converter
public class DescriptionConverter implements AttributeConverter<Description, String> {

    @Override
    public String convertToDatabaseColumn(Description description) {
        // consume Google API to persist.
    }

    @Override
    public Document convertToEntityAttribute(String description) {
        // consume Google API to retrieve.
    }

}

Upvotes: 1

Related Questions