A persistent and an object referencing a singleton

I am 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 type of extraction, these classes are single. Thus, type is a reference to a singleton object. I do not have an ExtractionType table in my database, but I need to save the extraction type of my export profile.

How can I save an ExportProfile object using JPA while maintaining a reference to the type object?

NOTE. The number of ExtractionType implementations is undefined, since a new implementation can be added at any time. I also use Spring, can this help?

+4
source share
1 answer

Here's the idea: do an ExtractionTypeEnum , an enumeration with one element for each of the possible singletons that implement ExtractionType , and save it as a field in your entity instead of ExtractionType . Later, if you need to extract a singleton corresponding to the value of ExtractionTypeEnum , you can implement a factory that will return 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 example, I assume that ConcreteExtractionType1 and ConcreteExtractionType2 implement ExtractionType .

+1
source

Source: https://habr.com/ru/post/1411522/


All Articles