简体   繁体   English

有没有办法用 JPA 存储“扩展枚举”

[英]Is there a way to store "extended enum" with JPA

Is there a way to store "extended enum" with JPA?有没有办法用 JPA 存储“扩展枚举”?
I'm working with abstract object in my spring boot project and my base object can have multiple states.我在我的 spring 引导项目中使用抽象 object,我的基础 object 可以有多个状态。 The object extending it can have the base state but also other specific states.扩展它的 object 可以有基数 state 但也有其他特定的状态。 You can't extend enum in Java, so my I first tought of using an interface with a default method isCommon to discriminate between my common enum values and my extended enum values in my services.您不能在 Java 中扩展enum ,所以我首先想到使用带有默认方法isCommoninterface来区分我的服务中的普通枚举值和扩展枚举值。
However I can't use the annotation @Enumerated on my property anymore.但是我不能再在我的属性上使用注释@Enumerated Is there a way to make it work or another pattern I could use?有没有办法让它工作或我可以使用其他模式?
A small code sample to provide some context:提供一些上下文的小代码示例:

@Entity
abstract class AbstractFoo {
   public StateInterface state;
}

@Entity
class ConcreteFoo extends AbstractFoo {

}

@Service
class ConcreteFooService {
    public boolean isCommonState(ConcreteFoo foo) {
        return foo.state.isCommon();
    }
}

interface StateInterface {
   default boolean isCommon() {
       return false;
   }
}

enum CommonState extends StateInterface {
   BEGIN, END;
   
   @Override
   boolean isCommon() {
      return true;
   }
}

enum SpecificState extends StateInterface {
    MIDDLE;
}

I would suggest you using the following Enum instead:我建议您改用以下枚举:

enum State {
    BEGIN(true), MIDDLE(false), END(true);

    private final boolean common;

    State(boolean common) {
        this.common = common;
    }

    public boolean isCommon() {
       return common;
    }
}

For your use case, this is the best I can think of.对于您的用例,这是我能想到的最好的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM