4

我正在做一个 JPA 项目。我有一个ExportProfile对象:

@Entity
public class ExportProfile{
    @Id
    @GeneratedValue
    private int id;

    private String name;

    private ExtractionType type;

    //...

}

ExtractionType是由几个类实现的接口,每个类都有不同的提取类型,这些类是单例。type对单例对象的引用也是如此。我的数据库中没有ExtractionType表,但我必须保留导出配置文件提取类型

如何ExportProfile使用 JPA 持久化对象,保存对type对象的引用?

注意:没有定义实现的数量ExtractionType,因为可以随时添加新的实现。我也在使用Spring,这有帮助吗?

4

1 回答 1

1

这是一个想法:ExtractionTypeEnum为实现 的每个可能的单例创建一个带有一个元素的枚举ExtractionType,并将其作为字段存储在您的实体中,而不是ExtractionType. 稍后,如果您需要检索与某个ExtractionTypeEnum值对应的单例,您可以实现一个工厂,为每种情况返回正确的单例:

public ExtractionType getType(ExportProfile profile) {
    switch (profile.getExtractionTypeEnum()) {
        case ExtractionTypeEnum.TYPE1:
            return ConcreteExtractionType1.getInstance();
        case ExtractionTypeEnum.TYPE2:
            return ConcreteExtractionType2.getInstance();
    }
}

在上面,我假设两者ConcreteExtractionType1ConcreteExtractionType2实现ExtractionType.

于 2012-05-09T13:44:58.887 回答