2012-07-15 18 views
0

我的應用程序具有name和nameDe的英文和德文實體。但現在只使用英語。由於有太多的實體可用,我想要一個可以返回所選語言條目的泛型類,但對於多個條目,我的方法不起作用。來自db的多語言支持數據

@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()}" /> 
+1

請仔細閱讀您熟悉的主題 - http://stackoverflow.com/questions/19295/database-backed-i18n-for-java-web-app – 2012-07-15 18:20:44

回答

1

您可以創建一個實體Lang這樣

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

    @NotNull 
    private String key; 

    @NotNull 
    private String translation; 
} 

,並用它在你的Address這樣

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

然後你能夠訪問正確的語言在JSF :

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

表達式userLocale應該解析爲您的語言密鑰(en,de,...),或者可以對其進行硬編碼。 #{emp.name['en'].translation}

0

更便於您創建翻譯表:

e.g: 人物 - >所有你的人的 PersonTranslations

人物|編號 PersonTranslations |區域;爲person_id;

然後在你的Person類設置了語言上的謂詞

Person.description所有屬性(這將使用爲person_id鍵上PersonTranslation搜索,語言環境) 一些像PersonTranslation.find(1,成 'en');

enter image description here