简体   繁体   English

是否可以覆盖子类中字段的Field约束

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

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 然后大约有10个孩子课堂,这是其中之一

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 eg I would like the childOne class object to have null stringOne or null stringTwo if I want to. 例如,如果我愿意,我希望childOne类对象具有null stringOne或null stringTwo。 But other 9 child objects can have the constraint from parent class. 但是其他9个子对象可以具有父类的约束。

Most important part is that I cannot have the parent as an abstract. 最重要的部分是我不能将父母作为摘要。 I am really sorry for this late edit. 对于这次后期编辑,我感到非常抱歉。

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 */
}

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

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