【问题标题】:Saving nested enum to db using JPA使用 JPA 将嵌套枚举保存到数据库
【发布时间】: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


    【解决方案1】:

    这是不可能的,在 JPA 中使用枚举时应该三思。

    请阅读我关于该主题的文章: https://martinelli.ch/2018/01/08/mapping-enums-with-jpa/

    【讨论】:

      【解决方案2】:

      当前 JPA 2.1 不支持映射枚举包含的变量。 我认为第一个解决方案是正确的,在 Shop 内建立 Region 的 ManyToOne 关系,并在 Region 和 country 之间建立 oneToOne 关系,(因此国家会急切地加载 Region 并且您可以随时访问它),您还可以提供区域内的便捷方法,提供国家名称 + 区域或任何对您的业务方便的名称

      【讨论】:

        猜你喜欢
        • 2014-08-07
        • 1970-01-01
        • 2018-04-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-24
        • 1970-01-01
        相关资源
        最近更新 更多