【发布时间】:2018-02-06 13:01:37
【问题描述】:
例如,我们有一个 Shops 表。每个商店都属于某个国家(现在以 ENUM 形式实施)。现在我不仅需要将商店映射到一个国家,还要映射到那个国家的一个地区。
第一个想法是制作单独的表格国家和地区。 Country 有很多地区,Shop 属于一个地区,并通过它到达 Country。但是,如果我需要能够将 Shop 映射到 Country 而无需指定其区域怎么办?用我的解决方案是不可能的。
第二个想法是使用复杂的 ENUM。像这样:
public enum Location implements ContainsRegion {
FRANCE("France") {
public EnumSet getRegions() {
return EnumSet.allOf(FranceRegions.class);
}
},
GERMANY("Germany") {
public EnumSet getRegions() {
return EnumSet.allOF(GermanyRegions.class);
}
};
private final String country;
private Region region;
public static Location factory(String name) throws IOException {
for(Location c : values()) {
if(c.country.equalsIgnoreCase(name)) {
return c;
}
}
throw new IOException("Unknown country");
}
@JsonCreator
public static Location factory(@JsonProperty("region") Region region, @JsonProperty("name") String name) throws IOException {
Location location = factory(name);
if(isNull(region)) {
return location;
}
if(location.getRegions().contains(region)) {
location.setRegion(region);
return location;
}
throw new IOException("This region is not available for location");
}
}
它适用于 JSON 序列化和反序列化,但我无法将其映射到 db 表?有什么解决办法吗?
最后一个想法是做一个单独的实体Location: 它将包含对 Shop、Country 和 Region 的引用。并将作为@OneToOne 映射到 Shop。在这种情况下,它从 Shop 实体到 Location 实体,我将能够获取/设置国家和地区,如果未指定地区,它可能只是 null。
请告诉我,完成这项任务的最佳方法是什么? 谢谢!
【问题讨论】:
标签: java mysql hibernate jpa enums