Java 使用键值对定义枚举
我想在我的表实体类中使用的国家列表如下Java 使用键值对定义枚举,java,enums,Java,Enums,我想在我的表实体类中使用的国家列表如下 package com.danieladenew.webproject.enums; public enum CountryEnum { AMERICA("United States Of America"), UK("United Kingdom"), ; private String name; CountryEnum(String s) { } @Override publi
package com.danieladenew.webproject.enums;
public enum CountryEnum {
AMERICA("United States Of America"),
UK("United Kingdom"),
;
private String name;
CountryEnum(String s) {
}
@Override
public String ToString() {
}
}
@Entity
@Table
public class Exchange
{
@Column(name="COUNTRY OF ORIGIN")
@Enumerated(EnumType.STRING)
private CountryEnum countryofOrigin;
.
.
}
但是,我不明白我怎么能有,例如:
用美国做钥匙
和保存数据时要选择的美利坚合众国?基于此链接:
定义JPA用来访问country属性的getter/setter。请注意,我们将这些方法与getCountryOfOrigin/setCountryOfOrigin方法分开定义,因为它们接受并返回CountryEnum枚举。这些方法与提供程序形成协定,以返回字符串。我们还需要告诉提供者要使用的数据库列名,因为默认列命名规则在这种情况下不起作用
@Access(AccessType.PROPERTY)
@Column(name="COUNTRY OF ORIGIN", length=32)
protected String getDBCountryOfOrigin() {
return countryofOrigin==null ? null : countryofOrigin.name;
}
protected void setDBCountryOfOrigin(String dbValue) {
countryofOrigin = CountryEnum.getName(dbValue);
}
您需要将此方法添加到枚举中
public static CountryEnum getName(String prettyName) {
for (CountryEnum country : values()) {
if (country.name.equals(prettyName)) {
return country;
}
}
return null;
}