davioooh
davioooh

Reputation: 24706

Persist and object referencing a singleton

I'm working on a JPA project. I have an ExportProfile object:

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

    private String name;

    private ExtractionType type;

    //...

}

ExtractionType is an interface implemented by several classes, each for a different extraction type, these classes are singletons. So type is a reference to a singleton object. I don't have an ExtractionType table in my DB, but i have to persist the extraction type of my export profile.

How can I persist the ExportProfile object using JPA, saving the reference to type object?

NOTE: The number of ExtractionType implementations is not defined, because new implementation can be added anytime. I'm also using Spring, can this help?

Upvotes: 4

Views: 493

Answers (1)

Óscar López
Óscar López

Reputation: 236124

Here's an idea: make an ExtractionTypeEnum, an enumeration with one element for each of the possible singletons that implement ExtractionType, and store it as a field in your entity, instead of ExtractionType . Later on, if you need to to retrieve the singleton corresponding to a ExtractionTypeEnum value, you can implement a factory that returns the correct singleton for each case:

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

In the above, I'm assuming that both ConcreteExtractionType1 and ConcreteExtractionType2 implement ExtractionType.

Upvotes: 1

Related Questions