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() {
}
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() {
}
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.
source
share