Saving map <Locale, String> using JPA

What is the easiest way to save an attribute Map<Locale,String>using JPA annotations? The application I'm working on should store multilingual text - this is (essentially) the same text, but written in several languages.

Note that for a large number of objects, this type of attribute is required (and several such attributes for the object). Therefore, the solution should be easily replicable, rather than copying the paste and gobs code for each object.

To illustrate, an application will need to store data for these purposes: enter image description here

(note that the same element is written in five languages)

+4
source share
1

, . , , , language → . hashmap, , .

@Embeddable
public class LocalizedString {

    private String language;
    private String text;

    public LocalizedString() {}

    public LocalizedString(String language, String text) {
        this.language = language;
       this.text = text;
    }

    // auto-generated getters, setters, hashCode(), equals(), etc.
} 



@Entity
@Table(schema = "app", name = "mling_str")
public class MultilingualString {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name = "string_id")
    private long id;

    @ElementCollection(fetch = FetchType.EAGER)
    @MapKey(name = "language")
    @CollectionTable(schema = "app", name = "ming_str_map", 
                 joinColumns = @JoinColumn(name = "string_id"))
    private Map<String, LocalizedString> map = new HashMap<String, LocalizedString>();

    public MultilingualString() {}

    public MultilingualString(String lang, String text) {
        addText(lang, text);
    }

    public void addText(String lang, String text) {
        map.put(lang, new LocalizedString(lang, text));
    }

    public String getText(String lang) {
        if (map.containsKey(lang)) {
           return map.get(lang).getText();
        }
        return null;
    }

    // auto-generated getters, setters, hashCode(), equals(), etc.
}
+2

All Articles