0

My application has entities with nameEn and nameDe for english and german. But only english being used now. Since there are so many entities available, I wanted to have a generic class which can return the selected language entries,but for multiple entries my approach didn't work.

 @Entity
 @Table(name="employee")    
 public class Employee  implements java.io.Serializable {
     // Fields
   private Integer id;
   private String nameEn;      
   private String nameDe;    

   //Getter, Setter Methods 
}

@Entity 
@Table(name="address")
public class Address implements 
  java.io.Serializable {

 private String descriptionEn;
 private String descriptionDe;
}

public interface ILabelText {
   String getNameEn();
   String getNameDe();   
   String getDescriptionEn();
   String getDescriptionDe();   
}

public abstract class LabelText implements ILabelText, Serializable {

private static final long serialVersionUID = 1L;

protected String descriptionEn;
protected String descriptionDe;


private Logger log = Logger.getLogger(LabelText.class);
String language = FacesContext.getCurrentInstance().getViewRoot().getLocale().getLanguage();


public String getDescription() {        
    log.info("Language Selected is  " + language);
    if (language.equals("De")) {
        return getDescriptionDe();
    } else {
        return getDescriptionEn();
    }
}

    public String getName() {       
    log.info("Language Selected is  " + language);
    if (language.equals("De")) {
        return getNameDe();
    } else {
        return getNameEn();
    }
}
}


//In Xhtml, based on selected locale, display value accordingly
<h:outputText value="#{emp.getName()}" />
<h:outputText value="#{add.getDescription()}" />
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
techie2k
  • 559
  • 1
  • 6
  • 32

2 Answers2

1

You can create an entity Lang like this

@Entity
public class Lang implements Serializable
{
  @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
  private long id;

  @NotNull
  private String key;

  @NotNull
  private String translation;
}

and use it in your Address like this

@OneToMany(cascade = CascadeType.ALL, fetch=FetchType.EAGER)
@MapKey(name = "key")
protected Map<String, Lang> name;

Then you are able to access the correct language in JSF:

<h:outputText value="#{emp.name[userLocale].translation}" />

The expression userLocale should be resolved to your language key (en, de, ...) or can be hardcoded e.g. #{emp.name['en'].translation}.

Thor
  • 6,607
  • 13
  • 62
  • 96
0

Is more easy you create a table with translations:

e.g: People -> All of your persons PersonTranslations

People | id PersonTranslations | locale; person_id;

then on your Person class you set the language for all attributes on predicate

Person.description (this will search on PersonTranslation using a person_id key, and a locale) some like that PersonTranslation.find(1, 'en');

enter image description here

GTSouza
  • 365
  • 4
  • 16