Create an object with two fields that are mutually exclusive

I would like to create an object that has two fields that are mutually exclusive, i.e. only one or the other of the two fields must contain a value. Is there an annotation that I can use to achieve this, or do I need to do this using other means?

+4
source share
2 answers

JPA does not provide a mechanism for implementing mutually exclusive fields, but you can implement this in the field settings. The final implementation depends on what exact behavior you want to achieve.

To explicitly ban two fields set at the same time, use something like

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

In any case, you should keep in mind that mutual exclusivity is provided only by your implementation. This means that you should either use only the installers above for write access to these fields, or implement the same logic for each method that has write access.

+2
source
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;
 }

}
+1
source

All Articles