繁体   English   中英

创建一个具有两个互斥字段的实体

[英]Create an entity with two fields that are mutually exclusive

我想创建一个实体,它有两个相互排斥的字段,即两个字段中只有一个或另一个应该包含一个值。 有没有我可以用来实现这个的注释,还是我需要通过其他方式来做到这一点?

JPA不提供实现互斥字段的机制,但您可以在字段的setter中实现它。 最终实现取决于您想要实现的确切行为。

要明确禁止同时设置2个字段,请使用类似的内容

@Entity
public class MutuallyExclusive1 {
    @Id
    @GeneratedValue
    private int Id;
    private String strValue;
    @Enumerated(EnumType.STRING)
    private MyEnum enumValue;

    public MutuallyExclusive1() {
        // do nothing
    }

    public void setEnum(final MyEnum enumValue) {
        if (strValue != null) {
            throw new IllegalStateException("stgValue and enumValue cannot be populated at the same time!");
        }
        this.enumValue = enumValue;
    }

    public void setString(final String strValue) {
        if (enumValue != null) {
            throw new IllegalStateException("stgValue and enumValue cannot be populated at the same time!");
        }
        this.strValue = strValue;
    }
}

在设置另一个用途时隐式擦除一个值

@Entity
public class MutuallyExclusive2 {
    @Id
    @GeneratedValue
    private int Id;
    private String strValue;
    @Enumerated(EnumType.STRING)
    private MyEnum enumValue;

    public MutuallyExclusive2() {
        // do nothing
    }

    public void setEnum(final MyEnum enumValue) {
        this.strValue = null;
        this.enumValue = enumValue;
    }

    public void setString(final String strValue) {
        this.enumValue = null;
        this.strValue = strValue;
    }
}

无论哪种方式,您都应该记住,互斥性只能由您的实施来强制执行。 这意味着您应该使用上面的setter来对这些字段进行写访问,或者在每个具有写访问权限的方法中实现相同的逻辑。

class Exclusive{

  private String value1 = null;
  private Enum value2 = null;

  public Exclusive(){
   ....
  }

  public void setValue1(String s){
    value1 = s;
    value2 = null;
  }

 public void setValue2(Enum e){
    value2 = e;
    value1 = null;
 }

}

暂无
暂无

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

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