简体   繁体   English

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

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

I would like to create an entity which has two fields that are mutually exclusive ie only one or the other of the two fields should contain a value. 我想创建一个实体,它有两个相互排斥的字段,即两个字段中只有一个或另一个应该包含一个值。 Is there an annotation I can use to achieve this or do I need to do this by some other means? 有没有我可以用来实现这个的注释,还是我需要通过其他方式来做到这一点?

JPA doesn't provide mechanism to implement mutual exclusive fields, but you can implement this in fields' setters. JPA不提供实现互斥字段的机制,但您可以在字段的setter中实现它。 The final implementation depends on what exact behavior you want to achieve. 最终实现取决于您想要实现的确切行为。

To explicitly disallow having 2 fields set at the same time use something like 要明确禁止同时设置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;
    }
}

To implicitly erase one value while setting another use 在设置另一个用途时隐式擦除一个值

@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;
    }
}

Either way you should keep in mind that mutually exclusiveness is enforced only by your implementation. 无论哪种方式,您都应该记住,互斥性只能由您的实施来强制执行。 That means you should either use only the setters above for write access to these fields or implement the same logic in every method having write access to them. 这意味着您应该使用上面的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