Is it possible to override the Field constraint on a field in a child class

426 views Asked by At

I have a parent class lets call it Parent

public class Parent {

@Basic(optional = false)
String stringOne;

@Basic(optional = false)
String stringTwo;

    public String getStringOne() {
        return stringOne;
    }
    public void setStringOne(String stringOne) {
        this.stringOne = stringOne;
    }
    public String getStringTwo() {
        return stringTwo;
    }
    public void setStringTwo(String parentTwo) {
        this.stringTwo = parentTwo;
    }
}

Then there are around 10 child classes, here is one of them

public class ChildOne extends Parent{
     @Override
     public String getStringOne() {
        return stringOne;
    }
     @Override
    public String getStringTwo() {
        return stringTwo;
    }
}

I know I cannot override the instance variables but is it possible to remove the constraint on the child class. For e.g. I would like the childOne class object to have null stringOne or null stringTwo if I want to. But other 9 child objects can have the constraint from parent class.

Most important part is that I cannot have the parent as an abstract. I am really sorry for this late edit.

1

There are 1 answers

4
Tea Curran On

I believe what you want is a Mapped Superclass. Make sure you put the annotations on your getters rather than the properties itself.

@MappedSuperclass
public abstract class Parent {

    String stringOne;

    String stringTwo;

    @Basic(optional = false)
    public String getStringOne() {
        return stringOne;
    }

    @Basic(optional = false)
    public String getStringTwo() {
        return stringTwo;
    }

    /* setters here */
}

@Entity
@Table(name="child_one")
public class ChildOne extends Parent{

    @Override
    @Basic(optional = true)
    public String getStringOne() {
        return stringOne;
    }

    @Override
    @Basic(optional = true)
    public String getStringTwo() {
        return stringTwo;
    }

    /* setters here */
}